twurst-client 0.3.4

Twirp client related code
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
#![doc = include_str!("../README.md")]
#![doc(
    test(attr(deny(warnings))),
    html_favicon_url = "https://raw.githubusercontent.com/helsing-ai/twurst/main/docs/img/twurst.png",
    html_logo_url = "https://raw.githubusercontent.com/helsing-ai/twurst/main/docs/img/twurst.png"
)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

use http::header::CONTENT_TYPE;
use http::{HeaderMap, HeaderName, HeaderValue, Method, Request, Response, StatusCode};
use http_body::{Body, Frame, SizeHint};
use http_body_util::BodyExt;
use prost_reflect::bytes::{Buf, Bytes, BytesMut};
use prost_reflect::{DeserializeOptions, DynamicMessage, ReflectMessage};
use serde::Serialize;
use std::convert::Infallible;
use std::error::Error;
use std::future::poll_fn;
use std::mem::take;
use std::pin::Pin;
use std::task::{Context, Poll};
use tower_service::Service;
pub use twurst_error::{TwirpError, TwirpErrorCode};

const APPLICATION_JSON: HeaderValue = HeaderValue::from_static("application/json");
const APPLICATION_PROTOBUF: HeaderValue = HeaderValue::from_static("application/protobuf");

/// Underlying client used by autogenerated clients to handle networking.
///
/// Can be constructed with [`TwirpHttpClient::new_using_reqwest_012`] to use [`reqwest 0.12`](reqwest_012),
/// with [`TwirpHttpClient::new_using_reqwest_013`] to use [`reqwest 0.13`](reqwest_013),
/// or from a regular [`tower::Service`](Service) using [`TwirpHttpClient::new_with_base`]
/// or [`TwirpHttpClient::new`] if relative URLs are fine.
///
/// URL grammar for twirp service is `URL ::= Base-URL [ Prefix ] "/" [ Package "." ] Service "/" Method`.
/// The `/ [ Package "." ] Service "/" Method` part is auto-generated by the build step
/// but the `Base-URL [ Prefix ]` must be set to do proper call to remote services.
/// This is the `base_url` parameter.
/// If not filled, request URL is only going to be the auto-generated part.
#[derive(Clone)]
pub struct TwirpHttpClient<S: TwirpHttpService> {
    service: S,
    base_url: Option<String>,
    use_json: bool,
}

#[cfg(feature = "reqwest-012")]
impl TwirpHttpClient<Reqwest012Service> {
    /// Builds a new client using [`reqwest 0.12`](reqwest_012).
    ///
    /// Note that `base_url` must be absolute with a scheme like `https://`.
    ///
    /// ```
    /// use twurst_client::TwirpHttpClient;
    ///
    /// let _client = TwirpHttpClient::new_using_reqwest_012("http://example.com/twirp");
    /// ```
    pub fn new_using_reqwest_012(base_url: impl Into<String>) -> Self {
        Self::new_with_reqwest_012_client(reqwest_012::Client::new(), base_url)
    }

    /// Builds a new client using [`reqwest 0.12`](reqwest_012).
    ///
    /// Note that `base_url` must be absolute with a scheme like `https://`.
    ///
    /// ```
    /// # use reqwest_012::Client;
    /// use twurst_client::TwirpHttpClient;
    ///
    /// let _client =
    ///     TwirpHttpClient::new_with_reqwest_012_client(Client::new(), "http://example.com/twirp");
    /// ```
    pub fn new_with_reqwest_012_client(
        client: reqwest_012::Client,
        base_url: impl Into<String>,
    ) -> Self {
        Self::new_with_base(Reqwest012Service(client), base_url)
    }
}

