cdk-http-client 0.18.0-rc.0

HTTP client abstraction for CDK
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
//! bitreq-based backend implementation

use std::sync::Arc;

use bitreq::RequestExt;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::error::HttpError;
use crate::response::{RawResponse, Response};

#[derive(Debug, Clone)]
pub(crate) struct ProxyConfig {
    url: url::Url,
    matcher: Option<regex::Regex>,
}

fn validate_proxy_url(url: &url::Url) -> Response<()> {
    match url.scheme() {
        "http" => Ok(()),
        scheme => Err(HttpError::Proxy(format!(
            "Unsupported proxy URL scheme for bitreq backend: {scheme}"
        ))),
    }
}

pub(crate) fn apply_proxy_if_needed(
    request: bitreq::Request,
    url: &str,
    proxy_config: &Option<ProxyConfig>,
) -> Response<bitreq::Request> {
    if let Some(ref config) = proxy_config {
        if let Some(ref matcher) = config.matcher {
            if let Ok(parsed_url) = url::Url::parse(url) {
                if let Some(host) = parsed_url.host_str() {
                    if matcher.is_match(host) {
                        let proxy = bitreq::Proxy::new_http(&config.url)
                            .map_err(|e| HttpError::Proxy(e.to_string()))?;
                        return Ok(request.with_proxy(proxy));
                    }
                }
            }
        } else {
            let proxy = bitreq::Proxy::new_http(&config.url)
                .map_err(|e| HttpError::Proxy(e.to_string()))?;
            return Ok(request.with_proxy(proxy));
        }
    }
    Ok(request)
}

/// HTTP client wrapper
#[derive(Clone)]
pub struct HttpClient {
    inner: Arc<bitreq::Client>,
    proxy_config: Option<ProxyConfig>,
    no_redirects: bool,
}

impl std::fmt::Debug for HttpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpClient").finish()
    }
}

impl HttpClient {
    /// Create a new HTTP client with default settings
    pub fn new() -> Self {
        super::install_rustls_crypto_provider();
        Self {
            inner: Arc::new(bitreq::Client::new(10)),
            proxy_config: None,
            no_redirects: false,
        }
    }

    /// Create an HTTP client from pre-built parts
    pub(crate) fn from_parts(
        client: Arc<bitreq::Client>,
        proxy_config: Option<ProxyConfig>,
        no_redirects: bool,
    ) -> Self {
        super::install_rustls_crypto_provider();
        Self {
            inner: client,
            proxy_config,
            no_redirects,
        }
    }

    /// Create a new HTTP client builder
    pub fn builder() -> HttpClientBuilder {
        HttpClientBuilder::default()
    }

    /// Apply proxy and redirect settings to a request
    fn configure_request(&self, request: bitreq::Request, url: &str) -> Response<bitreq::Request> {
        let request = apply_proxy_if_needed(request, url, &self.proxy_config)?;
        Ok(if self.no_redirects {
            request.with_max_redirects(0)
        } else {
            request
        })
    }

    /// GET request, returns JSON deserialized to R
    pub async fn fetch<R: DeserializeOwned>(&self, url: &str) -> Response<R> {
        let request = bitreq::get(url);
        let request = self.configure_request(request, url)?;
        let response = request
            .send_async_with_client(&self.inner)
            .await
            .map_err(HttpError::from)?;
        RawResponse::new(response.status_code as u16, response.into_bytes()).json_or_status_error()
    }

    /// POST with JSON body, returns JSON deserialized to R
    pub async fn post_json<B: Serialize, R: DeserializeOwned>(
        &self,
        url: &str,
        body: &B,
    ) -> Response<R> {
        let request = bitreq::post(url).with_json(body).map_err(HttpError::from)?;
        let request = self.configure_request(request, url)?;
        let response: bitreq::Response = request
            .send_async_with_client(&self.inner)
            .await
            .map_err(HttpError::from)?;

        RawResponse::new(response.status_code as u16, response.into_bytes()).json_or_status_error()
    }

