calmlens 0.1.1

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
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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
//! The async [`ServerClient`].
use crate::error::{invalid_argument, invalid_config, invalid_payload, ErrorCode};
use crate::models::*;
use crate::transport::{
    decode, execute, stream_error, upload_body, uuid, CallOptions, Exchange, Prepared, Transport,
};
use crate::{Error, Result};
use bytes::Bytes;
use futures_util::{stream::BoxStream, StreamExt, TryStreamExt};
use http::{HeaderMap, HeaderValue, Method, StatusCode};
use serde::Serialize;
use std::{
    collections::HashMap,
    fmt,
    sync::{Arc, Mutex},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

/// The production API base URL.
pub const DEFAULT_BASE_URL: &str = "https://api.calmlens.com/v1";
/// The production CDN base URL.
pub const DEFAULT_CDN_BASE_URL: &str = "https://cdn.calmlens.com/v1";
/// The most lens definitions [`ServerClient::ensure_lenses`] sends in one request.
pub const ENSURE_LENSES_MAX_PER_REQUEST: usize = 100;
const MIN_PART: u64 = 5 * 1024 * 1024;
const DECISION_POLL_FIRST_DELAY: Duration = Duration::from_millis(500);
const DECISION_POLL_MAX_DELAY: Duration = Duration::from_secs(5);
const DEFAULT_DECISION_TIMEOUT: Duration = Duration::from_secs(60);

/// Configures a [`ServerClient`]. Create it with [`ServerClient::builder`].
///
/// Defaults: a 60-second `timeout` for API calls, no whole-request timeout for uploads and
/// CDN downloads, a 10-second `connect_timeout`, a 60-second `read_timeout` between response
/// bytes, and 2 retries of repeatable requests.
#[derive(Clone)]
pub struct ServerClientBuilder {
    api_key: String,
    project_id: String,
    base_url: String,
    cdn_base_url: String,
    timeout: Duration,
    connect_timeout: Duration,
    read_timeout: Duration,
    max_retries: u32,
    http_client: Option<reqwest::Client>,
}

impl fmt::Debug for ServerClientBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServerClientBuilder")
            .field("api_key", &"[redacted]")
            .field("project_id", &self.project_id)
            .field("base_url", &self.base_url)
            .field("cdn_base_url", &self.cdn_base_url)
            .field("timeout", &self.timeout)
            .field("connect_timeout", &self.connect_timeout)
            .field("read_timeout", &self.read_timeout)
            .field("max_retries", &self.max_retries)
            .field("http_client", &self.http_client.is_some())
            .finish()
    }
}

impl ServerClientBuilder {
    pub(crate) fn new(api_key: String, project_id: String) -> Self {
        Self {
            api_key,
            project_id,
            base_url: DEFAULT_BASE_URL.into(),
            cdn_base_url: DEFAULT_CDN_BASE_URL.into(),
            timeout: Duration::from_secs(60),
            connect_timeout: Duration::from_secs(10),
            read_timeout: Duration::from_secs(60),
            max_retries: 2,
            http_client: None,
        }
    }
    /// The API base URL, e.g. `http://localhost:6110/v1` for a local CalmLens.
    pub fn base_url(mut self, value: impl Into<String>) -> Self {
        self.base_url = value.into();
        self
    }
    /// The CDN base URL.
    pub fn cdn_base_url(mut self, value: impl Into<String>) -> Self {
        self.cdn_base_url = value.into();
        self
    }
    /// The whole-request timeout for API calls (60 seconds by default). Uploads and CDN
    /// downloads have none, so large transfers are not cut off; bound them with
    /// [`ServerClient::with_timeout`] or rely on `read_timeout`.
    pub fn timeout(mut self, value: Duration) -> Self {
        self.timeout = value;
        self
    }
    /// The timeout for establishing a connection (10 seconds by default).
    pub fn connect_timeout(mut self, value: Duration) -> Self {
        self.connect_timeout = value;
        self
    }
    /// The longest wait for the next response bytes, for every request including CDN streams
    /// (60 seconds by default).
    pub fn read_timeout(mut self, value: Duration) -> Self {
        self.read_timeout = value;
        self
    }
    /// How many times to retry a repeatable request (2 by default; 0 disables retries).
    ///
    /// GET and HEAD requests and POSTs carrying an `Idempotency-Key` (uploads and parts) are
    /// retried after transport failures and timeouts, `429`, `502`, `503`, `504` and
    /// `idempotency/request-in-progress`, waiting for `Retry-After` when the server sends one
    /// and otherwise for a jittered exponential backoff. Uploads from readers and streams are
    /// sent once.
    pub fn max_retries(mut self, value: u32) -> Self {
        self.max_retries = value;
        self
    }
    /// Sends requests through your own reqwest client, e.g. for a proxy, custom root
    /// certificates or a shared connection pool. Its own timeouts and redirect policy apply
    /// instead of `connect_timeout` and `read_timeout`; disable redirects on it.
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http_client = Some(client);
        self
    }
    /// Validates the options and creates the client. Fails with `sdk/invalid-config`.
    pub fn build(self) -> Result<ServerClient> {
        let config = self.validate()?;
        let http = match self.http_client {
            Some(client) => client,
            None => reqwest::Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .connect_timeout(self.connect_timeout)
                .read_timeout(self.read_timeout)
                .build()
                .map_err(|cause| {
                    invalid_config(format!("Could not create the HTTP client: {cause}"))
                        .with_source(cause)
                })?,
        };
        Ok(ServerClient::from_parts(config, Transport::Http(http)))
    }
    #[cfg(feature = "testing")]
    pub(crate) fn build_mock(
        self,
        mock: Arc<crate::testing::MockTransport>,
    ) -> Result<ServerClient> {
        Ok(ServerClient::from_parts(
            self.validate()?,
            Transport::Mock(mock),
        ))
    }
    fn validate(&self) -> Result<Config> {
        for (name, value) in [
            ("timeout", self.timeout),
            ("connect_timeout", self.connect_timeout),
            ("read_timeout", self.read_timeout),
        ] {
            if value.is_zero() {
                return Err(invalid_config(format!("{name} must be positive")));
            }
        }
        if self.api_key.is_empty() || self.project_id.is_empty() {
            return Err(invalid_config("API key and project ID are required"));
        }
        id(&self.project_id).map_err(|_| invalid_config("Invalid project ID"))?;
        let api_key = HeaderValue::from_str(&self.api_key)
            .map_err(|_| invalid_config("The API key contains characters a header cannot"))?;
        let mut api_key = api_key;
        api_key.set_sensitive(true);
        let mut urls = Vec::new();
        for url in [&self.base_url, &self.cdn_base_url] {
            let parsed = reqwest::Url::parse(url).ok().filter(|url| {
                ["http", "https"].contains(&url.scheme())
                    && url.query().is_none()
                    && url.fragment().is_none()
            });
            if parsed.is_none() {
                return Err(invalid_config(format!(
                    "Base URLs must be absolute HTTP(S) URLs without a query: {url:?}"
                )));
            }
            urls.push(url.trim_end_matches('/').to_owned());
        }
        Ok(Config {
            api_key,
            project_id: self.project_id.clone(),
            cdn_base_url: urls.pop().unwrap_or_default(),
            base_url: urls.pop().unwrap_or_default(),
            timeout: self.timeout,
            max_retries: self.max_retries,
        })
    }
}