#[cfg(feature = "reqwest-013")]
impl TwirpHttpClient<Reqwest013Service> {
    /// Builds a new client using [`reqwest 0.13`](reqwest_013).
    ///
    /// Note that `base_url` must be absolute with a scheme like `https://`.
    ///
    /// ```
    /// use twurst_client::TwirpHttpClient;
    ///
    /// let _client = TwirpHttpClient::new_using_reqwest_013("http://example.com/twirp");
    /// ```
    pub fn new_using_reqwest_013(base_url: impl Into<String>) -> Self {
        Self::new_with_reqwest_013_client(reqwest_013::Client::new(), base_url)
    }

    /// Builds a new client using [`reqwest 0.13`](reqwest_013).
    ///
    /// Note that `base_url` must be absolute with a scheme like `https://`.
    ///
    /// ```
    /// # use reqwest_013::Client;
    /// use twurst_client::TwirpHttpClient;
    ///
    /// let _client =
    ///     TwirpHttpClient::new_with_reqwest_013_client(Client::new(), "http://example.com/twirp");
    /// ```
    pub fn new_with_reqwest_013_client(
        client: reqwest_013::Client,
        base_url: impl Into<String>,
    ) -> Self {
        Self::new_with_base(Reqwest013Service(client), base_url)
    }
}

impl<S: TwirpHttpService> TwirpHttpClient<S> {
    /// Builds a new client from a [`tower::Service`](Service) and a base URL to the Twirp endpoint.
    ///
    /// ```
    /// use http::Response;
    /// use std::convert::Infallible;
    /// use twurst_client::TwirpHttpClient;
    /// use twurst_error::TwirpError;
    ///
    /// let _client = TwirpHttpClient::new_with_base(
    ///     tower::service_fn(|_request| async {
    ///         Ok::<Response<String>, Infallible>(TwirpError::unimplemented("not implemented").into())
    ///     }),
    ///     "http://example.com/twirp",
    /// );
    /// ```
    pub fn new_with_base(service: S, base_url: impl Into<String>) -> Self {
        let mut base_url = base_url.into();
        // We remove the last '/' to make concatenation work
        if base_url.ends_with('/') {
            base_url.pop();
        }
        Self {
            service,
            base_url: Some(base_url),
            use_json: false,
        }
    }

    /// New service without base URL. Relative URLs will be used for requests!
    ///
    /// ```
    /// use http::Response;
    /// use std::convert::Infallible;
    /// use twurst_client::TwirpHttpClient;
    /// use twurst_error::TwirpError;
    ///
    /// let _client = TwirpHttpClient::new(tower::service_fn(|_request| async {
    ///     Ok::<Response<String>, Infallible>(TwirpError::unimplemented("not implemented").into())
    /// }));
    /// ```
    pub fn new(service: S) -> Self {
        Self {
            service,
            base_url: None,
            use_json: false,
        }
    }

    /// Use JSON for requests and response instead of binary protobuf encoding that is used by default
    pub fn use_json(&mut self) {
        self.use_json = true;
    }

    /// Use binary protobuf encoding for requests and response (the default)
    pub fn use_binary_protobuf(&mut self) {
        self.use_json = false;
    }

    /// Send a Twirp request and get a response.
    ///
    /// Used internally by the generated code.
    /// To customize the request (e.g. attach per-call headers), use [`Self::call_builder`].
    pub async fn call<I: ReflectMessage, O: ReflectMessage + Default>(
        &self,
        path: &str,
        request: &I,
    ) -> Result<O, TwirpError> {
        self.call_builder(path, request).send().await
    }

