1use crate::error::{ProviderError, ProviderErrorKind};
2use async_trait::async_trait;
3use serde::Deserialize;
4use std::collections::VecDeque;
5use std::fmt;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
11#[serde(rename_all = "UPPERCASE")]
12pub enum Method {
13 Get,
14 Post,
15 Put,
16 Patch,
17 Delete,
18}
19
20impl Method {
21 pub fn as_str(self) -> &'static str {
25 match self {
26 Method::Get => "GET",
27 Method::Post => "POST",
28 Method::Put => "PUT",
29 Method::Patch => "PATCH",
30 Method::Delete => "DELETE",
31 }
32 }
33}
34
35#[derive(Clone, PartialEq, Eq)]
40pub struct HttpRequest {
41 pub method: Method,
42 pub url: String,
43 pub headers: Vec<(String, String)>,
44 pub body: Option<Vec<u8>>,
45 pub accept: Vec<String>,
46}
47
48impl HttpRequest {
49 pub fn get(url: &str) -> Self {
53 Self {
54 method: Method::Get,
55 url: url.to_string(),
56 headers: Vec::new(),
57 body: None,
58 accept: Vec::new(),
59 }
60 }
61
62 pub fn post(url: impl Into<String>, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
66 Self {
67 method: Method::Post,
68 url: url.into(),
69 headers,
70 body: Some(body),
71 accept: Vec::new(),
72 }
73 }
74
75 pub fn header(&self, name: &str) -> Option<&str> {
79 find_header(&self.headers, name)
80 }
81}
82
83impl fmt::Debug for HttpRequest {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 let names: Vec<&str> = self.headers.iter().map(|(n, _)| n.as_str()).collect();
86 f.debug_struct("HttpRequest")
87 .field("method", &self.method)
88 .field("url", &self.url)
89 .field("headers", &names)
90 .field("body_bytes", &self.body.as_ref().map(Vec::len))
91 .field("accept", &self.accept)
92 .finish()
93 }
94}
95
96#[async_trait]
100pub trait Body: Send {
101 async fn chunk(&mut self) -> Result<Option<Vec<u8>>, HttpError>;
102}
103
104#[derive(Debug, Default)]
108pub struct ChunkBody(VecDeque<Vec<u8>>);
109
110impl ChunkBody {
111 pub fn new(chunks: Vec<Vec<u8>>) -> Self {
115 Self(chunks.into())
116 }
117}
118
119#[async_trait]
120impl Body for ChunkBody {
121 async fn chunk(&mut self) -> Result<Option<Vec<u8>>, HttpError> {
122 Ok(self.0.pop_front())
123 }
124}
125
126pub struct HttpResponse {
130 pub status: u16,
131 pub url: String,
132 pub headers: Vec<(String, String)>,
133 pub body: Box<dyn Body>,
134 pub truncated: bool,
135}
136
137impl HttpResponse {
138 pub fn header(&self, name: &str) -> Option<&str> {
142 find_header(&self.headers, name)
143 }
144
145 pub fn content_type(&self) -> String {
149 self.header("content-type")
150 .map(media_type)
151 .unwrap_or_default()
152 }
153}
154
155#[async_trait]
160pub trait Transport: Send + Sync {
161 async fn send(&self, req: HttpRequest) -> Result<HttpResponse, HttpError>;
162}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum HttpErrorKind {
169 Invalid,
170 Blocked,
171 Network,
172 Timeout,
173 Rejected,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
180#[error("{message}")]
181pub struct HttpError {
182 pub kind: HttpErrorKind,
183 pub message: String,
184}
185
186impl HttpError {
187 pub fn new(kind: HttpErrorKind, message: impl Into<String>) -> Self {
191 Self {
192 kind,
193 message: message.into(),
194 }
195 }
196}
197
198impl From<HttpError> for ProviderError {
199 fn from(e: HttpError) -> Self {
200 let kind = match e.kind {
201 HttpErrorKind::Timeout => ProviderErrorKind::Stalled,
202 HttpErrorKind::Invalid | HttpErrorKind::Blocked | HttpErrorKind::Rejected => {
203 ProviderErrorKind::BadRequest
204 }
205 HttpErrorKind::Network => ProviderErrorKind::Network,
206 };
207 ProviderError::new(kind, e.message)
208 }
209}
210
211pub async fn read_limited(body: &mut dyn Body, limit: usize) -> Result<(Vec<u8>, bool), HttpError> {
215 let mut out = Vec::new();
216 while let Some(chunk) = body.chunk().await? {
217 let room = limit - out.len();
218 if chunk.len() > room {
219 out.extend_from_slice(&chunk[..room]);
220 assert!(out.len() == limit);
221 return Ok((out, true));
222 }
223 out.extend_from_slice(&chunk);
224 }
225 Ok((out, false))
226}
227
228pub fn media_type(value: &str) -> String {
232 value
233 .split(';')
234 .next()
235 .unwrap_or_default()
236 .trim()
237 .to_ascii_lowercase()
238}
239
240fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
241 headers
242 .iter()
243 .find(|(k, _)| k.eq_ignore_ascii_case(name))
244 .map(|(_, v)| v.as_str())
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 fn reply(headers: Vec<(String, String)>, chunks: Vec<&str>) -> HttpResponse {
252 let chunks = chunks.into_iter().map(|c| c.as_bytes().to_vec()).collect();
253 HttpResponse {
254 status: 200,
255 url: "https://x/".into(),
256 headers,
257 body: Box::new(ChunkBody::new(chunks)),
258 truncated: false,
259 }
260 }
261
262 #[test]
263 fn request_debug_hides_header_values() {
264 let req = HttpRequest::post(
265 "https://x/v1",
266 vec![("Authorization".into(), "Bearer k-123".into())],
267 b"{}".to_vec(),
268 );
269 let dbg = format!("{req:?}");
270 assert!(
271 dbg.contains("Authorization") && !dbg.contains("k-123"),
272 "{dbg}"
273 );
274 assert_eq!(req.header("authorization"), Some("Bearer k-123"));
275 assert_eq!(req.method.as_str(), "POST");
276 }
277
278 #[test]
279 fn content_type_is_lowercase_media_type() {
280 let r = reply(
281 vec![("Content-Type".into(), "Text/HTML; charset=utf-8".into())],
282 vec![],
283 );
284 assert_eq!(r.content_type(), "text/html");
285 assert_eq!(reply(vec![], vec![]).content_type(), "");
286 }
287
288 #[tokio::test]
289 async fn read_limited_flags_overflow() {
290 let mut r = reply(vec![], vec!["abc", "def"]);
291 assert_eq!(
292 read_limited(r.body.as_mut(), 10).await.unwrap(),
293 (b"abcdef".to_vec(), false)
294 );
295 let mut r = reply(vec![], vec!["abc", "def"]);
296 assert_eq!(
297 read_limited(r.body.as_mut(), 4).await.unwrap(),
298 (b"abcd".to_vec(), true)
299 );
300 let mut r = reply(vec![], vec!["abc"]);
301 assert_eq!(
302 read_limited(r.body.as_mut(), 3).await.unwrap(),
303 (b"abc".to_vec(), false)
304 );
305 }
306
307 #[test]
308 fn http_error_maps_to_provider_kinds() {
309 let cases = [
310 (HttpErrorKind::Timeout, ProviderErrorKind::Stalled),
311 (HttpErrorKind::Invalid, ProviderErrorKind::BadRequest),
312 (HttpErrorKind::Network, ProviderErrorKind::Network),
313 (HttpErrorKind::Blocked, ProviderErrorKind::BadRequest),
314 (HttpErrorKind::Rejected, ProviderErrorKind::BadRequest),
315 ];
316 for (from, to) in cases {
317 let e: ProviderError = HttpError::new(from, "boom").into();
318 assert_eq!((e.kind, e.message.as_str()), (to, "boom"));
319 }
320 }
321}