| 1 | use crate::{Requester, RequesterBuilder}; |
| 2 | use async_trait::async_trait; |
| 3 | use std::collections::HashMap; |
| 4 | |
| 5 | #[derive(Clone)] |
| 6 | pub struct ReqwestRequester(reqwest::Client); |
| 7 | |
| 8 | impl ReqwestRequester { |
| 9 | pub fn inner(&self) -> &reqwest::Client { |
| 10 | &self.0 |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | #[cfg_attr(feature = "rt-multi-thread", async_trait)] |
| 15 | #[cfg_attr(not(feature = "rt-multi-thread"), async_trait(?Send))] |
| 16 | impl Requester for ReqwestRequester { |
| 17 | type Error = ReqwestRequesterError; |
| 18 | |
| 19 | async fn get( |
| 20 | &self, |
| 21 | url: &url::Url, |
| 22 | body: &[u8], |
| 23 | headers: HashMap<&str, &str>, |
| 24 | ) -> Result<Vec<u8>, Self::Error> { |
| 25 | self.request(reqwest::Method::GET, url, body, headers).await |
| 26 | } |
| 27 | |
| 28 | async fn post( |
| 29 | &self, |
| 30 | url: &url::Url, |
| 31 | body: &[u8], |
| 32 | headers: HashMap<&str, &str>, |
| 33 | ) -> Result<Vec<u8>, Self::Error> { |
| 34 | self.request(reqwest::Method::POST, url, body, headers) |
| 35 | .await |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | pub struct ReqwestRequesterBuilder(reqwest::ClientBuilder); |
| 40 | |
| 41 | impl RequesterBuilder for ReqwestRequesterBuilder { |
| 42 | type Requester = ReqwestRequester; |
| 43 | |
| 44 | fn with_pem_bundle(mut self, bytes: &[u8]) -> Self { |
| 45 | // TODO: Error when certificate parsing failed? |
| 46 | let certificates = reqwest::tls::Certificate::from_pem_bundle(bytes).unwrap_or_default(); |
| 47 | for c in certificates { |
| 48 | self.0 = self.0.add_root_certificate(c); |
| 49 | } |
| 50 | self |
| 51 | } |
| 52 | |
| 53 | fn build(self) -> Self::Requester { |
| 54 | // TODO: Fail when not able to build? |
| 55 | ReqwestRequester(self.0.build().unwrap_or_default()) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | impl Default for ReqwestRequesterBuilder { |
| 60 | fn default() -> Self { |
| 61 | Self(reqwest::Client::builder()) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl ReqwestRequester { |
| 66 | pub fn new() -> Self { |
| 67 | Self(reqwest::Client::new()) |
| 68 | } |
| 69 | |
| 70 | async fn request( |
| 71 | &self, |
| 72 | method: reqwest::Method, |
| 73 | url: &url::Url, |
| 74 | body: &[u8], |
| 75 | headers: HashMap<&str, &str>, |
| 76 | ) -> Result<Vec<u8>, ReqwestRequesterError> { |
| 77 | log::trace!( |
| 78 | "{}: URL: {}, Body: {}, Headers: {:?}", |
| 79 | method, |
| 80 | url, |
| 81 | String::from_utf8_lossy(body), |
| 82 | headers |
| 83 | ); |
| 84 | let body = body.to_vec(); |
| 85 | // TODO: Fail on parsing header. |
| 86 | let mut req = self.0.request(method, url.clone()).body(body); |
| 87 | |
| 88 | for (key, value) in headers { |
| 89 | req = req.header(key, value); |
| 90 | } |
| 91 | |
| 92 | let response = req.send().await?; |
| 93 | |
| 94 | let status = response.status(); |
| 95 | let bytes = response.bytes().await?; |
| 96 | |
| 97 | if status.is_success() { |
| 98 | Ok(bytes.to_vec()) |
| 99 | } else { |
| 100 | log::error!( |
| 101 | "Request was not successfull; returned body: {}", |
| 102 | String::from_utf8_lossy(&bytes) |
| 103 | ); |
| 104 | Err(ReqwestRequesterError::NoSuccessStatusCode( |
| 105 | status.as_u16(), |
| 106 | status.canonical_reason(), |
| 107 | bytes.to_vec(), |
| 108 | )) |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl Default for ReqwestRequester { |
| 114 | fn default() -> Self { |
| 115 | Self::new() |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | #[derive(Debug)] |
| 120 | pub enum ReqwestRequesterError { |
| 121 | /// reqwest failed. |
| 122 | Reqwest(reqwest::Error), |
| 123 | /// Got a status code which is no success. |
| 124 | /// Contains the status code, the "canonical reason" and the body bytes. |
| 125 | NoSuccessStatusCode(u16, Option<&'static str>, Vec<u8>), |
| 126 | } |
| 127 | |
| 128 | impl std::fmt::Display for ReqwestRequesterError { |
| 129 | fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { |
| 130 | match self { |
| 131 | Self::Reqwest(e) => write!(fmt, "reqwest error: {}", e), |
| 132 | Self::NoSuccessStatusCode(code, Some(reason), _) => { |
| 133 | write!(fmt, "unsuccessful status code {} ({})", code, reason) |
| 134 | } |
| 135 | Self::NoSuccessStatusCode(code, None, _) => { |
| 136 | write!(fmt, "unsuccessful status code {}", code) |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | impl std::error::Error for ReqwestRequesterError {} |
| 143 | |
| 144 | impl From<reqwest::Error> for ReqwestRequesterError { |
| 145 | fn from(e: reqwest::Error) -> ReqwestRequesterError { |
| 146 | Self::Reqwest(e) |
| 147 | } |
| 148 | } |