meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
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
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
// this file is @generated by Perseid; edit the shared runtime template.
//! Request building, retries and response decoding.
#![allow(dead_code)]

use std::{
    borrow::Cow,
    fmt,
    hash::{BuildHasher as _, Hasher as _},
    sync::Arc,
    time::{Duration, SystemTime},
};

use bytes::Bytes;
use http::{
    header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, RETRY_AFTER, USER_AGENT},
    HeaderMap, HeaderName, HeaderValue, Method, StatusCode,
};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS, NON_ALPHANUMERIC};
use serde::de::DeserializeOwned;

use crate::api::{
    auth_schemes::{base64, OAuthUse, Security, SyncFuture},
    middleware::{BoxError, Next, Request as MiddlewareRequest, Response},
    upload::{Multipart, RequestBody},
    Call, EventStream, RequestOptions, SseEvent, Upload,
};
use crate::{error::Error, Configuration};

const IDEMPOTENCY_KEY: &str = "idempotency-key";
/// Whether the API deduplicates POSTs by `Idempotency-Key`, so that each gets one to be retried.
const AUTO_IDEMPOTENCY_KEY: bool = false;
const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);

/// A request that got no usable API response. The crate's `Error` is built from it.
#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum Failure {
    /// The request could not be built: an invalid header, URL or body.
    Request(BoxError),
    /// No response within the configured timeout.
    Timeout,
    /// Connecting, sending or reading the response failed.
    Transport(BoxError),
    /// The response body does not match the expected type.
    Decode(BoxError),
}

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Request(error) => write!(f, "invalid request: {error}"),
            Self::Timeout => f.write_str("request timed out"),
            Self::Transport(error) => write!(f, "transport error: {error}"),
            Self::Decode(error) => write!(f, "unexpected response body: {error}"),
        }
    }
}

impl std::error::Error for Failure {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Request(error) | Self::Transport(error) | Self::Decode(error) => Some(&**error),
            Self::Timeout => None,
        }
    }
}

pub(crate) fn request_error(error: impl Into<BoxError>) -> Error {
    Error::generic(Failure::Request(error.into()))
}

pub(crate) fn transport_error(error: impl Into<BoxError>) -> Error {
    Error::generic(Failure::Transport(error.into()))
}

pub(crate) fn decode_error(error: impl Into<BoxError>) -> Error {
    Error::generic(Failure::Decode(error.into()))
}

/// The body of a successful response: read whole, or left open for an event stream.
pub(crate) enum ResponseBody {
    Buffered(Bytes),
    Events(Option<hyper::body::Incoming>, Bytes),
}

impl ResponseBody {
    fn bytes(self) -> Result<Bytes, Error> {
        match self {
            Self::Buffered(bytes) => Ok(bytes),
            Self::Events(..) => Err(decode_error("expected a buffered body")),
        }
    }
}

/// A successful response, before its body is decoded.
pub(crate) struct Received {
    pub(crate) status: StatusCode,
    pub(crate) headers: HeaderMap,
    pub(crate) body: ResponseBody,
}

fn json<T: DeserializeOwned>(body: ResponseBody) -> Result<T, Error> {
    serde_json::from_slice(&body.bytes()?).map_err(decode_error)
}

fn json_or_none<T: DeserializeOwned>(body: ResponseBody) -> Result<Option<T>, Error> {
    let bytes = body.bytes()?;
    if bytes.trim_ascii().is_empty() {
        return Ok(None);
    }
    // A `null` body is no value too.
    serde_json::from_slice::<Option<T>>(&bytes).map_err(decode_error)
}

fn empty(body: ResponseBody) -> Result<(), Error> {
    body.bytes().map(drop)
}

fn text(body: ResponseBody) -> Result<String, Error> {
    String::from_utf8(body.bytes()?.into()).map_err(decode_error)
}

fn events(body: ResponseBody) -> Result<EventStream, Error> {
    match body {
        ResponseBody::Events(body, buffered) => Ok(EventStream::new(body, buffered)),
        ResponseBody::Buffered(_) => Err(decode_error("expected an event stream")),
    }
}

fn typed_events<E: DeserializeOwned>(body: ResponseBody) -> Result<EventStream<E>, Error> {
    events(body).map(EventStream::typed)
}

/// How one attempt ended, before deciding whether to retry.
enum Attempt {
    Done(StatusCode, HeaderMap, ResponseBody),
    Status(StatusCode, HeaderMap, Bytes),
    Failed(Failure),
}

impl Attempt {
    fn retryable(&self) -> bool {
        match self {
            Self::Done(..) | Self::Failed(Failure::Request(_) | Failure::Decode(_)) => false,
            Self::Failed(Failure::Timeout | Failure::Transport(_)) => true,
            Self::Status(status, ..) => {
                matches!(status.as_u16(), 408 | 429) || status.is_server_error()
            }
        }
    }