    /// Start building a Twirp call, allowing per-call customization such as extra HTTP headers.
    ///
    /// The returned [`TwirpCallBuilder`] is dispatched by calling [`TwirpCallBuilder::send`].
    ///
    /// ```
    /// use http::header::AUTHORIZATION;
    /// use http::{HeaderValue, Response};
    /// use prost_reflect::prost_types::Timestamp;
    /// use std::convert::Infallible;
    /// use twurst_client::TwirpHttpClient;
    /// use twurst_error::TwirpError;
    ///
    /// let client = TwirpHttpClient::new(tower::service_fn(|_request| async {
    ///     Ok::<Response<String>, Infallible>(TwirpError::unimplemented("not implemented").into())
    /// }));
    /// // build a call with custom headers; `.send::<ResponseType>().await` dispatches it
    /// let request = Timestamp::default();
    /// let _pending = client
    ///     .call_builder("/example.ExampleService/Test", &request)
    ///     .header(AUTHORIZATION, HeaderValue::from_static("Bearer token"))
    ///     .send::<Timestamp>();
    /// ```
    pub fn call_builder<'a, I: ReflectMessage>(
        &'a self,
        path: &'a str,
        request: &'a I,
    ) -> TwirpCallBuilder<'a, S, I> {
        let uri = match &self.base_url {
            Some(base) => format!("{base}{path}"),
            None => path.to_string(),
        };
        TwirpCallBuilder {
            client: self,
            request,
            builder: Request::builder().method(Method::POST).uri(uri),
        }
    }

    fn encode_body<T: ReflectMessage>(&self, message: &T) -> Result<TwirpRequestBody, TwirpError> {
        if self.use_json {
            Ok(json_encode(message)?.into())
        } else {
            let mut buffer = BytesMut::with_capacity(message.encoded_len());
            message.encode(&mut buffer).map_err(|e| {
                TwirpError::wrap(
                    TwirpErrorCode::Internal,
                    format!("Failed to serialize to protobuf: {e}"),
                    e,
                )
            })?;
            Ok(Bytes::from(buffer).into())
        }
    }

    fn content_type(&self) -> HeaderValue {
        if self.use_json {
            APPLICATION_JSON
        } else {
            APPLICATION_PROTOBUF
        }
    }

    async fn extract_response<T: ReflectMessage + Default>(
        &self,
        response: Response<S::ResponseBody>,
    ) -> Result<T, TwirpError> {
        // We collect the body
        // TODO: size limit
        let (parts, body) = response.into_parts();
        let body = body.collect().await.map_err(|e| {
            TwirpError::wrap(
                TwirpErrorCode::Internal,
                format!("Failed to load request body: {e}"),
                e,
            )
        })?;
        let response = Response::from_parts(parts, body);

        // Error
        if response.status() != StatusCode::OK {
            return Err(response.map(|b| b.to_bytes()).into());
        }

        // Success
        let content_type = response.headers().get(CONTENT_TYPE).cloned();
        let body = response.into_body();
        if content_type == Some(APPLICATION_PROTOBUF) {
            T::decode(body.aggregate()).map_err(|e| {
                TwirpError::wrap(
                    TwirpErrorCode::Malformed,
                    format!("Bad response binary protobuf encoding: {e}"),
                    e,
                )
            })
        } else if content_type == Some(APPLICATION_JSON) {
            json_decode(&body.to_bytes())
        } else if let Some(content_type) = content_type {
            Err(TwirpError::malformed(format!(
                "Unsupported response content-type: {}",
                String::from_utf8_lossy(content_type.as_bytes())
            )))
        } else {
            Err(TwirpError::malformed("No content-type in the response"))
        }
    }
}

/// Builder for a single Twirp call, returned by [`TwirpHttpClient::call_builder`].
///
/// Allows per-call customization (currently extra HTTP headers) before dispatching
/// the request via [`Self::send`].
#[must_use = "TwirpCallBuilder does nothing until `.send()` is awaited"]
pub struct TwirpCallBuilder<'a, S: TwirpHttpService, I> {
    client: &'a TwirpHttpClient<S>,
    request: &'a I,
    builder: http::request::Builder,
}

impl<'a, S: TwirpHttpService, I: ReflectMessage> TwirpCallBuilder<'a, S, I> {
    /// Add a header to the outgoing request.
    ///
    /// Mirrors [`http::request::Builder::header`]: any conversion error is captured
    /// in the underlying [`http::request::Builder`] and surfaced when [`Self::send`]
    /// is awaited.
    pub fn header<K, V>(mut self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        self.builder = self.builder.header(name, value);
        self
    }