struct Config {
    api_key: HeaderValue,
    project_id: String,
    base_url: String,
    cdn_base_url: String,
    timeout: Duration,
    max_retries: u32,
}

struct Inner {
    config: Config,
    transport: Transport,
    user_agent: HeaderValue,
    lenses: Mutex<HashMap<String, Lens>>,
}

/// The async CalmLens client.
///
/// Create one client and reuse it: clones are cheap and share the connection pool and lens
/// cache, so hold it in your application state (or an `Arc`) rather than creating one per
/// request. All methods are `Send`, so they work in Tokio tasks, axum and actix-web handlers.
#[derive(Clone)]
pub struct ServerClient {
    inner: Arc<Inner>,
    timeout: Option<Duration>,
    max_retries: Option<u32>,
}

impl fmt::Debug for ServerClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let config = &self.inner.config;
        f.debug_struct("ServerClient")
            .field("api_key", &"[redacted]")
            .field("project_id", &config.project_id)
            .field("base_url", &config.base_url)
            .field("cdn_base_url", &config.cdn_base_url)
            .field("timeout", &self.timeout.unwrap_or(config.timeout))
            .field(
                "max_retries",
                &self.max_retries.unwrap_or(config.max_retries),
            )
            .finish_non_exhaustive()
    }
}