    fn retry_after(&self) -> Option<Duration> {
        let Self::Status(_, headers, _) = self else {
            return None;
        };
        let header = |name: &str| headers.get(name)?.to_str().ok();
        let delay = if let Some(ms) = header("retry-after-ms") {
            Duration::try_from_secs_f64(ms.trim().parse::<f64>().ok()? / 1000.0).ok()?
        } else {
            let value = header(RETRY_AFTER.as_str())?.trim();
            match value.parse::<u64>() {
                Ok(seconds) => Duration::from_secs(seconds),
                Err(_) => httpdate(value)?.duration_since(SystemTime::now()).ok()?,
            }
        };
        (delay <= MAX_RETRY_AFTER).then_some(delay)
    }

    fn into_error(self) -> Error {
        match self {
            Self::Done(..) => unreachable!("a successful attempt is not an error"),
            Self::Status(status, headers, body) => Error::from_response(status, headers, body),
            Self::Failed(failure) => Error::generic(failure),
        }
    }
}

/// HTTP request builder with retry logic.
pub(crate) struct Request {
    method: Method,
    path: Cow<'static, str>,
    query_params: Vec<(String, String)>,
    path_params: Vec<(&'static str, String)>,
    /// Path parameters already serialized and percent-encoded by their style.
    encoded_path_params: Vec<(&'static str, String)>,
    headers: HeaderMap,
    cookies: Vec<(String, String)>,
    serialized_body: Option<Bytes>,
    body_is_form: bool,
    upload: Option<Upload>,
    upload_content_type: &'static str,
    multipart: Option<Multipart>,
    error: Option<Error>,
    security: Option<Security>,
    overrides: HeaderMap,
    #[allow(clippy::option_option)]
    timeout: Option<Option<Duration>>,
    max_retries: Option<u32>,
    /// A POST that is safe to retry without an `Idempotency-Key`.
    retry_safe: bool,
}

impl Request {
    pub fn new(method: Method, path: &'static str) -> Self {
        Request {
            method,
            path: Cow::Borrowed(path),
            query_params: Vec::new(),
            path_params: Vec::new(),
            encoded_path_params: Vec::new(),
            headers: HeaderMap::new(),
            cookies: Vec::new(),
            serialized_body: None,
            body_is_form: false,
            upload: None,
            upload_content_type: "application/octet-stream",
            multipart: None,
            error: None,
            security: None,
            overrides: HeaderMap::new(),
            timeout: None,
            max_retries: None,
            retry_safe: false,
        }
    }

    /// Applies the settings of one call. Its headers win over every other header.
    pub fn with_options(mut self, options: &RequestOptions) -> Self {
        for (name, value) in &options.headers {
            match header(name, value) {
                Ok((name, value)) => {
                    self.overrides.append(name, value);
                }
                Err(error) => self.fail(error),
            }
        }
        if let Some(key) = &options.idempotency_key {
            match header(IDEMPOTENCY_KEY, key) {
                Ok((name, value)) => {
                    self.headers.insert(name, value);
                }
                Err(error) => self.fail(error),
            }
        }
        self.timeout = options.timeout.or(self.timeout);
        self.max_retries = options.max_retries.or(self.max_retries);
        self
    }

    fn fail(&mut self, error: impl Into<BoxError>) {
        self.error.get_or_insert_with(|| request_error(error));
    }

    pub fn with_body_param<T: serde::Serialize>(mut self, param: T) -> Self {
        match serde_json::to_vec(&param) {
            Ok(body) => self.serialized_body = Some(body.into()),
            Err(error) => self.fail(error),
        }
        self
    }

    pub fn with_optional_body_param<T: serde::Serialize>(self, param: Option<T>) -> Self {
        match param {
            Some(body) => self.with_body_param(body),
            None => self,
        }
    }

    /// Sets `name` in the JSON object body, e.g. `stream: true` for a streaming twin.
    pub fn with_body_property(mut self, name: &str, value: impl Into<serde_json::Value>) -> Self {
        let body = self.serialized_body.as_deref().unwrap_or(b"{}");
        match serde_json::from_slice::<serde_json::Value>(body) {
            Ok(serde_json::Value::Object(mut object)) => {
                object.insert(name.to_owned(), value.into());
                self.with_body_param(object)
            }
            Ok(_) => {
                self.fail("the body is not a JSON object");
                self
            }
            Err(error) => {
                self.fail(error);
                self
            }
        }
    }

    /// Encodes the properties of `param` as `a=1&b[c]=2`, given those whose lists are sent as
    /// `name[]=x` (`deepObject`) or comma-separated (`explode: false`).
    pub fn with_form_body_param<T: serde::Serialize>(
        mut self,
        param: T,
        deep_object: &[&str],
        unexploded: &[&str],
    ) -> Self {
        match serde_json::to_value(&param) {
            Ok(serde_json::Value::Object(fields)) => {
                let mut pairs = Vec::new();
                for (name, value) in &fields {
                    let deep = deep_object.contains(&name.as_str());
                    let explode = !unexploded.contains(&name.as_str());
                    encode_param(name, value, deep, explode, &mut pairs);
                }
                let mut form = url::form_urlencoded::Serializer::new(String::new());
                form.extend_pairs(pairs);
                self.serialized_body = Some(form.finish().into());
            }
            Ok(serde_json::Value::Null) => return self,
            Ok(_) => self.fail("a form body must be an object"),
            Err(error) => self.fail(error),
        }
        self.body_is_form = true;
        self
    }

    pub fn with_upload_body(mut self, body: Option<Upload>, content_type: &'static str) -> Self {
        self.upload = body;
        self.upload_content_type = content_type;
        self
    }

    pub fn with_multipart_body(mut self, body: Result<Option<Multipart>, Error>) -> Self {
        match body {
            Ok(body) => self.multipart = body,
            Err(error) => {
                self.error.get_or_insert(error);
            }
        }
        self
    }

    /// Sets the `Authorization` header, below the headers of the call.
    fn with_authorization(mut self, value: String) -> Self {
        match HeaderValue::try_from(value) {
            Ok(mut value) => {
                value.set_sensitive(true);
                self.headers.insert(AUTHORIZATION, value);
            }
            Err(error) => self.fail(error),
        }
        self
    }

    /// Overrides the API-wide security requirement.
    pub fn with_security(mut self, security: Security) -> Self {
        self.security = Some(security);
        self
    }

    /// A header parameter, a list comma-separated.
    pub fn with_header_param(mut self, name: &'static str, value: &impl QueryParamValue) -> Self {
        match header(name, &value.encode()) {
            Ok((name, value)) => {
                self.headers.insert(name, value);
            }
            Err(error) => self.fail(error),
        }
        self
    }

    /// A `content: application/json` header, sent as compact JSON text.
    pub fn with_json_header_param<T: serde::Serialize>(
        mut self,
        name: &'static str,
        value: Option<T>,
    ) -> Self {
        match value.map(|value| serde_json::to_string(&value)).transpose() {
            Ok(Some(json)) => return self.with_header_param(name, &json),
            Ok(None) => {}
            Err(error) => self.fail(error),
        }
        self
    }

    pub fn with_optional_header_param(
        self,
        name: &'static str,
        value: Option<impl QueryParamValue>,
    ) -> Self {
        match value {
            Some(value) => self.with_header_param(name, &value),
            None => self,
        }
    }

    /// A cookie parameter, sent in the single `Cookie` header with the other cookies.
    pub fn with_cookie_param(mut self, name: &'static str, value: &impl QueryParamValue) -> Self {
        self.cookies.push((name.to_owned(), value.encode()));
        self
    }

    pub fn with_optional_cookie_param(
        self,
        name: &'static str,
        value: Option<impl QueryParamValue>,
    ) -> Self {
        match value {
            Some(value) => self.with_cookie_param(name, &value),
            None => self,
        }
    }

    pub fn with_query_param(mut self, name: &'static str, param: &impl QueryParamValue) -> Self {
        self.query_params.push((name.to_owned(), param.encode()));
        self
    }

    /// Sends the JSON value of `param`: objects as `name[key]=value`, lists as `name=a&name=b`
    /// (`name[]=a` with `deep_object`, `name=a,b` without `explode`).
    pub fn with_structured_query_param<T: serde::Serialize>(
        mut self,
        name: &'static str,
        param: Option<T>,
        deep_object: bool,
        explode: bool,
    ) -> Self {
        match param.map(serde_json::to_value).transpose() {
            Ok(Some(value)) => {
                encode_param(name, &value, deep_object, explode, &mut self.query_params);
            }
            Ok(None) => {}
            Err(error) => self.fail(error),
        }
        self
    }

    /// Sends the items of a list joined by `delimiter` (`pipeDelimited`, `spaceDelimited`).
    pub fn with_delimited_query_param<T: serde::Serialize>(
        mut self,
        name: &'static str,
        param: Option<T>,
        delimiter: &str,
    ) -> Self {
        match param.map(serde_json::to_value).transpose() {
            Ok(Some(serde_json::Value::Array(items))) => {
                let joined = items
                    .iter()
                    .filter_map(scalar_text)
                    .collect::<Vec<_>>()
                    .join(delimiter);
                if !joined.is_empty() {
                    self.query_params.push((name.to_owned(), joined));
                }
            }
            Ok(_) => {}
            Err(error) => self.fail(error),
        }
        self
    }

    /// Sends a `content: application/json` parameter as compact JSON text.
    pub fn with_json_query_param<T: serde::Serialize>(
        mut self,
        name: &'static str,
        param: Option<T>,
    ) -> Self {
        match param.map(|param| serde_json::to_string(&param)).transpose() {
            Ok(Some(json)) => self.query_params.push((name.to_owned(), json)),
            Ok(None) => {}
            Err(error) => self.fail(error),
        }
        self
    }

    pub fn with_optional_query_param(
        self,
        name: &'static str,
        param: Option<impl QueryParamValue>,
    ) -> Self {
        match param {
            Some(value) => self.with_query_param(name, &value),
            None => self,
        }
    }

    /// Repeats the parameter for each value (`explode: true`): `?tag=a&tag=b`.
    pub fn with_exploded_query_param<T: QueryParamValue>(
        mut self,
        name: &'static str,
        values: Vec<T>,
    ) -> Self {
        for value in values {
            self.query_params.push((name.to_owned(), value.encode()));
        }
        self
    }

    pub fn with_optional_exploded_query_param<T: QueryParamValue>(
        self,
        name: &'static str,
        values: Option<Vec<T>>,
    ) -> Self {
        match values {
            Some(values) => self.with_exploded_query_param(name, values),
            None => self,
        }
    }

    pub fn with_path_param(mut self, name: &'static str, value: impl fmt::Display) -> Self {
        self.path_params.push((name, value.to_string()));
        self
    }

    /// A path parameter in its OpenAPI `style`: `simple`, `label`, `matrix`, or `json` for a
    /// `content: application/json` value.
    pub fn with_styled_path_param<T: serde::Serialize>(
        mut self,
        name: &'static str,
        value: T,
        style: &str,
        explode: bool,
    ) -> Self {
        match serde_json::to_value(value) {
            Ok(value) => self
                .encoded_path_params
                .push((name, encode_path_param(name, &value, style, explode))),
            Err(error) => self.fail(error),
        }
        self
    }

    /// A call decoding the JSON response body as `T`.
    pub fn json<T: DeserializeOwned + Send + 'static>(self, cfg: &Arc<Configuration>) -> Call<T> {
        Call::new(self, cfg.clone(), json::<T>, false)
    }

    /// A call decoding the JSON response body as `T`, or `None` when there is no body.
    pub fn json_or_none<T: DeserializeOwned + Send + 'static>(
        self,
        cfg: &Arc<Configuration>,
    ) -> Call<Option<T>> {
        Call::new(self, cfg.clone(), json_or_none::<T>, false)
    }