    /// Mutable access to the headers configured on the underlying request builder.
    ///
    /// Returns [`None`] if a previous configuration step on this builder produced an
    /// error (mirroring [`http::request::Builder::headers_mut`]); that error will be
    /// surfaced when [`Self::send`] is awaited.
    pub fn headers_mut(&mut self) -> Option<&mut HeaderMap> {
        self.builder.headers_mut()
    }

    /// Dispatch the configured Twirp call and decode the response.
    pub async fn send<O: ReflectMessage + Default>(self) -> Result<O, TwirpError> {
        let TwirpCallBuilder {
            client,
            request,
            mut builder,
        } = self;
        // We ensure that the service is ready
        client.service.ready().await.map_err(|e| {
            TwirpError::wrap(
                TwirpErrorCode::Unknown,
                format!("Service is not ready: {e}"),
                e,
            )
        })?;
        let body = client.encode_body(request)?;
        // Force-set Content-Type after any user-supplied headers so the framework value wins.
        if let Some(headers) = builder.headers_mut() {
            headers.insert(CONTENT_TYPE, client.content_type());
        }
        let http_request = builder.body(body).map_err(|e| {
            TwirpError::wrap(
                TwirpErrorCode::Malformed,
                format!("Failed to construct request: {e}"),
                e,
            )
        })?;
        let response = client.service.call(http_request).await.map_err(|e| {
            TwirpError::wrap(
                TwirpErrorCode::Unknown,
                format!("Transport error during the request: {e}"),
                e,
            )
        })?;
        client.extract_response(response).await
    }
}

/// A service that can be used to send Twirp requests eg. an HTTP client
///
/// Used by [`TwirpHttpClient`] to handle HTTP.
#[trait_variant::make(Send)]
pub trait TwirpHttpService: 'static {
    type ResponseBody: Body<Error: Error + Send + Sync>;
    type Error: Error + Send + Sync + 'static;

    async fn ready(&self) -> Result<(), Self::Error>;

    async fn call(
        &self,
        request: Request<TwirpRequestBody>,
    ) -> Result<Response<Self::ResponseBody>, Self::Error>;
}

impl<
    S: Service<
            Request<TwirpRequestBody>,
            Error: Error + Send + Sync + 'static,
            Response = Response<RespBody>,
            Future: Send,
        > + Clone
        + Send
        + Sync
        + 'static,
    RespBody: Body<Error: Error + Send + Sync + 'static>,
> TwirpHttpService for S
{
    type ResponseBody = RespBody;
    type Error = S::Error;

    async fn ready(&self) -> Result<(), Self::Error> {
        poll_fn(|cx| Service::poll_ready(&mut self.clone(), cx)).await
    }

    async fn call(
        &self,
        request: Request<TwirpRequestBody>,
    ) -> Result<Response<RespBody>, S::Error> {
        Service::call(&mut self.clone(), request).await
    }
}

/// Request body for Twirp requests.
///
/// It is a thin wrapper on top of [`Bytes`] to implement [`Body`].
pub struct TwirpRequestBody(Bytes);

impl From<Bytes> for TwirpRequestBody {
    #[inline]
    fn from(body: Bytes) -> Self {
        Self(body)
    }
}

impl From<TwirpRequestBody> for Bytes {
    #[inline]
    fn from(body: TwirpRequestBody) -> Self {
        body.0
    }
}

impl Body for TwirpRequestBody {
    type Data = Bytes;
    type Error = Infallible;

    #[inline]
    fn poll_frame(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let data = take(&mut self.0);
        Poll::Ready(if data.has_remaining() {
            Some(Ok(Frame::data(data)))
        } else {
            None
        })
    }