impl ServerClient {
    /// A client for the production API with default options.
    pub fn new(api_key: impl Into<String>, project_id: impl Into<String>) -> Result<Self> {
        Self::builder(api_key, project_id).build()
    }
    /// A builder for a client with custom URLs, timeouts, retries or HTTP client.
    pub fn builder(
        api_key: impl Into<String>,
        project_id: impl Into<String>,
    ) -> ServerClientBuilder {
        ServerClientBuilder::new(api_key.into(), project_id.into())
    }
    fn from_parts(config: Config, transport: Transport) -> Self {
        let user_agent = HeaderValue::from_str(&crate::user_agent())
            .unwrap_or_else(|_| HeaderValue::from_static("calmlens-rust"));
        Self {
            inner: Arc::new(Inner {
                config,
                transport,
                user_agent,
                lenses: Mutex::new(HashMap::new()),
            }),
            timeout: None,
            max_retries: None,
        }
    }
    /// A handle whose calls, including uploads and CDN downloads, time out after `timeout`.
    /// It shares this client's connections.
    pub fn with_timeout(&self, timeout: Duration) -> Self {
        Self {
            timeout: Some(timeout),
            ..self.clone()
        }
    }
    /// A handle that retries repeatable requests up to `max_retries` times.
    pub fn with_max_retries(&self, max_retries: u32) -> Self {
        Self {
            max_retries: Some(max_retries),
            ..self.clone()
        }
    }
    /// The project this client works in.
    pub fn project_id(&self) -> &str {
        &self.inner.config.project_id
    }
    /// Asset operations.
    pub fn assets(&self) -> AssetsClient<'_> {
        AssetsClient(self)
    }
    /// Folder operations.
    pub fn folders(&self) -> FoldersClient<'_> {
        FoldersClient(self)
    }
    /// The project's events feed.
    pub fn events(&self) -> EventsClient<'_> {
        EventsClient(self)
    }
    /// CDN URLs and downloads.
    pub fn cdn(&self) -> CdnClient<'_> {
        CdnClient(self)
    }
    /// Text moderation.
    pub fn text(&self) -> TextClient<'_> {
        TextClient(self)
    }
    /// Upload tokens for upload presets, signed locally.
    pub fn upload_tokens(&self) -> UploadTokensClient<'_> {
        UploadTokensClient(self)
    }

    /// Creates or updates a named lens and returns it. See [`ServerClient::ensure_lenses`].
    pub async fn ensure_lens(&self, lens: LensDefinition) -> Result<Lens> {
        let mut lenses = self
            .ensure_lenses(EnsureLenses { lenses: vec![lens] })
            .await?;
        lenses
            .pop()
            .ok_or_else(|| Error::new(ErrorCode::InvalidResponse, "Unexpected lens response"))
    }
    /// Creates or updates named lenses and returns them in request order. Definitions this
    /// client has already ensured are answered from its cache without a request. More than
    /// [`ENSURE_LENSES_MAX_PER_REQUEST`] new definitions are sent in consecutive requests, in order.
    pub async fn ensure_lenses(&self, options: EnsureLenses) -> Result<Vec<Lens>> {
        if options.lenses.is_empty() {
            return Err(invalid_argument("At least one lens is required"));
        }
        let mut keys = Vec::with_capacity(options.lenses.len());
        let mut missing: Vec<(String, &LensDefinition)> = Vec::new();
        let mut resolved = HashMap::new();
        {
            let cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
            for lens in &options.lenses {
                id(&lens.identifier)?;
                let key = serde_json::to_string(lens)
                    .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
                match cache.get(&key) {
                    Some(cached) => {
                        resolved.insert(key.clone(), cached.clone());
                    }
                    None if !missing.iter().any(|(k, _)| *k == key) => {
                        missing.push((key.clone(), lens))
                    }
                    None => {}
                }
                keys.push(key);
            }
        }
        #[derive(Serialize)]
        struct Body<'a> {
            lenses: Vec<&'a LensDefinition>,
        }
        #[derive(serde::Deserialize)]
        struct Response {
            lenses: Vec<Lens>,
        }
        for chunk in missing.chunks(ENSURE_LENSES_MAX_PER_REQUEST) {
            let request = self.prepare(Method::PUT, &self.project_path("lenses")?, &[])?;
            let request = request.json(&Body {
                lenses: chunk.iter().map(|(_, lens)| *lens).collect(),
            })?;
            let response: Response = self.call(request).await?;
            if response.lenses.len() != chunk.len() {
                return Err(Error::new(
                    ErrorCode::InvalidResponse,
                    "Unexpected lens response",
                ));
            }
            let mut cache = self.inner.lenses.lock().unwrap_or_else(|e| e.into_inner());
            for ((key, definition), lens) in chunk.iter().zip(response.lenses) {
                if lens.identifier != definition.identifier {
                    return Err(Error::new(
                        ErrorCode::InvalidResponse,
                        "Unexpected lens identifier",
                    ));
                }
                cache.retain(|_, cached| cached.identifier != lens.identifier);
                cache.insert(key.clone(), lens.clone());
                resolved.insert(key.clone(), lens);
            }
        }
        Ok(keys
            .iter()
            .filter_map(|key| resolved.get(key).cloned())
            .collect())
    }

    fn options(&self) -> CallOptions {
        CallOptions {
            timeout: self.inner.config.timeout,
            timeout_override: self.timeout,
            max_retries: self.max_retries.unwrap_or(self.inner.config.max_retries),
        }
    }
    fn project_path(&self, path: &str) -> Result<String> {
        Ok(format!(
            "/projects/{}/{path}",
            id(&self.inner.config.project_id)?
        ))
    }
    fn prepare(&self, method: Method, path: &str, query: &[(String, String)]) -> Result<Prepared> {
        let url = format!("{}{path}", self.inner.config.base_url);
        self.prepare_url(method, &url, query)
    }
    fn prepare_url(
        &self,
        method: Method,
        url: &str,
        query: &[(String, String)],
    ) -> Result<Prepared> {
        let mut url = reqwest::Url::parse(url).map_err(|cause| {
            invalid_argument(format!("Invalid URL: {cause}")).with_source(cause)
        })?;
        if !query.is_empty() {
            url.query_pairs_mut().extend_pairs(query);
        }
        let mut request = Prepared::new(method, url);
        request
            .headers
            .insert("x-api-key", self.inner.config.api_key.clone());
        request
            .headers
            .insert(http::header::USER_AGENT, self.inner.user_agent.clone());
        Ok(request)
    }
    async fn send(&self, request: Prepared) -> Result<(u16, HeaderMap, Bytes)> {
        let exchange = execute(&self.inner.transport, request, self.options(), true).await?;
        let (status, headers) = (exchange.status, exchange.headers.clone());
        let body = exchange.read().await?;
        Ok((status, headers, body))
    }
    async fn call<T: serde::de::DeserializeOwned>(&self, request: Prepared) -> Result<T> {
        let (status, headers, body) = self.send(request).await?;
        decode(status, &headers, &body)
    }
    async fn call_empty(&self, request: Prepared) -> Result<()> {
        self.send(request).await.map(|_| ())
    }

    async fn submit(&self, options: SubmitAsset, queue: bool) -> Result<Asset> {
        if options.name.is_empty() {
            return Err(invalid_payload("Asset name is required"));
        }
        let sources = [
            options.content.is_some(),
            options.part.is_some(),
            options.url.is_some(),
        ];
        if sources.iter().filter(|present| **present).count() != 1 {
            return Err(invalid_payload(
                "Supply exactly one of content, part, or url; isFinal belongs in part",
            ));
        }
        let idempotency_key = options.idempotency_key.clone().unwrap_or_else(uuid);
        let mut query = Query::default();
        query.push("name", &options.name);
        query.push("queue", queue);
        query.opt("description", options.description.as_ref());
        query.json("processingOptions", options.processing_options.as_ref())?;
        query.opt("visibility", options.visibility.as_ref());
        query.json("metadata", options.metadata.as_ref())?;
        query.opt("externalId", options.external_id.as_ref());
        query.opt("externalUrl", options.external_url.as_ref());
        if let Patch::Value(folder) = &options.folder_id {
            query.push("folderId", folder);
        }
        query.opt("uploadPresetId", options.upload_preset_id.as_ref());
        if let Some(url) = &options.url {
            #[derive(Serialize)]
            #[serde(rename_all = "camelCase")]
            struct UrlBody<'a> {
                name: &'a str,
                url: &'a str,
                #[serde(skip_serializing_if = "Option::is_none")]
                description: Option<&'a String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                processing_options: Option<&'a ProcessingOptions>,
                #[serde(skip_serializing_if = "Option::is_none")]
                visibility: Option<&'a Visibility>,
                #[serde(skip_serializing_if = "Option::is_none")]
                metadata: Option<&'a Vec<MetadataItem>>,
                #[serde(skip_serializing_if = "Option::is_none")]
                external_id: Option<&'a String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                external_url: Option<&'a String>,
                #[serde(skip_serializing_if = "Patch::is_missing")]
                folder_id: &'a Patch<String>,
                #[serde(skip_serializing_if = "Option::is_none")]
                upload_preset_id: Option<&'a String>,
            }
            let request = self
                .prepare(
                    Method::POST,
                    &self.project_path("assets")?,
                    &[("queue".into(), queue.to_string())],
                )?
                .header("idempotency-key", &idempotency_key)?
                .json(&UrlBody {
                    name: &options.name,
                    url,
                    description: options.description.as_ref(),
                    processing_options: options.processing_options.as_ref(),
                    visibility: options.visibility.as_ref(),
                    metadata: options.metadata.as_ref(),
                    external_id: options.external_id.as_ref(),
                    external_url: options.external_url.as_ref(),
                    folder_id: &options.folder_id,
                    upload_preset_id: options.upload_preset_id.as_ref(),
                })?;
            return self.call(request).await;
        }
        let multipart = options.part.is_some();
        let content = match (options.content, options.part) {
            (Some(content), _) | (None, Some(content)) => content,
            (None, None) => return Err(invalid_payload("Content is required")),
        };
        let mime = content
            .mime_type
            .split(';')
            .next()
            .unwrap_or("")
            .trim()
            .to_lowercase();
        if mime.is_empty() || mime == "application/octet-stream" || mime.starts_with("multipart/") {
            return Err(Error::new(
                ErrorCode::InvalidUploadMimeType,
                format!("{mime} is not a valid upload file type. Uploads must use a concrete file MIME type that CalmLens can store and process, such as image/png, image/jpeg, application/pdf, or text/plain."),
            ));
        }
        if multipart && content.part_number.is_some_and(|number| number != 1) {
            return Err(Error::new(
                ErrorCode::UseUploadPart,
                "Use uploadPart for multipart upload parts after the first part",
            ));
        }
        let is_final = content.is_final.unwrap_or(false);
        let (body, size) = upload_body(content.payload, multipart)?;
        if multipart {
            check_part_size(size, is_final)?;
            if mime.starts_with("image/") {
                check_image_size(size, is_final)?;
            }
        }
        query.push("contentType", &content.mime_type);
        query.push("sizeInBytes", size);
        if multipart {
            query.push("partNumber", 1);
            query.push("isFinal", is_final);
            query.opt("totalSizeInBytes", options.total_size_in_bytes);
        }
        let mut request = self
            .prepare(Method::POST, &self.project_path("assets")?, &query.0)?
            .header("content-type", &content.mime_type)?
            .header(
                "x-calmlens-upload",
                if multipart { "part" } else { "content" },
            )?
            .header("idempotency-key", &idempotency_key)?;
        request.body = body;
        request.transfer = true;
        self.call(request).await
    }

    async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
        let path = format!("/assets/{}/part", id(&options.asset_id)?);
        let part_number = options.part.part_number.unwrap_or(0);
        if part_number < 1 {
            return Err(Error::new(
                ErrorCode::InvalidUploadPartNumber,
                "Multipart upload part number is invalid.",
            ));
        }
        let is_final = options.part.is_final.unwrap_or(false);
        let (body, size) = upload_body(options.part.payload, true)?;
        check_part_size(size, is_final)?;
        let mut query = Query::default();
        query.opt("queue", options.queue);
        query.push("partNumber", part_number);
        query.push("isFinal", is_final);
        query.push("sizeInBytes", size);
        let idempotency_key = options.idempotency_key.unwrap_or_else(uuid);
        let mut request = self
            .prepare(Method::POST, &path, &query.0)?
            .header("content-type", "application/octet-stream")?
            .header("x-calmlens-upload", "part")?
            .header("idempotency-key", &idempotency_key)?;
        request.body = body;
        request.transfer = true;
        self.call(request).await
    }

    async fn list_page(&self, options: &ListAssets) -> Result<AssetPage> {
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_deref());
        query.opt("pageSize", options.page_size);
        query.opt("filter", options.filter.as_ref());
        query.ordering(options.ordering.as_deref());
        query.opt("folderId", options.folder_id.as_ref());
        self.call(self.prepare(Method::GET, &self.project_path("assets/page")?, &query.0)?)
            .await
    }
    async fn children_page(&self, options: &ListChildren) -> Result<AssetPage> {
        let path = format!("/assets/{}/children", id(&options.asset_id)?);
        let mut query = Query::default();
        query.opt("cursor", options.cursor.as_deref());
        query.opt("pageSize", options.page_size);
        query.opt("filter", options.filter.as_ref());
        query.ordering(options.ordering.as_deref());
        self.call(self.prepare(Method::GET, &path, &query.0)?).await
    }
    async fn events_page(&self, options: &ListEvents) -> Result<EventsPage> {
        let mut query = Query::default();
        query.opt("after", options.after.as_ref());
        query.opt("limit", options.limit);
        self.call(self.prepare(Method::GET, &self.project_path("events")?, &query.0)?)
            .await
    }
}