    /// A call whose response has no body worth decoding.
    pub fn empty(self, cfg: &Arc<Configuration>) -> Call<()> {
        Call::new(self, cfg.clone(), empty, false)
    }

    pub fn binary(self, cfg: &Arc<Configuration>) -> Call<Bytes> {
        Call::new(self, cfg.clone(), ResponseBody::bytes, false)
    }

    pub fn text(self, cfg: &Arc<Configuration>) -> Call<String> {
        Call::new(self, cfg.clone(), text, false)
    }

    /// A call opening an event stream of raw events.
    pub fn events(self, cfg: &Arc<Configuration>) -> Call<EventStream<SseEvent>> {
        Call::new(self.accepting_events(), cfg.clone(), events, true)
    }

    /// A call opening an event stream whose events carry JSON `E`s, until `[DONE]`.
    pub fn typed_events<E: DeserializeOwned + Send + 'static>(
        self,
        cfg: &Arc<Configuration>,
    ) -> Call<EventStream<E>> {
        Call::new(
            self.accepting_events(),
            cfg.clone(),
            typed_events::<E>,
            true,
        )
    }

    fn accepting_events(mut self) -> Self {
        self.headers.insert(
            http::header::ACCEPT,
            HeaderValue::from_static("text/event-stream"),
        );
        self
    }

    pub(crate) async fn send(
        mut self,
        conf: &Configuration,
        event_stream: bool,
    ) -> Result<Received, Error> {
        if let Some(error) = self.error.take() {
            return Err(error);
        }
        let token = conf
            .bearer_access_token
            .as_deref()
            .filter(|t| !t.is_empty());
        let mut oauth = match conf.credentials.oauth_scheme(self.security, token) {
            Some((url, scope)) => Some(oauth_token(conf, url, scope).await?),
            None => None,
        };
        let auth = conf
            .credentials
            .apply(
                self.security,
                token,
                oauth.as_ref().map(|used| used.token.as_str()),
            )
            .await?;
        self.query_params.extend(
            auth.query
                .into_iter()
                .map(|(name, value)| (name.to_owned(), value)),
        );
        for (name, value) in &conf.headers {
            match header(name, value) {
                Ok((name, value))
                    if !self.overrides.contains_key(&name) && !self.headers.contains_key(&name) =>
                {
                    self.overrides.append(name, value);
                }
                Ok(_) => {}
                Err(error) => return Err(request_error(error)),
            }
        }
        for (name, value) in auth.headers {
            let name = HeaderName::from_bytes(name.as_bytes()).map_err(request_error)?;
            let mut value = HeaderValue::try_from(value).map_err(request_error)?;
            value.set_sensitive(true);
            self.headers.insert(name, value);
        }
        let mut cookie = self
            .cookies
            .iter()
            .map(|(name, value)| format!("{name}={}", utf8_percent_encode(value, COOKIE_VALUE)))
            .collect::<Vec<_>>();
        // An API key is an opaque credential: only what is not a cookie-octet is encoded.
        cookie.extend(
            auth.cookies.iter().map(|(name, value)| {
                format!("{name}={}", utf8_percent_encode(value, API_KEY_COOKIE))
            }),
        );
        // A `Cookie` header of the call is merged with the cookies instead of replacing them.
        for value in self.overrides.get_all("cookie") {
            cookie.push(String::from_utf8_lossy(value.as_bytes()).into_owned());
        }
        self.overrides.remove("cookie");
        if !cookie.is_empty() {
            let mut value = HeaderValue::try_from(cookie.join("; ")).map_err(request_error)?;
            value.set_sensitive(true);
            self.headers.insert("cookie", value);
        }
        for name in self.overrides.keys() {
            self.headers.remove(name);
        }
        for (name, value) in &self.overrides {
            self.headers.append(name, value.clone());
        }
        if AUTO_IDEMPOTENCY_KEY
            && self.method == Method::POST
            && !self.headers.contains_key(IDEMPOTENCY_KEY)
        {
            let key = format!("auto_{:016x}{:016x}", random(), random());
            self.headers.insert(
                IDEMPOTENCY_KEY,
                HeaderValue::try_from(key).map_err(request_error)?,
            );
        }
        self.headers
            .insert("meteroid-req-id", HeaderValue::from(random()));
        // Retrying a non-idempotent request without a key could apply it twice.
        let idempotent = self.retry_safe
            || self.method.is_idempotent()
            || self.headers.contains_key(IDEMPOTENCY_KEY);
        let replayable = self.upload.as_ref().is_none_or(Upload::replayable)
            && self.multipart.as_ref().is_none_or(Multipart::replayable);
        let max_retries = self.max_retries.unwrap_or(conf.max_retries) as usize;
        let mut retries = 0;
        // An access token the API rejects is replaced once, without using up a retry.
        let mut renewed = false;
        loop {
            let attempt = self.attempt(conf, event_stream).await;
            if let Attempt::Done(status, headers, body) = attempt {
                return Ok(Received {
                    status,
                    headers,
                    body,
                });
            }
            if let (Attempt::Status(StatusCode::UNAUTHORIZED, ..), Some(used), false, true) =
                (&attempt, &oauth, renewed, replayable)
            {
                let sent = self.headers.get(AUTHORIZATION).map(HeaderValue::as_bytes);
                if sent == Some(format!("Bearer {}", used.token).as_bytes()) {
                    renewed = true;
                    if let Some(client) = &conf.credentials.oauth {
                        client.invalidate(&used.key, &used.token).await;
                    }
                    let fresh = oauth_token(conf, used.url, used.scope).await?;
                    let mut value = HeaderValue::try_from(format!("Bearer {}", fresh.token))
                        .map_err(request_error)?;
                    value.set_sensitive(true);
                    self.headers.insert(AUTHORIZATION, value);
                    oauth = Some(fresh);
                    continue;
                }
            }
            if !(idempotent && replayable && attempt.retryable()) || retries >= max_retries {
                return Err(attempt.into_error());
            }
            let delay = attempt.retry_after().unwrap_or_else(|| backoff(retries));
            tokio::time::sleep(delay).await;
            retries += 1;
            self.headers
                .insert("meteroid-retry-count", HeaderValue::from(retries));
        }
    }

    async fn attempt(&mut self, conf: &Configuration, event_stream: bool) -> Attempt {
        let mut request = match self.build_request(conf) {
            Ok(request) => request,
            Err(error) => return Attempt::Failed(Failure::Request(error)),
        };
        let exchange = async {
            let body = request.body_mut().validate_empty().await;
            body.map_err(|error| Failure::Request(error.into()))?;
            let response = Next::new(&conf.middleware, &*conf.client)
                .run(MiddlewareRequest(request))
                .await
                .map_err(Failure::Transport)?;
            let status = response.status();
            if status.is_success() && event_stream {
                return open_event_stream(response);
            }
            let (status, headers, body) =
                response.into_parts().await.map_err(Failure::Transport)?;
            Ok(if status.is_success() {
                Attempt::Done(status, headers, ResponseBody::Buffered(body))
            } else {
                Attempt::Status(status, headers, body)
            })
        };
        let result = match self.timeout.unwrap_or(conf.timeout) {
            Some(timeout) => tokio::time::timeout(timeout, exchange)
                .await
                .unwrap_or(Err(Failure::Timeout)),
            None => exchange.await,
        };
        result.unwrap_or_else(Attempt::Failed)
    }

    fn build_request(
        &mut self,
        conf: &Configuration,
    ) -> Result<http::Request<RequestBody>, BoxError> {
        const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
        const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}');
        const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%');

        let mut path = self.path.to_string();
        for (name, value) in &self.path_params {
            if value == "." || value == ".." {
                return Err(format!(
                    "path parameter `{name}` is `{value}`, which the URL would resolve away"
                )
                .into());
            }
            let value = utf8_percent_encode(value, PATH_SEGMENT).to_string();
            path = path.replace(&format!("{{{name}}}"), &value);
        }
        for (name, value) in &self.encoded_path_params {
            path = path.replace(&format!("{{{name}}}"), value);
        }
        // The token endpoint of an OAuth2 scheme may live elsewhere.
        let mut uri = if path.contains("://") {
            path.clone()
        } else {
            format!("{}{path}", conf.base_path.trim_end_matches('/'))
        };
        if !self.query_params.is_empty() {
            let mut query = url::form_urlencoded::Serializer::new(String::new());
            for (name, value) in &self.query_params {
                query.append_pair(name, value);
            }
            uri.push(if path.contains('?') { '&' } else { '?' });
            uri.push_str(&query.finish());
        }

        let (body, content_type) = if let Some(form) = &mut self.multipart {
            (form.body()?, Some(form.content_type()))
        } else if let Some(upload) = &mut self.upload {
            (upload.body()?, Some(self.upload_content_type.to_owned()))
        } else if let Some(body) = &self.serialized_body {
            let content_type = if self.body_is_form {
                "application/x-www-form-urlencoded"
            } else {
                "application/json"
            };
            (
                Upload::bytes(body.clone()).body()?,
                Some(content_type.to_owned()),
            )
        } else {
            (RequestBody::empty(), None)
        };

        let length = body.length();
        let mut request = http::Request::builder()
            .method(self.method.clone())
            .uri(uri)
            .body(body)?;
        let headers = request.headers_mut();
        if let Some(content_type) = content_type {
            headers.insert(CONTENT_TYPE, HeaderValue::try_from(content_type)?);
            if let Some(length) = length {
                headers.insert(CONTENT_LENGTH, length.into());
            }
        }
        if let Some(user_agent) = &conf.user_agent {
            headers.insert(USER_AGENT, HeaderValue::try_from(user_agent)?);
        }
        for name in self.headers.keys() {
            headers.remove(name);
        }
        for (name, value) in &self.headers {
            headers.append(name, value.clone());
        }
        Ok(request)
    }
}

