1use std::collections::HashMap;
28use std::time::Duration;
29
30use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
31use reqwest::{Client, Method, Response as ReqwestResponse};
32use serde::Serialize;
33
34use super::collection::Collection;
35
36#[derive(Debug, thiserror::Error)]
37pub enum HttpError {
38 #[error("HTTP request failed: {0}")]
39 RequestFailed(String),
40}
41
42impl From<reqwest::Error> for HttpError {
43 fn from(e: reqwest::Error) -> Self {
44 HttpError::RequestFailed(e.to_string())
45 }
46}
47
48#[derive(Debug, Clone)]
49pub enum Body {
50 Json(serde_json::Value),
51 Form(Vec<(String, String)>),
52 Text(String),
53 None,
54}
55
56#[derive(Debug, Clone)]
57pub struct PendingRequest {
58 client: Option<Client>,
59 base_url: Option<String>,
60 headers: HeaderMap,
61 query: Vec<(String, String)>,
62 timeout: Option<Duration>,
63 retry_max: Option<usize>,
64 retry_delay: Option<Duration>,
65 body: Body,
66}
67
68impl Default for PendingRequest {
69 fn default() -> Self {
70 Self::new()
71 }
72}
73
74impl PendingRequest {
75 pub fn new() -> Self {
76 Self {
77 client: None,
78 base_url: None,
79 headers: HeaderMap::new(),
80 query: Vec::new(),
81 timeout: None,
82 retry_max: None,
83 retry_delay: None,
84 body: Body::None,
85 }
86 }
87
88 pub fn with_token(mut self, token: &str) -> Self {
89 let value = HeaderValue::from_str(&format!("Bearer {}", token)).unwrap();
90 self.headers.insert(reqwest::header::AUTHORIZATION, value);
91 self
92 }
93
94 pub fn with_basic_auth(mut self, username: &str, password: &str) -> Self {
95 let encoded = base64::Engine::encode(
96 &base64::engine::general_purpose::STANDARD,
97 format!("{}:{}", username, password),
98 );
99 let value = HeaderValue::from_str(&format!("Basic {}", encoded)).unwrap();
100 self.headers.insert(reqwest::header::AUTHORIZATION, value);
101 self
102 }
103
104 pub fn with_header(mut self, name: &str, value: &str) -> Self {
105 if let (Ok(name), Ok(value)) = (
106 HeaderName::from_bytes(name.as_bytes()),
107 HeaderValue::from_str(value),
108 ) {
109 self.headers.insert(name, value);
110 }
111 self
112 }
113
114 pub fn with_headers(mut self, headers: HashMap<&str, &str>) -> Self {
115 for (name, value) in headers {
116 if let (Ok(name), Ok(value)) = (
117 HeaderName::from_bytes(name.as_bytes()),
118 HeaderValue::from_str(value),
119 ) {
120 self.headers.insert(name, value);
121 }
122 }
123 self
124 }
125
126 pub fn accept(mut self, mime: &str) -> Self {
127 let value = HeaderValue::from_str(mime).unwrap();
128 self.headers.insert(reqwest::header::ACCEPT, value);
129 self
130 }
131
132 pub fn accept_json(self) -> Self {
133 self.accept("application/json")
134 }
135
136 pub fn content_type(mut self, mime: &str) -> Self {
137 let value = HeaderValue::from_str(mime).unwrap();
138 self.headers.insert(reqwest::header::CONTENT_TYPE, value);
139 self
140 }
141
142 pub fn timeout(mut self, duration: Duration) -> Self {
143 self.timeout = Some(duration);
144 self
145 }
146
147 pub fn retry(mut self, max: usize, delay: Duration) -> Self {
148 self.retry_max = Some(max);
149 self.retry_delay = Some(delay);
150 self
151 }
152
153 pub fn with_query(mut self, params: Vec<(&str, &str)>) -> Self {
154 self.query = params
155 .into_iter()
156 .map(|(k, v)| (k.to_string(), v.to_string()))
157 .collect();
158 self
159 }
160
161 pub fn base_url(mut self, url: &str) -> Self {
162 self.base_url = Some(url.to_string());
163 self
164 }
165
166 pub fn body(mut self, body: &str) -> Self {
167 self.body = Body::Text(body.to_string());
168 self
169 }
170
171 pub fn json<T: Serialize>(mut self, value: &T) -> Self {
172 let json_value = serde_json::to_value(value).unwrap_or(serde_json::Value::Null);
173 self.body = Body::Json(json_value);
174 self.content_type("application/json")
175 }
176
177 pub fn form<T: Serialize>(mut self, value: &T) -> Self {
178 let pairs = serde_urlencoded::to_string(value).unwrap_or_default();
179 self.body = Body::Text(pairs);
180 self.content_type("application/x-www-form-urlencoded")
181 }
182
183 pub fn as_form(mut self, pairs: Vec<(&str, &str)>) -> Self {
184 let encoded = serde_urlencoded::to_string(&pairs).unwrap_or_default();
185 self.body = Body::Text(encoded);
186 self.content_type("application/x-www-form-urlencoded")
187 }
188
189 async fn build_client(&self) -> Client {
190 if let Some(client) = &self.client {
191 return client.clone();
192 }
193 let mut builder = Client::builder();
194 if let Some(timeout) = self.timeout {
195 builder = builder.timeout(timeout);
196 }
197 builder.build().unwrap_or_default()
198 }
199
200 fn resolve_url(&self, url: &str) -> String {
201 match &self.base_url {
202 Some(base) => {
203 let base = base.trim_end_matches('/');
204 let path = url.trim_start_matches('/');
205 format!("{}/{}", base, path)
206 }
207 None => url.to_string(),
208 }
209 }
210
211 async fn do_request(&self, method: Method, url: &str) -> Result<Response, HttpError> {
212 let client = self.build_client().await;
213 let url = self.resolve_url(url);
214
215 let mut req = client.request(method.clone(), &url);
216
217 req = req.headers(self.headers.clone());
218
219 if !self.query.is_empty() {
220 req = req.query(&self.query);
221 }
222
223 req = match &self.body {
224 Body::Json(value) => req.json(value),
225 Body::Text(text) => req.body(text.clone()),
226 Body::Form(pairs) => req.form(pairs),
227 Body::None => req,
228 };
229
230 let max_retries = self.retry_max.unwrap_or(0);
231 let retry_delay = self.retry_delay.unwrap_or(Duration::from_millis(100));
232
233 let mut last_error = None;
234
235 for attempt in 0..=max_retries {
236 if attempt > 0 {
237 tokio::time::sleep(retry_delay).await;
238 }
239
240 match req.try_clone() {
241 Some(cloned_req) => match cloned_req.send().await {
242 Ok(resp) => return Ok(Response::new(resp)),
243 Err(e) => {
244 last_error = Some(e);
245 }
246 },
247 None => {
248 let resp = req
249 .try_clone()
250 .ok_or_else(|| {
251 HttpError::RequestFailed("request body cannot be retried".into())
252 })?
253 .send()
254 .await?;
255 return Ok(Response::new(resp));
256 }
257 }
258 }
259
260 Err(HttpError::RequestFailed(format!(
261 "HTTP request failed after {} retries: {:?}",
262 max_retries,
263 last_error.map(|e| e.to_string()).unwrap_or_default()
264 )))
265 }
266
267 pub async fn get(&self, url: &str) -> Result<Response, HttpError> {
268 self.do_request(Method::GET, url).await
269 }
270
271 pub async fn post(&self, url: &str) -> Result<Response, HttpError> {
272 self.do_request(Method::POST, url).await
273 }
274
275 pub async fn put(&self, url: &str) -> Result<Response, HttpError> {
276 self.do_request(Method::PUT, url).await
277 }
278
279 pub async fn patch(&self, url: &str) -> Result<Response, HttpError> {
280 self.do_request(Method::PATCH, url).await
281 }
282
283 pub async fn delete(&self, url: &str) -> Result<Response, HttpError> {
284 self.do_request(Method::DELETE, url).await
285 }
286
287 pub async fn head(&self, url: &str) -> Result<Response, HttpError> {
288 self.do_request(Method::HEAD, url).await
289 }
290}
291
292#[derive(Debug)]
293pub struct Response {
294 inner: ReqwestResponse,
295}
296
297impl Response {
298 pub fn new(response: ReqwestResponse) -> Self {
299 Self { inner: response }
300 }
301
302 pub fn status(&self) -> reqwest::StatusCode {
303 self.inner.status()
304 }
305
306 pub fn ok(&self) -> bool {
307 self.inner.status().is_success()
308 }
309
310 pub fn client_error(&self) -> bool {
311 self.inner.status().is_client_error()
312 }
313
314 pub fn server_error(&self) -> bool {
315 self.inner.status().is_server_error()
316 }
317
318 pub fn status_code(&self) -> u16 {
319 self.inner.status().as_u16()
320 }
321
322 pub async fn text(self) -> Result<String, HttpError> {
323 self.inner.text().await.map_err(HttpError::from)
324 }
325
326 pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, HttpError> {
327 self.inner.json().await.map_err(HttpError::from)
328 }
329
330 pub async fn body(self) -> Result<Vec<u8>, HttpError> {
331 self.inner
332 .bytes()
333 .await
334 .map(|b| b.to_vec())
335 .map_err(HttpError::from)
336 }
337
338 pub fn headers(&self) -> &HeaderMap {
339 self.inner.headers()
340 }
341
342 pub fn header(&self, name: &str) -> Option<&HeaderValue> {
343 self.inner.headers().get(name)
344 }
345
346 pub async fn collect_headers(self) -> Collection<(String, String)> {
347 let headers: Vec<(String, String)> = self
348 .inner
349 .headers()
350 .iter()
351 .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
352 .collect();
353 Collection::new(headers)
354 }
355}
356
357impl std::fmt::Display for Response {
358 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359 write!(
360 f,
361 "Response {} {}",
362 self.status_code(),
363 self.status().canonical_reason().unwrap_or("")
364 )
365 }
366}
367
368pub struct Http;
369
370impl Http {
371 #[allow(clippy::new_ret_no_self)]
372 pub fn new() -> PendingRequest {
373 PendingRequest::new()
374 }
375
376 pub fn with_token(token: &str) -> PendingRequest {
377 PendingRequest::new().with_token(token)
378 }
379
380 pub fn with_basic_auth(username: &str, password: &str) -> PendingRequest {
381 PendingRequest::new().with_basic_auth(username, password)
382 }
383
384 pub fn accept_json() -> PendingRequest {
385 PendingRequest::new().accept_json()
386 }
387
388 pub fn timeout(duration: Duration) -> PendingRequest {
389 PendingRequest::new().timeout(duration)
390 }
391
392 pub fn base_url(url: &str) -> PendingRequest {
393 PendingRequest::new().base_url(url)
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn test_pending_request_new() {
403 let req = PendingRequest::new();
404 assert!(req.headers.is_empty());
405 assert!(req.query.is_empty());
406 assert!(req.timeout.is_none());
407 }
408
409 #[test]
410 fn test_with_token_header() {
411 let req = PendingRequest::new().with_token("my-token");
412 let auth = req
413 .headers
414 .get(reqwest::header::AUTHORIZATION)
415 .unwrap()
416 .to_str()
417 .unwrap()
418 .to_string();
419 assert_eq!(auth, "Bearer my-token");
420 }
421
422 #[test]
423 fn test_with_header() {
424 let req = PendingRequest::new().with_header("X-Custom", "value");
425 assert_eq!(
426 req.headers.get("x-custom").unwrap().to_str().unwrap(),
427 "value"
428 );
429 }
430
431 #[test]
432 fn test_accept_json() {
433 let req = PendingRequest::new().accept_json();
434 assert_eq!(
435 req.headers
436 .get(reqwest::header::ACCEPT)
437 .unwrap()
438 .to_str()
439 .unwrap(),
440 "application/json"
441 );
442 }
443
444 #[test]
445 fn test_content_type() {
446 let req = PendingRequest::new().content_type("application/xml");
447 assert_eq!(
448 req.headers
449 .get(reqwest::header::CONTENT_TYPE)
450 .unwrap()
451 .to_str()
452 .unwrap(),
453 "application/xml"
454 );
455 }
456
457 #[test]
458 fn test_with_query() {
459 let req = PendingRequest::new().with_query(vec![("key", "value")]);
460 assert_eq!(req.query.len(), 1);
461 assert_eq!(req.query[0], ("key".to_string(), "value".to_string()));
462 }
463
464 #[test]
465 fn test_base_url() {
466 let req = PendingRequest::new().base_url("https://api.example.com");
467 assert_eq!(req.base_url, Some("https://api.example.com".to_string()));
468 }
469
470 #[test]
471 fn test_resolve_url() {
472 let req = PendingRequest::new().base_url("https://api.example.com/");
473 assert_eq!(
474 req.resolve_url("/v1/users"),
475 "https://api.example.com/v1/users"
476 );
477 }
478
479 #[test]
480 fn test_retry_config() {
481 let req = PendingRequest::new().retry(3, Duration::from_secs(1));
482 assert_eq!(req.retry_max, Some(3));
483 assert_eq!(req.retry_delay, Some(Duration::from_secs(1)));
484 }
485
486 #[test]
487 fn test_timeout_config() {
488 let req = PendingRequest::new().timeout(Duration::from_secs(30));
489 assert_eq!(req.timeout, Some(Duration::from_secs(30)));
490 }
491
492 #[test]
493 fn test_http_facade_new() {
494 let req = Http::new();
495 assert!(req.headers.is_empty());
496 }
497
498 #[test]
499 fn test_http_facade_with_token() {
500 let req = Http::with_token("token-123");
501 let auth = req
502 .headers
503 .get(reqwest::header::AUTHORIZATION)
504 .unwrap()
505 .to_str()
506 .unwrap()
507 .to_string();
508 assert_eq!(auth, "Bearer token-123");
509 }
510
511 #[test]
512 fn test_http_facade_accept_json() {
513 let req = Http::accept_json();
514 assert!(req.headers.get(reqwest::header::ACCEPT).is_some());
515 }
516
517 #[test]
518 fn test_json_body_sets_content_type() {
519 let req = PendingRequest::new().json(&serde_json::json!({"key": "value"}));
520 assert!(matches!(req.body, Body::Json(_)));
521 assert_eq!(
522 req.headers
523 .get(reqwest::header::CONTENT_TYPE)
524 .unwrap()
525 .to_str()
526 .unwrap(),
527 "application/json"
528 );
529 }
530
531 #[test]
532 fn test_form_body_sets_content_type() {
533 let req = PendingRequest::new().form(&vec![("key", "value")]);
534 assert_eq!(
535 req.headers
536 .get(reqwest::header::CONTENT_TYPE)
537 .unwrap()
538 .to_str()
539 .unwrap(),
540 "application/x-www-form-urlencoded"
541 );
542 }
543}