fn check_part_size(size: u64, is_final: bool) -> Result<()> {
    if !is_final && size < MIN_PART {
        return Err(invalid_payload(
            "Multipart upload parts must be at least 5MiB except the final part.",
        ));
    }
    Ok(())
}
fn check_image_size(size: u64, is_final: bool) -> Result<()> {
    if size > 20 * 1024 * 1024 {
        return Err(Error::new(
            ErrorCode::MultipartImageTooLarge,
            "Multipart image uploads cannot exceed 20MB.",
        ));
    }
    if is_final && size < 10 * 1024 * 1024 {
        return Err(Error::new(
            ErrorCode::MultipartImageTooSmall,
            "Multipart image uploads must total at least 10MB.",
        ));
    }
    Ok(())
}

#[derive(Default)]
struct Query(Vec<(String, String)>);
impl Query {
    fn push(&mut self, key: &str, value: impl fmt::Display) {
        self.0.push((key.into(), value.to_string()));
    }
    fn opt(&mut self, key: &str, value: Option<impl fmt::Display>) {
        if let Some(value) = value {
            self.push(key, value);
        }
    }
    fn json(&mut self, key: &str, value: Option<&impl Serialize>) -> Result<()> {
        if let Some(value) = value {
            let text = serde_json::to_string(value)
                .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
            self.push(key, text);
        }
        Ok(())
    }
    fn ordering(&mut self, ordering: Option<&[Order]>) {
        for (index, order) in ordering.unwrap_or_default().iter().enumerate() {
            self.push(&format!("ordering[{index}][field]"), &order.field);
            self.push(&format!("ordering[{index}][direction]"), &order.direction);
        }
    }
}