/// The access token of the OAuth2 scheme with token URL `url`: the cached one, else a new one.
///
/// Fetching a token sends a request, which may fetch a token: the future is boxed behind a named
/// type so the compiler proves it `Send` without following that cycle.
fn oauth_token<'a>(
    conf: &'a Configuration,
    url: &'static str,
    scope: &'static str,
) -> SyncFuture<'a, Result<OAuthUse, Error>> {
    SyncFuture::new(async move {
        let client = conf
            .credentials
            .oauth
            .as_ref()
            .ok_or_else(|| request_error("no OAuth2 client credentials"))?;
        let endpoint = token_endpoint(&conf.base_path, url);
        // Schemes of one token URL with different scopes get different tokens.
        let key = format!("{endpoint}\n{scope}");
        let fetch = SyncFuture::new(fetch_token(conf, endpoint, scope));
        let token = client.token(&key, fetch).await?;
        Ok(OAuthUse {
            url,
            scope,
            key,
            token,
        })
    })
}

/// The absolute URL of a token endpoint: an absolute-path reference is resolved against the origin
/// of the base URL, any other relative one is joined under it.
fn token_endpoint(base_path: &str, token_url: &str) -> String {
    if token_url.contains("://") {
        return token_url.to_owned();
    }
    let base = base_path.trim_end_matches('/');
    if token_url.starts_with('/') {
        if let Ok(parsed) = url::Url::parse(base) {
            return format!("{}{token_url}", parsed.origin().ascii_serialization());
        }
        return format!("{base}{token_url}");
    }
    format!("{base}/{token_url}")
}

