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
use std::marker::PhantomData;

use reqwest::header::CONTENT_TYPE;

pub trait Request {
    /// Type to deserialize from the http response body
    type Response;
    /// HTTP method that the request will be sent with
    fn method(&self) -> HttpMethod;
    /// String to appended to the end of url when sending this request.
    fn path(&self) -> String;
}

/// A client to delegate to the send function that provides the ability to
/// optionally specify:
/// - a base url to be used for all requests
/// - a request group to constrain the request types accepted by this type
#[derive(Debug, Clone)]
pub struct Client<RequestGroup = All> {
    base_url: String,
    _p: PhantomData<RequestGroup>,
}

impl<RequestGroup> Client<RequestGroup> {
    pub fn new(base_url: String) -> Self {
        Self {
            base_url,
            _p: PhantomData,
        }
    }

    /// Send the provided request to the host at the specified base url, using
    /// the request metadata specified by the Request implementation. This
    /// method upgrades from the `send` function by enabling you to constrain
    /// the request group with the type system.
    pub async fn send_to<Req>(base_url: &str, request: Req) -> Result<Req::Response, Error>
    where
        Req: Request + serde::Serialize + InRequestGroup<RequestGroup>,
        Req::Response: for<'a> serde::Deserialize<'a>,
    {
        send(base_url, request).await
    }

    /// Send the provided request to the host at the specified base url, using
    /// the request metadata specified by the Request implementation. This
    /// method upgrades from the `send_to` method by allowing you specify the
    /// base url at the time of instantiation rather than passing it to every
    /// `send` call.
    pub async fn send<Req>(&self, request: Req) -> Result<Req::Response, Error>
    where
        Req: Request + serde::Serialize + InRequestGroup<RequestGroup>,
        Req::Response: for<'a> serde::Deserialize<'a>,
    {
        send(&self.base_url, request).await
    }
}

/// Send the provided request to the host at the specified base url, using the
/// request metadata specified by the Request implementation.
pub async fn send<Req>(base_url: &str, request: Req) -> Result<Req::Response, Error>
where
    Req: Request + serde::Serialize,
    Req::Response: for<'a> serde::Deserialize<'a>,
{
    let url = join_url(base_url, request.path());
    send_custom(&url, request.method(), request).await
}

/// Send the provided request to the host at the specified base url using the
/// specified method, and deserialize the response as the specified response
/// type
pub async fn send_custom<Req, Res>(
    url: &str,
    method: HttpMethod,
    request: Req,
) -> Result<Res, Error>
where
    Req: serde::Serialize,
    Res: for<'a> serde::Deserialize<'a>,
{
    let response = reqwest::Client::new()
        .request(method.into(), url)
        .body(
            serde_json::to_string(&request)
                .map_err(Error::SerializationError)?
                .into_bytes(),
        )
        .header(CONTENT_TYPE, "application/json")
        .send()
        .await?;
    let status = response.status();
    if status.is_success() {
        let body = response.bytes().await?;
        serde_json::from_slice(&body).map_err(|error| Error::DeserializationError {
            error,
            response_body: body_bytes_to_str(&body),
        })
    } else {
        let message = match response.bytes().await {
            Ok(bytes) => body_bytes_to_str(&bytes),
            Err(e) => format!("failed to get body: {e:?}"),
        };
        Err(Error::InvalidStatusCode(status.into(), message))
    }
}

fn body_bytes_to_str(bytes: &[u8]) -> String {
    match std::str::from_utf8(bytes) {
        Ok(message) => message.to_owned(),
        Err(e) => format!("could not read message body as a string: {e:?}"),
    }
}

/// Define a request group to constrain which requests can be used with a client.
/// ```ignore
/// request_group!(MyApi { MyRequest1, MyRequest2 });
/// ```
#[macro_export]
macro_rules! request_group {
    ($viz:vis $Name:ident { $($Request:ident),*$(,)? }) => {
        $viz struct $Name;
        $(impl $crate::InRequestGroup<$Name> for $Request {})*
    };
}

/// Indicates that a request is part of a request group. If you use the
/// request_group macro to define the group, it will handle the implementation
/// of this trait automatically.
pub trait InRequestGroup<Group> {}

/// The default group. All requests are in this group.
pub struct All;
impl<T> InRequestGroup<All> for T {}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("reqwest error: {0}")]
    ClientError(#[from] reqwest::Error),
    #[error("serde serialization error: {0}")]
    SerializationError(serde_json::error::Error),
    #[error("serde deserialization error `{error}` while parsing response body: {response_body}")]
    DeserializationError {
        error: serde_json::error::Error,
        response_body: String,
    },
    #[error("invalid status code {0} with response body: `{1}`")]
    InvalidStatusCode(u16, String),
}

#[derive(Debug, Clone, Copy)]
pub enum HttpMethod {
    Options,
    Get,
    Post,
    Put,
    Delete,
    Head,
    Trace,
    Connect,
    Patch,
}

impl From<HttpMethod> for reqwest::Method {
    fn from(value: HttpMethod) -> Self {
        match value {
            HttpMethod::Options => reqwest::Method::OPTIONS,
            HttpMethod::Get => reqwest::Method::GET,
            HttpMethod::Post => reqwest::Method::POST,
            HttpMethod::Put => reqwest::Method::PUT,
            HttpMethod::Delete => reqwest::Method::DELETE,
            HttpMethod::Head => reqwest::Method::HEAD,
            HttpMethod::Trace => reqwest::Method::TRACE,
            HttpMethod::Connect => reqwest::Method::CONNECT,
            HttpMethod::Patch => reqwest::Method::PATCH,
        }
    }
}

fn join_url(base_url: &str, path: String) -> String {
    if base_url.chars().last().map(|c| c == '/').unwrap_or(true)
        || path.chars().next().map(|c| c == '/').unwrap_or(true)
    {
        format!("{base_url}{}", path)
    } else {
        format!("{base_url}/{}", path)
    }
}