Skip to main content

troupekit_core/
http.rs

1use crate::error::{ProviderError, ProviderErrorKind};
2use async_trait::async_trait;
3use serde::Deserialize;
4use std::collections::VecDeque;
5use std::fmt;
6
7/// HTTP method of a request.
8/// Deserializes from upper-case names such as `GET` and `POST`;
9/// `as_str` gives the same upper-case name for the wire.
10#[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    /// Returns the method's upper-case wire name, such as `GET`.
22    /// Transports build their client's method from it.
23    /// Never fails.
24    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/// One outgoing HTTP request for any transport.
36/// `accept` lists the media types a 2xx answer may have (empty accepts any;
37/// guarded transports enforce it). Debug prints header names only, so a
38/// request holding an API key can be logged safely.
39#[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    /// Builds a GET request for `url` with no headers, no body and any
50    /// accepted media type.
51    /// Returns the request for further field edits.
52    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    /// Builds a POST request for `url` with `headers` and the `body` bytes.
63    /// Any media type is accepted.
64    /// Returns the request.
65    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    /// Looks up request header `name`, ignoring ASCII case.
76    /// When a header repeats, the first value wins.
77    /// Returns the value, or `None` when absent.
78    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/// The body of an HTTP reply, read chunk by chunk so streams stay streams.
97/// `chunk` yields the next bytes, then `None` once the body has ended.
98/// Transports implement it over their own body type.
99#[async_trait]
100pub trait Body: Send {
101    async fn chunk(&mut self) -> Result<Option<Vec<u8>>, HttpError>;
102}
103
104/// A body already held in memory as a list of chunks.
105/// Fakes and transports that read eagerly hand it out; chunks come back
106/// in order and the body ends after the last one.
107#[derive(Debug, Default)]
108pub struct ChunkBody(VecDeque<Vec<u8>>);
109
110impl ChunkBody {
111    /// Builds a body that yields `chunks` first to last.
112    /// An empty list is an empty body.
113    /// Returns the body.
114    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
126/// An HTTP reply: status, final URL after redirects, headers, a body still
127/// to be read, and `truncated` when the transport cut the body at its own
128/// size limit. Header names keep the case the transport saw.
129pub 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    /// Looks up reply header `name`, ignoring ASCII case.
139    /// When a header repeats, the first value wins.
140    /// Returns the value, or `None` when absent.
141    pub fn header(&self, name: &str) -> Option<&str> {
142        find_header(&self.headers, name)
143    }
144
145    /// Returns the reply's media type in lower case without parameters,
146    /// such as `text/html` for `Text/HTML; charset=utf-8`.
147    /// Returns an empty string when there is no content type.
148    pub fn content_type(&self) -> String {
149        self.header("content-type")
150            .map(media_type)
151            .unwrap_or_default()
152    }
153}
154
155/// Sends HTTP requests. HTTP clients, guarded clients, proxies and test
156/// fakes implement it, so models and tools never own an HTTP stack.
157/// Returns `Ok` for any status the server sent and `Err` when the request
158/// was refused, failed in transport or broke a limit.
159#[async_trait]
160pub trait Transport: Send + Sync {
161    async fn send(&self, req: HttpRequest) -> Result<HttpResponse, HttpError>;
162}
163
164/// Kind of a failed transport call.
165/// `Invalid` is a malformed request, `Blocked` a refused address or scheme,
166/// `Rejected` a reply that broke a request rule, `Timeout` a time limit.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub enum HttpErrorKind {
169    Invalid,
170    Blocked,
171    Network,
172    Timeout,
173    Rejected,
174}
175
176/// A failed transport call: its kind and a message without secrets.
177/// Converts into `ProviderError` here and into tool errors in the tools
178/// crate, keeping the message. Displays as the message.
179#[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    /// Builds an error of `kind` with `message`.
188    /// The message must not hold secrets; it is shown and logged.
189    /// Returns the error.
190    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
211/// Reads `body` into memory, keeping at most `limit` bytes.
212/// Returns the bytes and `true` when more bytes arrived than were kept;
213/// reading stops at the first byte past the limit.
214pub 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
228/// Reduces a `Content-Type` header value to its media type: the part
229/// before any `;`, trimmed and in lower case, so `Text/HTML; charset=utf-8`
230/// becomes `text/html`. Returns an empty string for an empty value.
231pub 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}