fn percent_encode(value: &str, keep: &[u8]) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || keep.contains(&byte) {
            out.push(byte as char);
        } else {
            out.push_str(&format!("%{byte:02X}"));
        }
    }
    out
}
/// Encodes an identifier as one path segment. "." and ".." are rejected because URL
/// resolution treats them as relative segments, which would reach another route.
pub(crate) fn id(value: &str) -> Result<String> {
    if value.is_empty() {
        return Err(invalid_argument("Identifier is required"));
    }
    if value == "." || value == ".." {
        return Err(invalid_argument("Identifier cannot be \".\" or \"..\""));
    }
    Ok(percent_encode(value, b"-_.!~*'()"))
}
/// Encodes a CDN transform selector like JavaScript's encodeURI, keeping its separators and
/// the literal `[` and `]` the CDN matches.
fn transform(value: &str) -> Result<String> {
    let value = value.trim_start_matches('/');
    if value.contains("..") || value.contains('?') || value.contains('#') {
        return Err(invalid_argument(
            "Transform cannot contain \"..\", \"?\" or \"#\"",
        ));
    }
    Ok(percent_encode(value, b"-_.!~*'();/:@&=+$,[]"))
}

/// Asset operations. Get it from [`ServerClient::assets`].
#[derive(Debug, Clone, Copy)]
pub struct AssetsClient<'a>(&'a ServerClient);
impl AssetsClient<'_> {
    /// Uploads an asset and queues it for classification, returning straight away
    /// (`POST /projects/:projectId/assets?queue=true`). Retries reuse one
    /// `Idempotency-Key`, so a retried upload never creates a second asset.
    pub async fn create(&self, options: SubmitAsset) -> Result<Asset> {
        self.0.submit(options, true).await
    }
    /// Uploads an asset and waits for its moderation decision.
    pub async fn moderate(&self, options: SubmitAsset) -> Result<Asset> {
        if let Some(Content {
            payload: Payload::Text(text),
            ..
        }) = &options.content
        {
            if text.trim().is_empty() {
                return Err(invalid_payload(
                    "Text to moderate must be a non-empty string",
                ));
            }
        }
        self.0.submit(options, false).await
    }
    /// Sends a later multipart part. The final part is classified with the `queue` choice
    /// saved when the upload started unless `options.queue` overrides it.
    pub async fn upload_part(&self, options: UploadPart) -> Result<Asset> {
        self.0.upload_part(options).await
    }
    /// Searches approved assets in natural language.
    pub async fn search(&self, options: SearchAssets) -> Result<AssetSearchResponse> {
        let mut query = Query::default();
        query.push("query", &options.query);
        query.opt("mode", options.mode.as_ref());
        query.opt("limit", options.limit);
        self.0
            .call(self.0.prepare(
                Method::GET,
                &self.0.project_path("assets/search")?,
                &query.0,
            )?)
            .await
    }
    /// One page of assets.
    pub async fn list(&self, options: ListAssets) -> Result<AssetPage> {
        self.0.list_page(&options).await
    }
    /// Every asset from `options.cursor` on, fetching pages as the stream is read.
    pub fn iterate(&self, options: ListAssets) -> BoxStream<'static, Result<Asset>> {
        let client = self.0.clone();
        paginate(options, move |options| {
            let client = client.clone();
            async move {
                let page = client.list_page(&options).await?;
                let more = page.has_more.unwrap_or(false)
                    && page.next_cursor.is_some()
                    && !page.items.is_empty();
                let next = more.then_some(ListAssets {
                    cursor: page.next_cursor,
                    ..options
                });
                Ok((page.items, next))
            }
        })
    }
    /// One page of an asset's children.
    pub async fn list_children(&self, options: ListChildren) -> Result<AssetPage> {
        self.0.children_page(&options).await
    }
    /// Every child of an asset from `options.cursor` on.
    pub fn iterate_children(&self, options: ListChildren) -> BoxStream<'static, Result<Asset>> {
        let client = self.0.clone();
        paginate(options, move |options| {
            let client = client.clone();
            async move {
                let page = client.children_page(&options).await?;
                let more = page.has_more.unwrap_or(false)
                    && page.next_cursor.is_some()
                    && !page.items.is_empty();
                let next = more.then_some(ListChildren {
                    cursor: page.next_cursor,
                    ..options
                });
                Ok((page.items, next))
            }
        })
    }
    /// Retrieves an asset's current state.
    pub async fn retrieve(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        self.0.call(self.0.prepare(Method::GET, &path, &[])?).await
    }
    /// Retrieves the asset until it is decided ([`Asset::is_decided`]: moderation status
    /// `approved` or `rejected`, or processing status `failed`) and returns it. It checks again
    /// after 0.5 seconds, waiting 1.5 times longer each time up to 5 seconds, and fails with
    /// `sdk/timeout` and details `{assetId, processingStatus, moderationStatus}` when
    /// `options.timeout` (60 seconds by default) passes without a decision. Drop the future to
    /// stop waiting. Webhooks report decisions without polling.
    pub async fn wait_for_decision(&self, options: WaitForDecision) -> Result<Asset> {
        let timeout = options.timeout.unwrap_or(DEFAULT_DECISION_TIMEOUT);
        let asset_id = AssetId::new(options.asset_id);
        // A timeout too large to add to the clock never runs out.
        let deadline = tokio::time::Instant::now().checked_add(timeout);
        let mut delay = DECISION_POLL_FIRST_DELAY;
        loop {
            let asset = self.retrieve(asset_id.clone()).await?;
            if asset.is_decided() {
                return Ok(asset);
            }
            let remaining = deadline
                .map(|deadline| deadline.saturating_duration_since(tokio::time::Instant::now()));
            if remaining == Some(Duration::ZERO) {
                let processing = asset.processing.status.as_str();
                let moderation = asset.moderation.status.as_str();
                let mut details = serde_json::Map::new();
                details.insert("assetId".into(), asset.id.clone().into());
                details.insert("processingStatus".into(), processing.into());
                details.insert("moderationStatus".into(), moderation.into());
                return Err(Error::new(
                    ErrorCode::Timeout,
                    format!(
                        "Asset {} had no moderation decision after {timeout:?} (processing {processing}, moderation {moderation})",
                        asset.id
                    ),
                )
                .with_details(details));
            }
            tokio::time::sleep(remaining.map_or(delay, |remaining| remaining.min(delay))).await;
            delay = delay.mul_f64(1.5).min(DECISION_POLL_MAX_DELAY);
        }
    }
    /// Updates an asset; [`Patch::Missing`] fields are left unchanged.
    pub async fn update(&self, options: UpdateAsset) -> Result<Asset> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        let request = self.0.prepare(Method::PATCH, &path, &[])?.json(&options)?;
        self.0.call(request).await
    }
    /// Classifies an asset whose processing failed (status `error`) again.
    pub async fn retry(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}/retry", id(&options.asset_id)?);
        self.0.call(self.0.prepare(Method::POST, &path, &[])?).await
    }
    /// Removes the stored content (`DELETE /assets/:assetId/content`). The asset record,
    /// metadata and report remain; the returned asset has `storage_deleted_at` set.
    pub async fn delete_content(&self, options: AssetId) -> Result<Asset> {
        let path = format!("/assets/{}/content", id(&options.asset_id)?);
        self.0
            .call(self.0.prepare(Method::DELETE, &path, &[])?)
            .await
    }
    /// Deletes the asset record and its stored content (`DELETE /assets/:assetId`).
    pub async fn delete(&self, options: AssetId) -> Result<()> {
        let path = format!("/assets/{}", id(&options.asset_id)?);
        self.0
            .call_empty(self.0.prepare(Method::DELETE, &path, &[])?)
            .await
    }
    /// Moves an asset to a folder, or to the project root.
    pub async fn move_asset(&self, options: MoveAsset) -> Result<Asset> {
        let path = format!("/assets/{}/move", id(&options.asset_id)?);
        let request = self.0.prepare(Method::POST, &path, &[])?.json(&options)?;
        self.0.call(request).await
    }
    /// Creates a signed URL for an asset's content or preview (15 minutes by default).
    pub async fn create_signed_url(&self, options: SignedUrlOptions) -> Result<SignedUrl> {
        let path = format!("/assets/{}/signed-url", id(&options.asset_id)?);
        let transform = match options.transform {
            Some(transform) => Some(CdnTransform::Selector(transform.selector()?)),
            None => None,
        };
        let options = SignedUrlOptions {
            transform,
            resource: Some(options.resource.unwrap_or_else(|| "content".into())),
            expires_in_seconds: Some(options.expires_in_seconds.unwrap_or(900)),
            ..options
        };
        let request = self.0.prepare(Method::POST, &path, &[])?.json(&options)?;
        self.0.call(request).await
    }
}