    #[inline]
    fn is_end_stream(&self) -> bool {
        !self.0.has_remaining()
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        SizeHint::with_exact(self.0.remaining() as u64)
    }
}

fn json_encode<T: ReflectMessage>(message: &T) -> Result<Bytes, TwirpError> {
    let mut serializer = serde_json::Serializer::new(Vec::new());
    message
        .transcode_to_dynamic()
        .serialize(&mut serializer)
        .map_err(|e| {
            TwirpError::wrap(
                TwirpErrorCode::Malformed,
                format!("Failed to serialize request to JSON: {e}"),
                e,
            )
        })?;
    Ok(serializer.into_inner().into())
}

fn json_decode<T: ReflectMessage + Default>(message: &[u8]) -> Result<T, TwirpError> {
    let dynamic_message = dynamic_json_decode::<T>(message).map_err(|e| {
        TwirpError::wrap(
            TwirpErrorCode::Malformed,
            format!("Failed to parse JSON response: {e}"),
            e,
        )
    })?;
    dynamic_message.transcode_to().map_err(|e| {
        TwirpError::internal(format!(
            "Internal error while parsing the JSON response: {e}"
        ))
    })
}

fn dynamic_json_decode<T: ReflectMessage + Default>(
    message: &[u8],
) -> Result<DynamicMessage, serde_json::Error> {
    let mut deserializer = serde_json::Deserializer::from_slice(message);
    let dynamic_message = DynamicMessage::deserialize_with_options(
        T::default().descriptor(),
        &mut deserializer,
        // Ignore rather than returning an error when unknown fields are present following the proto3 spec:
        // https://protobuf.dev/programming-guides/proto3/#wire-safe-changes
        &DeserializeOptions::new().deny_unknown_fields(false),
    )?;
    deserializer.end()?;
    Ok(dynamic_message)
}

/// Wraps a [`reqwest::Client`](reqwest_012::Client) into a [`tower::Service`](Service) compatible with [`TwirpHttpClient`].
#[cfg(feature = "reqwest-012")]
#[derive(Clone, Default)]
pub struct Reqwest012Service(reqwest_012::Client);

#[cfg(feature = "reqwest-012")]
impl Reqwest012Service {
    #[inline]
    pub fn new() -> Self {
        reqwest_012::Client::new().into()
    }
}

#[cfg(feature = "reqwest-012")]
impl From<reqwest_012::Client> for Reqwest012Service {
    #[inline]
    fn from(client: reqwest_012::Client) -> Self {
        Self(client)
    }
}

#[cfg(feature = "reqwest-012")]
impl<B: Into<reqwest_012::Body>> Service<Request<B>> for Reqwest012Service {
    type Response = Response<reqwest_012::Body>;
    type Error = reqwest_012::Error;
    type Future = Pin<
        Box<dyn Future<Output = Result<Response<reqwest_012::Body>, reqwest_012::Error>> + Send>,
    >;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.0.poll_ready(cx)
    }

    fn call(&mut self, req: Request<B>) -> Self::Future {
        let req = match req.try_into() {
            Ok(req) => req,
            Err(e) => return Box::pin(async move { Err(e) }),
        };
        let future = self.0.call(req);
        Box::pin(async move { Ok(future.await?.into()) })
    }
}

#[cfg(feature = "reqwest-012")]
impl From<TwirpRequestBody> for reqwest_012::Body {
    #[inline]
    fn from(body: TwirpRequestBody) -> Self {
        body.0.into()
    }
}

/// Wraps a [`reqwest::Client`](reqwest_013::Client) into a [`tower::Service`](Service) compatible with [`TwirpHttpClient`].
#[cfg(feature = "reqwest-013")]
#[derive(Clone, Default)]
pub struct Reqwest013Service(reqwest_013::Client);

#[cfg(feature = "reqwest-013")]
impl Reqwest013Service {
    #[inline]
    pub fn new() -> Self {
        reqwest_013::Client::new().into()
    }
}