    /// POST with form data, returns JSON deserialized to R
    pub async fn post_form<F: Serialize, R: DeserializeOwned>(
        &self,
        url: &str,
        form: &F,
    ) -> Response<R> {
        let form_str = serde_urlencoded::to_string(form)
            .map_err(|e| HttpError::Serialization(e.to_string()))?;
        let request = bitreq::post(url)
            .with_body(form_str.into_bytes())
            .with_header("Content-Type", "application/x-www-form-urlencoded");
        let request = self.configure_request(request, url)?;
        let response: bitreq::Response = request
            .send_async_with_client(&self.inner)
            .await
            .map_err(HttpError::from)?;

        RawResponse::new(response.status_code as u16, response.into_bytes()).json_or_status_error()
    }

    /// PATCH with JSON body, returns JSON deserialized to R
    pub async fn patch_json<B: Serialize, R: DeserializeOwned>(
        &self,
        url: &str,
        body: &B,
    ) -> Response<R> {
        let request = bitreq::patch(url)
            .with_json(body)
            .map_err(HttpError::from)?;
        let request = self.configure_request(request, url)?;
        let response: bitreq::Response = request
            .send_async_with_client(&self.inner)
            .await
            .map_err(HttpError::from)?;

        RawResponse::new(response.status_code as u16, response.into_bytes()).json_or_status_error()
    }

    /// GET request returning raw response body
    pub async fn get_raw(&self, url: &str) -> Response<RawResponse> {
        let request = bitreq::get(url);
        let request = self.configure_request(request, url)?;
        let response = request
            .send_async_with_client(&self.inner)
            .await
            .map_err(HttpError::from)?;
        Ok(RawResponse::new(
            response.status_code as u16,
            response.into_bytes(),
        ))
    }

    /// POST request builder for complex cases
    pub fn post(&self, url: &str) -> BitreqRequestBuilder {
        BitreqRequestBuilder::new(
            bitreq::post(url),
            url,
            self.inner.clone(),
            self.proxy_config.clone(),
            self.no_redirects,
        )
    }

    /// GET request builder for complex cases
    pub fn get(&self, url: &str) -> BitreqRequestBuilder {
        BitreqRequestBuilder::new(
            bitreq::get(url),
            url,
            self.inner.clone(),
            self.proxy_config.clone(),
            self.no_redirects,
        )
    }

    /// PATCH request builder for complex cases
    pub fn patch(&self, url: &str) -> BitreqRequestBuilder {
        BitreqRequestBuilder::new(
            bitreq::patch(url),
            url,
            self.inner.clone(),
            self.proxy_config.clone(),
            self.no_redirects,
        )
    }
}

/// bitreq-based RequestBuilder wrapper
pub struct BitreqRequestBuilder {
    inner: bitreq::Request,
    error: Option<HttpError>,
    url: String,
    client: Arc<bitreq::Client>,
    proxy_config: Option<ProxyConfig>,
    no_redirects: bool,
}

impl std::fmt::Debug for BitreqRequestBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BitreqRequestBuilder")
            .field("url", &self.url)
            .field("error", &self.error)
            .finish_non_exhaustive()
    }
}

impl BitreqRequestBuilder {
    /// Create a new BitreqRequestBuilder from a bitreq::Request
    pub(crate) fn new(
        inner: bitreq::Request,
        url: &str,
        client: Arc<bitreq::Client>,
        proxy_config: Option<ProxyConfig>,
        no_redirects: bool,
    ) -> Self {
        Self {
            inner,
            error: None,
            url: url.to_string(),
            client,
            proxy_config,
            no_redirects,
        }
    }
    /// Add a header to the request.
    pub fn header(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
        Self {
            inner: self.inner.with_header(key.as_ref(), value.as_ref()),
            error: self.error,
            url: self.url,
            client: self.client,
            proxy_config: self.proxy_config,
            no_redirects: self.no_redirects,
        }
    }