/// Requests an access token with the client credentials grant, through the client's middleware,
/// timeout and retries like any other request. Gives the token and its lifetime, if declared.
async fn fetch_token(
    conf: &Configuration,
    endpoint: String,
    scope: &str,
) -> Result<(String, Option<Duration>), Error> {
    #[derive(serde::Deserialize)]
    struct Grant {
        access_token: String,
        #[serde(default)]
        expires_in: Option<serde_json::Value>,
    }

    let client = conf
        .credentials
        .oauth
        .as_ref()
        .ok_or_else(|| request_error("no OAuth2 client credentials"))?;
    let mut form = serde_json::Map::new();
    form.insert("grant_type".to_owned(), "client_credentials".into());
    if !scope.is_empty() {
        form.insert("scope".to_owned(), scope.into());
    }
    let mut request = Request::new(Method::POST, "").with_security(&[]);
    request.path = Cow::Owned(endpoint);
    // Another token is as good as the first: the request is safe to retry.
    request.retry_safe = true;
    if client.in_body {
        form.insert("client_id".to_owned(), client.client_id.clone().into());
        form.insert(
            "client_secret".to_owned(),
            client.client_secret.clone().into(),
        );
    } else {
        // RFC 6749 2.3.1: both are form-encoded before the base64.
        let encode = |value: &str| {
            url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
        };
        let credentials = format!(
            "{}:{}",
            encode(&client.client_id),
            encode(&client.client_secret)
        );
        request = request.with_authorization(format!("Basic {}", base64(credentials.as_bytes())));
    }
    request = request.with_form_body_param(serde_json::Value::Object(form), &[], &[]);
    let received = request.send(conf, false).await?;
    let grant: Grant = serde_json::from_slice(&received.body.bytes()?).map_err(decode_error)?;
    if grant.access_token.is_empty() {
        return Err(decode_error(
            "the token endpoint answered without an access_token",
        ));
    }
    let seconds = match grant.expires_in {
        Some(serde_json::Value::Number(number)) => number.as_f64(),
        Some(serde_json::Value::String(text)) => text.trim().parse::<f64>().ok(),
        _ => None,
    };
    let lifetime = seconds.and_then(|seconds| Duration::try_from_secs_f64(seconds.max(0.0)).ok());
    Ok((grant.access_token, lifetime))
}