#[cfg(feature = "reqwest-013")]
impl From<reqwest_013::Client> for Reqwest013Service {
    #[inline]
    fn from(client: reqwest_013::Client) -> Self {
        Self(client)
    }
}

#[cfg(feature = "reqwest-013")]
impl<B: Into<reqwest_013::Body>> Service<Request<B>> for Reqwest013Service {
    type Response = Response<reqwest_013::Body>;
    type Error = reqwest_013::Error;
    type Future = Pin<
        Box<dyn Future<Output = Result<Response<reqwest_013::Body>, reqwest_013::Error>> + Send>,
    >;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.0.poll_ready(cx)
    }

    fn call(&mut self, req: Request<B>) -> Self::Future {
        let req = match req.try_into() {
            Ok(req) => req,
            Err(e) => return Box::pin(async move { Err(e) }),
        };
        let future = self.0.call(req);
        Box::pin(async move { Ok(future.await?.into()) })
    }
}

#[cfg(feature = "reqwest-013")]
impl From<TwirpRequestBody> for reqwest_013::Body {
    #[inline]
    fn from(body: TwirpRequestBody) -> Self {
        body.0.into()
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use prost_reflect::ReflectMessage;
    use prost_reflect::prost::Message;
    use prost_reflect::prost_types::Timestamp;
    use std::future::Ready;
    use std::io;
    use std::task::{Context, Poll};
    use tower::service_fn;

    const FILE_DESCRIPTOR_SET_BYTES: &[u8] = &[
        10, 107, 10, 21, 101, 120, 97, 109, 112, 108, 101, 95, 115, 101, 114, 118, 105, 99, 101,
        46, 112, 114, 111, 116, 111, 18, 7, 112, 97, 99, 107, 97, 103, 101, 34, 11, 10, 9, 77, 121,
        77, 101, 115, 115, 97, 103, 101, 74, 52, 10, 6, 18, 4, 0, 0, 5, 1, 10, 8, 10, 1, 12, 18, 3,
        0, 0, 18, 10, 8, 10, 1, 2, 18, 3, 2, 0, 16, 10, 10, 10, 2, 4, 0, 18, 4, 4, 0, 5, 1, 10, 10,
        10, 3, 4, 0, 1, 18, 3, 4, 8, 17, 98, 6, 112, 114, 111, 116, 111, 51,
    ];

    #[derive(Message, ReflectMessage, PartialEq)]
    #[prost_reflect(
        file_descriptor_set_bytes = "crate::tests::FILE_DESCRIPTOR_SET_BYTES",
        message_name = "package.MyMessage"
    )]
    pub struct MyMessage {}

    #[tokio::test]
    async fn not_ready_service() -> Result<(), Box<dyn Error>> {
        #[derive(Clone)]
        struct NotReadyService;

        impl<S> Service<S> for NotReadyService {
            type Response = Response<String>;
            type Error = TwirpError;
            type Future = Ready<Result<Response<String>, TwirpError>>;

            fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                Poll::Ready(Err(TwirpError::internal("foo")))
            }

            fn call(&mut self, _: S) -> Self::Future {
                unimplemented!()
            }
        }

        let client = TwirpHttpClient::new(NotReadyService);
        assert_eq!(
            client
                .call::<_, Timestamp>("", &Timestamp::default())
                .await
                .unwrap_err()
                .to_string(),
            "Twirp Unknown error: Service is not ready: Twirp Internal error: foo"
        );
        Ok(())
    }

    #[tokio::test]
    async fn json_request_without_base_ok() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body("\"1970-01-01T00:00:10Z\"".to_string())
                    .unwrap(),
            )
        });

        let mut client = TwirpHttpClient::new(service);
        client.use_json();
        let response = client
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await?;
        assert_eq!(
            response,
            Timestamp {
                seconds: 10,
                nanos: 0
            }
        );
        Ok(())
    }

    #[tokio::test]
    async fn call_builder_with_header_ok() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            assert_eq!(
                request.headers().get(http::header::AUTHORIZATION),
                Some(&HeaderValue::from_static("Bearer token"))
            );
            assert_eq!(
                request.headers().get("x-request-id"),
                Some(&HeaderValue::from_static("abc-123"))
            );
            assert_eq!(
                request.headers().get(CONTENT_TYPE),
                Some(&APPLICATION_PROTOBUF)
            );
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body("\"1970-01-01T00:00:10Z\"".to_string())
                    .unwrap(),
            )
        });

        let client = TwirpHttpClient::new(service);
        let response: Timestamp = client
            .call_builder(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .header(
                http::header::AUTHORIZATION,
                HeaderValue::from_static("Bearer token"),
            )
            .header("x-request-id", "abc-123")
            .send()
            .await?;
        assert_eq!(
            response,
            Timestamp {
                seconds: 10,
                nanos: 0
            }
        );
        Ok(())
    }

    #[tokio::test]
    async fn call_builder_with_headers_map_ok() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(
                request.headers().get(http::header::AUTHORIZATION),
                Some(&HeaderValue::from_static("Bearer token"))
            );
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body("\"1970-01-01T00:00:10Z\"".to_string())
                    .unwrap(),
            )
        });

        let client = TwirpHttpClient::new(service);
        let mut headers = HeaderMap::new();
        headers.insert(
            http::header::AUTHORIZATION,
            HeaderValue::from_static("Bearer token"),
        );
        let request = Timestamp::default();
        let mut builder = client.call_builder("/foo", &request);
        builder.headers_mut().unwrap().extend(headers);
        let _response: Timestamp = builder.send().await?;
        Ok(())
    }

    #[tokio::test]
    async fn call_builder_invalid_header_name_surfaces_on_send() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|_: Request<TwirpRequestBody>| async move {
            panic!("service must not be called when builder has a captured error");
            #[allow(unreachable_code)]
            Ok::<Response<String>, TwirpError>(Response::new(String::new()))
        });

        let client = TwirpHttpClient::new(service);
        let err = client
            .call_builder("/foo", &Timestamp::default())
            .header("invalid header", "value")
            .send::<Timestamp>()
            .await
            .unwrap_err();
        assert_eq!(err.code(), TwirpErrorCode::Malformed);
        assert!(
            err.message().starts_with("Failed to construct request"),
            "unexpected error message: {}",
            err.message()
        );
        Ok(())
    }

    #[tokio::test]
    async fn json_request_with_unknown_fields_ok() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body("{\"unknown_field\":\"ignored\"}".to_string())
                    .unwrap(),
            )
        });

        let mut client = TwirpHttpClient::new(service);
        client.use_json();
        let response = client
            .call::<_, MyMessage>("/foo", &MyMessage::default())
            .await?;
        assert_eq!(response, MyMessage::default());
        Ok(())
    }

    #[cfg(feature = "reqwest-012")]
    #[tokio::test]
    async fn binary_request_without_base_ok_012() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_PROTOBUF)
                    .body(reqwest_012::Body::from(
                        Timestamp {
                            seconds: 10,
                            nanos: 0,
                        }
                        .encode_to_vec(),
                    ))
                    .unwrap(),
            )
        });

        let response = TwirpHttpClient::new(service)
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await?;
        assert_eq!(
            response,
            Timestamp {
                seconds: 10,
                nanos: 0
            }
        );
        Ok(())
    }

    #[cfg(feature = "reqwest-013")]
    #[tokio::test]
    async fn binary_request_without_base_ok_013() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<_, TwirpError>(
                Response::builder()
                    .header(CONTENT_TYPE, APPLICATION_PROTOBUF)
                    .body(reqwest_013::Body::from(
                        Timestamp {
                            seconds: 10,
                            nanos: 0,
                        }
                        .encode_to_vec(),
                    ))
                    .unwrap(),
            )
        });

        let response = TwirpHttpClient::new(service)
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await?;
        assert_eq!(
            response,
            Timestamp {
                seconds: 10,
                nanos: 0
            }
        );
        Ok(())
    }

    #[tokio::test]
    async fn request_with_base_twirp_error() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "http://example.com/twirp/foo");
            Ok::<Response<String>, TwirpError>(TwirpError::not_found("not found").into())
        });

        let response_error = TwirpHttpClient::new_with_base(service, "http://example.com/twirp")
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(response_error, TwirpError::not_found("not found"));
        Ok(())
    }

    #[tokio::test]
    async fn request_with_base_other_error() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "http://example.com/twirp/foo");
            Ok::<Response<String>, TwirpError>(
                Response::builder()
                    .status(StatusCode::UNAUTHORIZED)
                    .body("foo".to_string())
                    .unwrap(),
            )
        });

        let response_error = TwirpHttpClient::new_with_base(service, "http://example.com/twirp/")
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(response_error, TwirpError::unauthenticated("foo"));
        Ok(())
    }

    #[tokio::test]
    async fn request_transport_error() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Err::<Response<String>, _>(io::Error::other("Transport error"))
        });

        let response_error = TwirpHttpClient::new(service)
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(
            response_error,
            TwirpError::new(
                TwirpErrorCode::Unknown,
                "Transport error during the request: Transport error"
            )
        );
        Ok(())
    }

    #[tokio::test]
    async fn wrong_content_type_response() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<Response<String>, TwirpError>(
                Response::builder()
                    .status(StatusCode::OK)
                    .header(CONTENT_TYPE, "foo/bar")
                    .body("foo".into())
                    .unwrap(),
            )
        });

        let response_error = TwirpHttpClient::new(service)
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(
            response_error,
            TwirpError::malformed("Unsupported response content-type: foo/bar")
        );
        Ok(())
    }

    #[tokio::test]
    async fn invalid_protobuf_response() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<Response<String>, TwirpError>(
                Response::builder()
                    .status(StatusCode::OK)
                    .header(CONTENT_TYPE, APPLICATION_PROTOBUF)
                    .body("azerty".into())
                    .unwrap(),
            )
        });

        let mut client = TwirpHttpClient::new(service);
        client.use_json();
        let response_error = client
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(
            response_error,
            TwirpError::malformed(
                "Bad response binary protobuf encoding: failed to decode Protobuf message: buffer underflow"
            )
        );
        Ok(())
    }

    #[tokio::test]
    async fn invalid_json_response() -> Result<(), Box<dyn Error>> {
        let service = service_fn(|request: Request<TwirpRequestBody>| async move {
            assert_eq!(request.method(), Method::POST);
            assert_eq!(request.uri(), "/foo");
            Ok::<Response<String>, TwirpError>(
                Response::builder()
                    .status(StatusCode::OK)
                    .header(CONTENT_TYPE, APPLICATION_JSON)
                    .body("foo".into())
                    .unwrap(),
            )
        });

        let mut client = TwirpHttpClient::new(service);
        client.use_json();
        let response_error = client
            .call::<_, Timestamp>(
                "/foo",
                &Timestamp {
                    seconds: 10,
                    nanos: 0,
                },
            )
            .await
            .unwrap_err();
        assert_eq!(
            response_error,
            TwirpError::malformed(
                "Failed to parse JSON response: expected ident at line 1 column 2"
            )
        );
        Ok(())
    }

    #[tokio::test]
    async fn response_future_is_send() {
        fn is_send<T: Send>(_: T) {}

        let service = service_fn(|_: Request<TwirpRequestBody>| async move {
            Ok::<_, TwirpError>(Response::new(String::new()))
        });
        let client = TwirpHttpClient::new(service);

        // This will fail to compile if the future is not Send
        is_send(client.call::<_, Timestamp>("/foo", &Timestamp::default()));
    }
}