1use std::error::Error;
6use std::future::Future;
7
8pub static TWITCH_OAUTH2_USER_AGENT: &str =
10 concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
11
12pub trait Client: Sync + Send {
14 type Error: Error + Send + Sync + 'static;
16 fn req(
18 &self,
19 request: http::Request<Vec<u8>>,
20 ) -> impl Future<Output = Result<http::Response<Vec<u8>>, <Self as Client>::Error>> + Send + use<Self>;
21}
22
23#[doc(hidden)]
24#[derive(Debug, thiserror::Error, Clone)]
25#[error("this client does not do anything, only used for documentation test that only checks code integrity")]
26pub struct DummyClient;
27
28#[cfg(feature = "reqwest")]
29impl Client for DummyClient {
30 type Error = DummyClient;
31
32 fn req(
33 &self,
34 _: http::Request<Vec<u8>>,
35 ) -> impl Future<Output = Result<http::Response<Vec<u8>>, Self::Error>> + Send + use<> {
36 std::future::ready(Err(self.clone()))
37 }
38}
39#[cfg(feature = "reqwest")]
40use reqwest::Client as ReqwestClient;
41
42#[cfg(feature = "reqwest")]
43impl Client for ReqwestClient {
44 type Error = reqwest::Error;
45
46 fn req(
47 &self,
48 request: http::Request<Vec<u8>>,
49 ) -> impl Future<Output = Result<http::Response<Vec<u8>>, Self::Error>> + Send + use<> {
50 use futures::future::Either;
51
52 let req = match reqwest::Request::try_from(request) {
54 Ok(req) => req,
55 Err(e) => return Either::Right(async move { Err(e) }),
56 };
57 let fut = self.execute(req);
59 let fut = async move {
61 let mut response = fut.await?;
62 let mut result = http::Response::builder().status(response.status());
63 let headers = result
64 .headers_mut()
65 .expect("expected to get headers mut when building response");
67 std::mem::swap(headers, response.headers_mut());
68 let result = result.version(response.version());
69 Ok(result
70 .body(response.bytes().await?.as_ref().to_vec())
71 .expect("mismatch reqwest -> http conversion should not fail"))
72 };
73 Either::Left(fut)
74 }
75}
76
77#[cfg(all(feature = "reqwest", test))]
78mod tests {
79 use super::*;
80
81 #[test]
82 fn reqwest_capture() {
84 fn inner() -> impl Future<Output = Result<http::Response<Vec<u8>>, reqwest::Error>> + Send {
85 let client = ReqwestClient::new();
86 client.req(http::Request::new(vec![]))
87 }
88 let _fut = inner();
89 }
90}