use crate::error::{ProviderError, ProviderErrorKind};
use async_trait::async_trait;
use serde::Deserialize;
use std::collections::VecDeque;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Method {
Get,
Post,
Put,
Patch,
Delete,
}
impl Method {
pub fn as_str(self) -> &'static str {
match self {
Method::Get => "GET",
Method::Post => "POST",
Method::Put => "PUT",
Method::Patch => "PATCH",
Method::Delete => "DELETE",
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct HttpRequest {
pub method: Method,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
pub accept: Vec<String>,
}
impl HttpRequest {
pub fn get(url: &str) -> Self {
Self {
method: Method::Get,
url: url.to_string(),
headers: Vec::new(),
body: None,
accept: Vec::new(),
}
}
pub fn post(url: impl Into<String>, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
Self {
method: Method::Post,
url: url.into(),
headers,
body: Some(body),
accept: Vec::new(),
}
}
pub fn header(&self, name: &str) -> Option<&str> {
find_header(&self.headers, name)
}
}
impl fmt::Debug for HttpRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names: Vec<&str> = self.headers.iter().map(|(n, _)| n.as_str()).collect();
f.debug_struct("HttpRequest")
.field("method", &self.method)
.field("url", &self.url)
.field("headers", &names)
.field("body_bytes", &self.body.as_ref().map(Vec::len))
.field("accept", &self.accept)
.finish()
}
}
#[async_trait]
pub trait Body: Send {
async fn chunk(&mut self) -> Result<Option<Vec<u8>>, HttpError>;
}
#[derive(Debug, Default)]
pub struct ChunkBody(VecDeque<Vec<u8>>);
impl ChunkBody {
pub fn new(chunks: Vec<Vec<u8>>) -> Self {
Self(chunks.into())
}
}
#[async_trait]
impl Body for ChunkBody {
async fn chunk(&mut self) -> Result<Option<Vec<u8>>, HttpError> {
Ok(self.0.pop_front())
}
}
pub struct HttpResponse {
pub status: u16,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: Box<dyn Body>,
pub truncated: bool,
}
impl HttpResponse {
pub fn header(&self, name: &str) -> Option<&str> {
find_header(&self.headers, name)
}
pub fn content_type(&self) -> String {
self.header("content-type")
.map(media_type)
.unwrap_or_default()
}
}
#[async_trait]
pub trait Transport: Send + Sync {
async fn send(&self, req: HttpRequest) -> Result<HttpResponse, HttpError>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpErrorKind {
Invalid,
Blocked,
Network,
Timeout,
Rejected,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{message}")]
pub struct HttpError {
pub kind: HttpErrorKind,
pub message: String,
}
impl HttpError {
pub fn new(kind: HttpErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
}
impl From<HttpError> for ProviderError {
fn from(e: HttpError) -> Self {
let kind = match e.kind {
HttpErrorKind::Timeout => ProviderErrorKind::Stalled,
HttpErrorKind::Invalid | HttpErrorKind::Blocked | HttpErrorKind::Rejected => {
ProviderErrorKind::BadRequest
}
HttpErrorKind::Network => ProviderErrorKind::Network,
};
ProviderError::new(kind, e.message)
}
}
pub async fn read_limited(body: &mut dyn Body, limit: usize) -> Result<(Vec<u8>, bool), HttpError> {
let mut out = Vec::new();
while let Some(chunk) = body.chunk().await? {
let room = limit - out.len();
if chunk.len() > room {
out.extend_from_slice(&chunk[..room]);
assert!(out.len() == limit);
return Ok((out, true));
}
out.extend_from_slice(&chunk);
}
Ok((out, false))
}
pub fn media_type(value: &str) -> String {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
}
fn find_header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
#[cfg(test)]
mod tests {
use super::*;
fn reply(headers: Vec<(String, String)>, chunks: Vec<&str>) -> HttpResponse {
let chunks = chunks.into_iter().map(|c| c.as_bytes().to_vec()).collect();
HttpResponse {
status: 200,
url: "https://x/".into(),
headers,
body: Box::new(ChunkBody::new(chunks)),
truncated: false,
}
}
#[test]
fn request_debug_hides_header_values() {
let req = HttpRequest::post(
"https://x/v1",
vec![("Authorization".into(), "Bearer k-123".into())],
b"{}".to_vec(),
);
let dbg = format!("{req:?}");
assert!(
dbg.contains("Authorization") && !dbg.contains("k-123"),
"{dbg}"
);
assert_eq!(req.header("authorization"), Some("Bearer k-123"));
assert_eq!(req.method.as_str(), "POST");
}
#[test]
fn content_type_is_lowercase_media_type() {
let r = reply(
vec![("Content-Type".into(), "Text/HTML; charset=utf-8".into())],
vec![],
);
assert_eq!(r.content_type(), "text/html");
assert_eq!(reply(vec![], vec![]).content_type(), "");
}
#[tokio::test]
async fn read_limited_flags_overflow() {
let mut r = reply(vec![], vec!["abc", "def"]);
assert_eq!(
read_limited(r.body.as_mut(), 10).await.unwrap(),
(b"abcdef".to_vec(), false)
);
let mut r = reply(vec![], vec!["abc", "def"]);
assert_eq!(
read_limited(r.body.as_mut(), 4).await.unwrap(),
(b"abcd".to_vec(), true)
);
let mut r = reply(vec![], vec!["abc"]);
assert_eq!(
read_limited(r.body.as_mut(), 3).await.unwrap(),
(b"abc".to_vec(), false)
);
}
#[test]
fn http_error_maps_to_provider_kinds() {
let cases = [
(HttpErrorKind::Timeout, ProviderErrorKind::Stalled),
(HttpErrorKind::Invalid, ProviderErrorKind::BadRequest),
(HttpErrorKind::Network, ProviderErrorKind::Network),
(HttpErrorKind::Blocked, ProviderErrorKind::BadRequest),
(HttpErrorKind::Rejected, ProviderErrorKind::BadRequest),
];
for (from, to) in cases {
let e: ProviderError = HttpError::new(from, "boom").into();
assert_eq!((e.kind, e.message.as_str()), (to, "boom"));
}
}
}