/// Everything but the unreserved characters, which keeps a cookie value RFC 6265 safe.
const COOKIE_VALUE: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

/// What RFC 6265 does not allow in a cookie value: controls, space, `"`, `,`, `;` and `\`.
const API_KEY_COOKIE: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b',').add(b';').add(b'\\');

fn header(name: &str, value: &str) -> Result<(HeaderName, HeaderValue), BoxError> {
    Ok((
        HeaderName::from_bytes(name.as_bytes())?,
        HeaderValue::try_from(value)?,
    ))
}

fn open_event_stream(response: Response) -> Result<Attempt, Failure> {
    let content_type = response
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.split(';').next())
        .unwrap_or_default()
        .trim();
    if !content_type.eq_ignore_ascii_case("text/event-stream") {
        return Err(Failure::Decode(
            format!("expected a text/event-stream response, got `{content_type}`").into(),
        ));
    }
    let (status, headers) = (response.status(), response.headers().clone());
    let (body, buffered) = response.into_events();
    Ok(Attempt::Done(
        status,
        headers,
        ResponseBody::Events(body, buffered),
    ))
}

/// Exponential backoff from 500ms up to 8s with jitter.
fn backoff(retries: usize) -> Duration {
    let exponent = u32::try_from(retries).unwrap_or(u32::MAX);
    let delay = Duration::from_millis(500) * 2u32.saturating_pow(exponent);
    let jitter = 1.0 - f64::from(u16::try_from(random() % 1000).unwrap_or_default()) / 4000.0;
    delay.min(Duration::from_secs(8)).mul_f64(jitter)
}