/// Yields the items of successive pages; `fetch` returns a page and the next page's options.
fn paginate<O, F, Fut, T>(first: O, fetch: F) -> BoxStream<'static, Result<T>>
where
    O: Send + 'static,
    T: Send + 'static,
    F: Fn(O) -> Fut + Send + 'static,
    Fut: std::future::Future<Output = Result<(Vec<T>, Option<O>)>> + Send + 'static,
{
    futures_util::stream::try_unfold(Some(first), move |next| {
        let page = next.map(&fetch);
        async move {
            match page {
                None => Ok(None),
                Some(page) => {
                    let (items, next) = page.await?;
                    Ok(Some((
                        futures_util::stream::iter(items.into_iter().map(Ok)),
                        next,
                    )))
                }
            }
        }
    })
    .try_flatten()
    .boxed()
}

/// Folder operations. Get it from [`ServerClient::folders`].
#[derive(Debug, Clone, Copy)]
pub struct FoldersClient<'a>(&'a ServerClient);
impl FoldersClient<'_> {
    /// Every folder in the project.
    pub async fn list(&self) -> Result<Vec<Folder>> {
        #[derive(serde::Deserialize)]
        struct Response {
            folders: Vec<Folder>,
        }
        let request = self
            .0
            .prepare(Method::GET, &self.0.project_path("folders")?, &[])?;
        Ok(self.0.call::<Response>(request).await?.folders)
    }
    /// Creates a folder.
    pub async fn create(&self, options: CreateFolder) -> Result<Folder> {
        let request = self
            .0
            .prepare(Method::POST, &self.0.project_path("folders")?, &[])?
            .json(&options)?;
        self.0.call(request).await
    }
    /// Retrieves a folder.
    pub async fn retrieve(&self, options: FolderId) -> Result<Folder> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        self.0.call(self.0.prepare(Method::GET, &path, &[])?).await
    }
    /// Renames a folder.
    pub async fn update(&self, options: UpdateFolder) -> Result<Folder> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        let request = self.0.prepare(Method::PATCH, &path, &[])?.json(&options)?;
        self.0.call(request).await
    }
    /// Moves a folder under another folder, or to the project root.
    pub async fn move_folder(&self, options: MoveFolder) -> Result<Folder> {
        let path = format!("/folders/{}/move", id(&options.folder_id)?);
        let request = self.0.prepare(Method::POST, &path, &[])?.json(&options)?;
        self.0.call(request).await
    }
    /// Deletes an empty folder.
    pub async fn delete(&self, options: FolderId) -> Result<()> {
        let path = format!("/folders/{}", id(&options.folder_id)?);
        self.0
            .call_empty(self.0.prepare(Method::DELETE, &path, &[])?)
            .await
    }
}