    /// Set the request body as JSON.
    pub fn json<T>(mut self, body: &T) -> Self
    where
        T: Serialize,
    {
        // Preserve any error already set by an earlier builder step rather than
        // clearing it on a successful serialization.
        if self.error.is_some() {
            return self;
        }
        match self.inner.clone().with_json(body) {
            Ok(req) => self.inner = req,
            Err(e) => self.error = Some(HttpError::from(e)),
        }
        self
    }

    /// Set the request body as form data.
    pub fn form<T>(mut self, body: &T) -> Self
    where
        T: Serialize + ?Sized,
    {
        match serde_urlencoded::to_string(body) {
            Ok(form_str) => {
                self.inner = self
                    .inner
                    .with_body(form_str.into_bytes())
                    .with_header("Content-Type", "application/x-www-form-urlencoded");
            }
            Err(e) => self.error = Some(HttpError::Serialization(e.to_string())),
        }
        self
    }

    /// Send the request and return a raw response.
    pub async fn send(self) -> Response<RawResponse> {
        if let Some(err) = self.error {
            return Err(err);
        }
        let request = apply_proxy_if_needed(self.inner, &self.url, &self.proxy_config)?;
        let request = if self.no_redirects {
            request.with_max_redirects(0)
        } else {
            request
        };
        let response = request
            .send_async_with_client(&self.client)
            .await
            .map_err(HttpError::from)?;
        Ok(RawResponse::new(
            response.status_code as u16,
            response.into_bytes(),
        ))
    }

    /// Send the request and deserialize the response as JSON.
    pub async fn send_json<R: DeserializeOwned>(self) -> Response<R> {
        if let Some(err) = self.error {
            return Err(err);
        }
        let request = apply_proxy_if_needed(self.inner, &self.url, &self.proxy_config)?;
        let request = if self.no_redirects {
            request.with_max_redirects(0)
        } else {
            request
        };
        let response = request
            .send_async_with_client(&self.client)
            .await
            .map_err(HttpError::from)?;

        RawResponse::new(response.status_code as u16, response.into_bytes()).json_or_status_error()
    }
}

/// HTTP client builder for configuring proxy and TLS settings
#[derive(Debug, Default)]
pub struct HttpClientBuilder {
    proxy: Option<ProxyConfig>,
    accept_invalid_certs: bool,
    no_redirects: bool,
}

impl HttpClientBuilder {
    /// Accept invalid TLS certificates
    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }

    /// Disable automatic HTTP redirect following
    pub fn no_redirects(mut self) -> Self {
        self.no_redirects = true;
        self
    }

    /// Set an HTTP proxy URL.
    ///
    /// The `bitreq` backend supports HTTP proxy URLs only. SOCKS proxy schemes
    /// such as `socks5h` require building this crate with the `reqwest` feature.
    pub fn proxy(mut self, url: url::Url) -> Self {
        self.proxy = Some(ProxyConfig { url, matcher: None });
        self
    }

    /// Set an HTTP proxy URL with a host pattern matcher.
    ///
    /// The `bitreq` backend supports HTTP proxy URLs only. SOCKS proxy schemes
    /// such as `socks5h` require building this crate with the `reqwest` feature.
    pub fn proxy_with_matcher(mut self, url: url::Url, pattern: &str) -> Response<Self> {
        let matcher = regex::Regex::new(pattern)
            .map_err(|e| HttpError::Proxy(format!("Invalid proxy pattern: {}", e)))?;
        self.proxy = Some(ProxyConfig {
            url,
            matcher: Some(matcher),
        });
        Ok(self)
    }

    /// Build the HTTP client
    pub fn build(self) -> Response<HttpClient> {
        if self.accept_invalid_certs {
            return Err(HttpError::Build(
                "danger_accept_invalid_certs is not supported".to_string(),
            ));
        }

        if let Some(proxy) = &self.proxy {
            validate_proxy_url(&proxy.url)?;
        }

        Ok(HttpClient::from_parts(
            Arc::new(bitreq::Client::new(10)),
            self.proxy,
            self.no_redirects,
        ))
    }
}