/// Randomness for request ids and jitter, without a dependency.
pub(crate) fn random() -> u64 {
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    hasher.write_u128(
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos(),
    );
    hasher.finish()
}

/// Parses an IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`), the form `Retry-After` uses.
fn httpdate(value: &str) -> Option<SystemTime> {
    let mut parts = value.split_whitespace().skip(1);
    let day: u64 = parts.next()?.parse().ok()?;
    let month = parts.next()?;
    let month = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ]
    .iter()
    .position(|m| *m == month)? as u64
        + 1;
    let year: u64 = parts.next()?.parse().ok()?;
    let mut time = parts.next()?.split(':').map(|n| n.parse::<u64>().ok());
    let (h, m, s) = (time.next()??, time.next()??, time.next()??);
    // Days since 1970-01-01, from Howard Hinnant's `days_from_civil`.
    let (y, mo) = if month <= 2 {
        (year - 1, month + 9)
    } else {
        (year, month - 3)
    };
    let era = y / 400;
    let yoe = y - era * 400;
    let doy = (153 * mo + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = (era * 146_097 + doe).checked_sub(719_468)?;
    let seconds = days * 86_400 + h * 3600 + m * 60 + s;
    Some(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds))
}

fn scalar_text(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Bool(b) => Some(b.to_string()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

/// One parameter as query or form pairs, nested values the way Stripe-style APIs read them.
fn encode_param(
    name: &str,
    value: &serde_json::Value,
    deep_object: bool,
    explode: bool,
    out: &mut Vec<(String, String)>,
) {
    let nested = |v: &serde_json::Value| v.is_object() || v.is_array();
    match value {
        serde_json::Value::Array(items) if !deep_object && !items.iter().any(nested) => {
            let texts = items.iter().filter_map(scalar_text);
            if explode {
                out.extend(texts.map(|text| (name.to_owned(), text)));
            } else {
                let joined = texts.collect::<Vec<_>>().join(",");
                if !joined.is_empty() {
                    out.push((name.to_owned(), joined));
                }
            }
        }
        value => flatten_param(name.to_owned(), value, out),
    }
}

fn flatten_param(prefix: String, value: &serde_json::Value, out: &mut Vec<(String, String)>) {
    match value {
        serde_json::Value::Object(fields) => {
            for (key, value) in fields {
                flatten_param(format!("{prefix}[{key}]"), value, out);
            }
        }
        serde_json::Value::Array(items) => {
            for (index, item) in items.iter().enumerate() {
                if item.is_object() || item.is_array() {
                    flatten_param(format!("{prefix}[{index}]"), item, out);
                } else if let Some(text) = scalar_text(item) {
                    out.push((format!("{prefix}[]"), text));
                }
            }
        }
        value => out.extend(scalar_text(value).map(|text| (prefix, text))),
    }
}

/// A path parameter serialized by its OpenAPI `style` (`simple`, `label`, `matrix`; `json` for
/// `content`), each part percent-encoded.
fn encode_path_param(name: &str, value: &serde_json::Value, style: &str, explode: bool) -> String {
    const UNRESERVED: &AsciiSet = &percent_encoding::NON_ALPHANUMERIC
        .remove(b'-')
        .remove(b'.')
        .remove(b'_')
        .remove(b'~');
    let encode = |text: &str| utf8_percent_encode(text, UNRESERVED).to_string();
    let text = |value: &serde_json::Value| match value {
        serde_json::Value::Null => String::new(),
        serde_json::Value::Array(_) | serde_json::Value::Object(_) => value.to_string(),
        value => scalar_text(value).unwrap_or_default(),
    };
    if style == "json" {
        return encode(&value.to_string());
    }
    let name = encode(name);
    let (head, separator) = match style {
        "label" => (".", "."),
        "matrix" => (";", ";"),
        _ => ("", ","),
    };
    let encoded = match value {
        serde_json::Value::Array(items) => {
            let values: Vec<String> = items.iter().map(|item| encode(&text(item))).collect();
            match (style, explode) {
                ("matrix", true) => values.iter().map(|v| format!(";{name}={v}")).collect(),
                ("matrix", false) => format!(";{name}={}", values.join(",")),
                (_, explode) => {
                    format!(
                        "{head}{}",
                        values.join(if explode { separator } else { "," })
                    )
                }
            }
        }
        serde_json::Value::Object(fields) => {
            let pairs: Vec<(String, String)> = fields
                .iter()
                .map(|(key, value)| (encode(key), encode(&text(value))))
                .collect();
            let flat = || {
                let flat: Vec<&str> = pairs
                    .iter()
                    .flat_map(|(k, v)| [k.as_str(), v.as_str()])
                    .collect();
                flat.join(",")
            };
            match (style, explode) {
                ("matrix", true) => pairs.iter().map(|(k, v)| format!(";{k}={v}")).collect(),
                ("matrix", false) => format!(";{name}={}", flat()),
                (_, true) => {
                    let pairs: Vec<String> =
                        pairs.iter().map(|(k, v)| format!("{k}={v}")).collect();
                    format!("{head}{}", pairs.join(separator))
                }
                (_, false) => format!("{head}{}", flat()),
            }
        }
        scalar => {
            let value = encode(&text(scalar));
            match style {
                "label" => format!(".{value}"),
                "matrix" if value.is_empty() => format!(";{name}"),
                "matrix" => format!(";{name}={value}"),
                _ => value,
            }
        }
    };
    // A whole segment of dots would be resolved away by the URL.
    if encoded == "." || encoded == ".." {
        return encoded.replace('.', "%2E");
    }
    encoded
}

pub(crate) trait QueryParamValue {
    fn encode(&self) -> String;
}

macro_rules! impl_query_param_value {
    ($($ty:ty),*) => {
        $(impl QueryParamValue for $ty {
            fn encode(&self) -> String {
                self.to_string()
            }
        })*
    };
}

impl_query_param_value!(
    bool,
    i16,
    u16,
    i32,
    u32,
    i64,
    u64,
    f32,
    f64,
    String,
    &str,
    uuid::Uuid
);

impl QueryParamValue for rust_decimal::Decimal {
    fn encode(&self) -> String {
        self.to_string()
    }
}

/// A comma-separated list (`explode: false`).
impl<T: QueryParamValue> QueryParamValue for Vec<T> {
    fn encode(&self) -> String {
        self.iter().map(T::encode).collect::<Vec<_>>().join(",")
    }
}

#[cfg(test)]
mod wire_tests {
    use super::*;

    #[test]
    fn api_key_cookie_keeps_cookie_octets() {
        let sent = |key: &str| utf8_percent_encode(key, API_KEY_COOKIE).to_string();
        assert_eq!(sent("abc/def+ghi=="), "abc/def+ghi==");
        assert_eq!(sent("a b,c;d\"e\\f"), "a%20b%2Cc%3Bd%22e%5Cf");
        assert_eq!(sent("caf\u{e9}"), "caf%C3%A9");
    }

    #[test]
    fn styled_path_params_never_become_dot_segments() {
        let encode = |value: &str, style: &str| {
            encode_path_param(
                "id",
                &serde_json::Value::String(value.to_owned()),
                style,
                false,
            )
        };
        assert_eq!(encode("", "label"), "%2E");
        assert_eq!(encode(".", "label"), "%2E%2E");
        assert_eq!(encode("..", "simple"), "%2E%2E");
        assert_eq!(encode("a", "label"), ".a");
    }
}