/// The events feed. Get it from [`ServerClient::events`].
#[derive(Debug, Clone, Copy)]
pub struct EventsClient<'a>(&'a ServerClient);
impl EventsClient<'_> {
    /// One page of events after `options.after`. Without `after` the page is empty and its
    /// cursor marks now.
    pub async fn list(&self, options: ListEvents) -> Result<EventsPage> {
        self.0.events_page(&options).await
    }
    /// Pages of events from `options.after`, following each page's cursor until a page has
    /// `has_more: false`. Store the last page's `cursor` and continue from it later.
    pub fn pages(&self, options: ListEvents) -> BoxStream<'static, Result<EventsPage>> {
        let client = self.0.clone();
        futures_util::stream::try_unfold(Some(options), move |next| {
            let client = client.clone();
            async move {
                let Some(options) = next else {
                    return Ok(None);
                };
                let page = client.events_page(&options).await?;
                // A page that does not advance the cursor ends the stream instead of repeating.
                let advanced = options.after.as_deref() != Some(page.cursor.as_str());
                let next = (page.has_more && advanced).then(|| ListEvents {
                    after: Some(page.cursor.clone()),
                    ..options
                });
                Ok(Some((page, next)))
            }
        })
        .boxed()
    }
}

/// Signs upload tokens, which let a browser upload through an upload preset. Get it from
/// [`ServerClient::upload_tokens`]. Signing happens locally with the API key; no request is made.
#[derive(Debug, Clone, Copy)]
pub struct UploadTokensClient<'a>(&'a ServerClient);
impl UploadTokensClient<'_> {
    /// Signs a single-use token. Hand it to the browser as its bearer token and give each
    /// upload its own.
    pub fn sign(&self, options: SignUploadToken) -> Result<SignedUploadToken> {
        use base64::Engine;
        use hmac::{Hmac, Mac};
        use sha2::{Digest, Sha256};

        id(&options.upload_preset_id)
            .map_err(|_| invalid_argument("Upload preset ID is required"))?;
        let ttl = options.expires_in_seconds.unwrap_or(600);
        if !(1..=3600).contains(&ttl) {
            return Err(invalid_argument(
                "expiresInSeconds must be a whole number from 1 to 3600",
            ));
        }
        if options.external_id.as_deref() == Some("") {
            return Err(invalid_argument("externalId must be a non-empty string"));
        }
        let api_key = String::from_utf8_lossy(self.0.inner.config.api_key.as_bytes()).into_owned();
        let prefix_length = if api_key.starts_with("clsk_") { 13 } else { 8 };
        let expires_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0, |elapsed| elapsed.as_millis() as u64)
            + u64::from(ttl) * 1000;
        #[derive(Serialize)]
        struct Claims<'a> {
            v: u8,
            u: &'a str,
            k: &'a str,
            e: u64,
            n: String,
            #[serde(skip_serializing_if = "Option::is_none")]
            x: Option<&'a str>,
        }
        let claims = Claims {
            v: 1,
            u: &options.upload_preset_id,
            k: &api_key[..prefix_length.min(api_key.len())],
            e: expires_at,
            n: uuid(),
            x: options.external_id.as_deref(),
        };
        let body = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .encode(serde_json::to_vec(&claims).map_err(|e| invalid_argument(e.to_string()))?);
        let secret: String = Sha256::digest(api_key.as_bytes())
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect();
        let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes())
            .map_err(|e| invalid_argument(e.to_string()))?;
        mac.update(format!("calmlens-upload-token:v1:{body}").as_bytes());
        let signature: String = mac
            .finalize()
            .into_bytes()
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect();
        Ok(SignedUploadToken {
            token: format!("clut_{body}.{signature}"),
            expires_at,
        })
    }
}

/// Text moderation. Get it from [`ServerClient::text`].
#[derive(Debug, Clone, Copy)]
pub struct TextClient<'a>(&'a ServerClient);
impl TextClient<'_> {
    /// Moderates text as a `text/plain` asset named `text` unless `name` is set.
    pub async fn moderate(&self, options: ModerateText) -> Result<Asset> {
        self.0
            .assets()
            .moderate(SubmitAsset {
                name: options.name.unwrap_or_else(|| "text".into()),
                content: Some(Content::text(options.text)),
                description: options.description,
                processing_options: options.processing_options,
                metadata: options.metadata,
                external_id: options.external_id,
                external_url: options.external_url,
                folder_id: options.folder_id,
                upload_preset_id: options.upload_preset_id,
                idempotency_key: options.idempotency_key,
                ..Default::default()
            })
            .await
    }
}

/// CDN URLs and downloads. Get it from [`ServerClient::cdn`].
#[derive(Debug, Clone, Copy)]
pub struct CdnClient<'a>(&'a ServerClient);
impl CdnClient<'_> {
    /// The CDN URL of an asset's content or preview, optionally through a lens or transform.
    pub fn get_asset_url(&self, options: &CdnRequest) -> Result<String> {
        let resource = options
            .resource
            .as_ref()
            .map_or("content", |value| value.as_str());
        if !["content", "preview"].contains(&resource) {
            return Err(invalid_argument("Resource must be content or preview"));
        }
        let config = &self.0.inner.config;
        let mut url = format!(
            "{}/assets/{}/{}/{resource}",
            config.cdn_base_url,
            id(&config.project_id)?,
            id(&options.asset_identifier)?
        );
        if let Some(lens) = options.lens.as_deref().filter(|v| !v.is_empty()) {
            url.push_str(&format!("/@{}", id(lens)?));
        }
        if let Some(value) = options.transform.as_ref().filter(|v| !v.is_empty()) {
            url.push(if options.lens.as_deref().is_some_and(|v| !v.is_empty()) {
                ','
            } else {
                '/'
            });
            match value {
                CdnTransform::Selector(value) => url.push_str(&transform(value)?),
                // Already path-safe: unreserved characters, percent escapes, brackets, `=` and `,`.
                CdnTransform::Steps(_) => url.push_str(&value.selector()?),
            }
        }
        Ok(url)
    }
    /// Fetches an asset through the CDN with the API key, returning the response whatever
    /// its status. The body streams; it is not subject to the API call timeout.
    pub async fn serve(&self, options: CdnRequest) -> Result<CdnResponse> {
        let url = self.get_asset_url(&options)?;
        let init = options.init.unwrap_or_default();
        let method = Method::from_bytes(init.method.as_deref().unwrap_or("GET").as_bytes())
            .map_err(|_| invalid_argument("Invalid HTTP method"))?;
        let mut request = self.0.prepare_url(method, &url, &[])?;
        for (name, value) in &init.headers {
            if name.eq_ignore_ascii_case("x-api-key") {
                continue;
            }
            let name = http::HeaderName::from_bytes(name.as_bytes())
                .map_err(|_| invalid_argument(format!("Invalid header name {name:?}")))?;
            let value = HeaderValue::from_str(value)
                .map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
            request.headers.insert(name, value);
        }
        request.transfer = true;
        let exchange: Exchange =
            execute(&self.0.inner.transport, request, self.0.options(), false).await?;
        Ok(CdnResponse {
            status: StatusCode::from_u16(exchange.status)
                .map_err(|_| Error::new(ErrorCode::InvalidResponse, "Invalid status"))?,
            headers: exchange.headers.clone(),
            body: exchange.stream(),
        })
    }
}

/// A streaming CDN response. Drop it to close an unfinished download.
pub struct CdnResponse {
    status: StatusCode,
    headers: HeaderMap,
    body: crate::ByteStream,
}
impl fmt::Debug for CdnResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CdnResponse")
            .field("status", &self.status)
            .field("headers", &self.headers)
            .finish_non_exhaustive()
    }
}
impl CdnResponse {
    /// The HTTP status.
    pub fn status(&self) -> StatusCode {
        self.status
    }
    /// The response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    /// The next chunk of the body, or `None` at the end.
    pub async fn chunk(&mut self) -> Result<Option<Bytes>> {
        match self.body.next().await {
            None => Ok(None),
            Some(chunk) => chunk.map(Some).map_err(stream_error),
        }
    }
    /// The whole body in memory. Prefer [`CdnResponse::chunk`] or
    /// [`CdnResponse::into_stream`] for large files.
    pub async fn bytes(mut self) -> Result<Bytes> {
        let mut body = Vec::new();
        while let Some(chunk) = self.chunk().await? {
            body.extend_from_slice(&chunk);
        }
        Ok(body.into())
    }
    /// The whole body as UTF-8 text.
    pub async fn text(self) -> Result<String> {
        String::from_utf8(self.bytes().await?.to_vec()).map_err(|cause| {
            Error::new(ErrorCode::InvalidResponse, "Invalid UTF-8 response").with_source(cause)
        })
    }
    /// The body as a stream of chunks.
    pub fn into_stream(self) -> BoxStream<'static, Result<Bytes>> {
        self.body.map_err(stream_error).boxed()
    }
}