use std::borrow::Cow;
use std::ops::Deref;
use std::time::Duration;
use crate::error::ScenarioError;
use reqwest::{IntoUrl, Method, Response, StatusCode, Url};
use serde::ser::Error as _;
pub use reqwest;
pub use reqwest::multipart;
#[derive(Debug, Clone, Copy)]
pub struct CaptureOptions {
pub max_request_body: usize,
pub max_response_body: usize,
}
impl Default for CaptureOptions {
fn default() -> Self {
Self {
max_request_body: 512,
max_response_body: 512,
}
}
}
impl CaptureOptions {
pub const fn disabled() -> Self {
Self {
max_request_body: 0,
max_response_body: 0,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
#[error("HTTP request failed: {0}")]
Reqwest(#[from] reqwest::Error),
#[error("JSON serialization failed: {0}")]
Serde(#[from] serde_json::Error),
#[error("Invalid URL: {0}")]
Url(#[from] url::ParseError),
#[error("HTTP {method} {url} -> {status}")]
Status {
status: StatusCode,
method: Method,
url: String,
request_body: Option<String>,
response_body: Option<Result<String, String>>,
},
}
impl HttpError {
pub fn status(status: StatusCode, method: Method, url: &Url) -> Self {
Self::Status {
status,
method,
url: url.to_string(),
request_body: None,
response_body: None,
}
}
async fn from_response(
resp: Response,
method: Method,
url: Url,
request_body: Option<String>,
capture: &CaptureOptions,
) -> Self {
let status = resp.status();
let response_body = if capture.max_response_body == 0 {
None
} else {
match resp.text().await {
Ok(text) => Some(Ok(truncate_log(&text, capture.max_response_body))),
Err(err) => Some(Err(err.to_string())),
}
};
Self::Status {
status,
method,
url: url.to_string(),
request_body,
response_body,
}
}
}
impl ScenarioError for HttpError {
fn kind(&self) -> Cow<'static, str> {
match self {
Self::Reqwest(_) => "reqwest".into(),
Self::Serde(_) => "serde".into(),
Self::Url(_) => "url_parse".into(),
Self::Status { status, .. } => format!("http_status_{}", status.as_u16()).into(),
}
}
}
impl ScenarioError for reqwest::Error {
fn kind(&self) -> Cow<'static, str> {
if let Some(status) = self.status() {
return format!("http_status_{}", status.as_u16()).into();
}
if self.is_timeout() {
return "timeout".into();
}
if self.is_connect() {
return "connect".into();
}
if self.is_body() || self.is_decode() {
return "decode".into();
}
if self.is_redirect() {
return "redirect".into();
}
if self.is_request() || self.is_builder() {
return "request".into();
}
"reqwest".into()
}
}
fn truncate_log(s: &str, max: usize) -> String {
if s.chars().count() <= max {
s.to_string()
} else {
let head: String = s.chars().take(max).collect();
format!("{head}...(total {} chars)", s.chars().count())
}
}
pub fn resolve(base: &Url, path: &str) -> Result<Url, HttpError> {
Ok(base.join(path.trim_start_matches('/'))?)
}
pub async fn check_status(
resp: Response,
method: Method,
capture: &CaptureOptions,
) -> Result<Response, HttpError> {
if resp.status() == StatusCode::OK {
return Ok(resp);
}
let url = resp.url().clone();
Err(HttpError::from_response(resp, method, url, None, capture).await)
}
pub struct Client {
pub base_url: reqwest::Url,
inner: reqwest::Client,
capture: CaptureOptions,
}
fn normalize_base(mut base_url: Url) -> Url {
if !base_url.path().ends_with('/') {
let path = format!("{}/", base_url.path());
base_url.set_path(&path);
}
base_url
}
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
impl Client {
pub fn new(base_url: impl IntoUrl) -> Result<Self, HttpError> {
let inner = reqwest::Client::builder()
.timeout(DEFAULT_TIMEOUT)
.build()?;
Self::from_reqwest(inner, base_url)
}
pub fn from_reqwest(inner: reqwest::Client, base_url: impl IntoUrl) -> Result<Self, HttpError> {
Ok(Self {
base_url: normalize_base(base_url.into_url()?),
inner,
capture: CaptureOptions::default(),
})
}
pub fn with_capture(mut self, capture: CaptureOptions) -> Self {
self.capture = capture;
self
}
pub fn inner(&self) -> &reqwest::Client {
&self.inner
}
pub fn resolve(&self, path: &str) -> Result<Url, HttpError> {
resolve(&self.base_url, path)
}
pub fn request(&self, method: reqwest::Method, url: &str) -> RequestBuilder<'_> {
RequestBuilder::new(self, method, url)
}
fn capture_body(&self, bytes: &[u8]) -> Option<String> {
if self.capture.max_request_body == 0 {
None
} else {
Some(truncate_log(
&String::from_utf8_lossy(bytes),
self.capture.max_request_body,
))
}
}
}
impl Deref for Client {
type Target = reqwest::Client;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct RequestBuilder<'a> {
client: &'a Client,
method: reqwest::Method,
url: String,
body: Option<reqwest::Body>,
multipart: Option<reqwest::multipart::Form>,
headers: reqwest::header::HeaderMap,
query: Vec<(String, String)>,
body_snapshot: Option<String>,
}
impl<'a> RequestBuilder<'a> {
pub fn new(client: &'a Client, method: reqwest::Method, url: &str) -> Self {
Self {
client,
method,
url: url.to_string(),
body: None,
multipart: None,
headers: reqwest::header::HeaderMap::new(),
query: Vec::new(),
body_snapshot: None,
}
}
pub fn header(mut self, key: &str, value: &str) -> Self {
if let Ok(header_name) = reqwest::header::HeaderName::from_bytes(key.as_bytes())
&& let Ok(header_value) = reqwest::header::HeaderValue::from_str(value)
{
self.headers.insert(header_name, header_value);
}
self
}
pub fn query(mut self, key: &str, value: &str) -> Self {
self.query.push((key.to_string(), value.to_string()));
self
}
pub fn query_vec(mut self, params: &[(String, String)]) -> Self {
self.query.extend(params.iter().cloned());
self
}
pub fn json<B: serde::Serialize>(mut self, body: &B) -> Result<Self, serde_json::Error> {
let bytes = serde_json::to_vec(body)?;
self.multipart = None;
self.body_snapshot = self.client.capture_body(&bytes);
self.body = Some(reqwest::Body::from(bytes));
self.headers.insert(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
Ok(self)
}
pub fn json_unwrap<B: serde::Serialize>(self, body: &B) -> Self {
self.json(body).unwrap()
}
pub fn body(mut self, body: impl Into<reqwest::Body>) -> Self {
self.multipart = None;
self.body = Some(body.into());
self
}
pub fn form<B: serde::Serialize>(mut self, form: &B) -> Result<Self, serde_json::Error> {
let encoded = serde_urlencoded::to_string(form)
.map_err(|e| serde_json::Error::custom(e.to_string()))?;
self.multipart = None;
self.body_snapshot = self.client.capture_body(encoded.as_bytes());
self.body = Some(reqwest::Body::from(encoded.into_bytes()));
self.headers.insert(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/x-www-form-urlencoded"),
);
Ok(self)
}
pub fn multipart(mut self, form: reqwest::multipart::Form) -> Self {
self.body = None;
self.body_snapshot = None;
self.multipart = Some(form);
self
}
async fn send_impl(
client: &Client,
method: reqwest::Method,
full_url: Url,
headers: reqwest::header::HeaderMap,
query: Vec<(String, String)>,
body: Option<reqwest::Body>,
multipart: Option<reqwest::multipart::Form>,
) -> Result<Response, HttpError> {
let mut req_builder = client.inner.request(method, full_url);
for (key, value) in headers {
if let Some(key) = key {
req_builder = req_builder.header(key, value);
}
}
if !query.is_empty() {
req_builder = req_builder.query(&query);
}
if let Some(form) = multipart {
req_builder = req_builder.multipart(form);
} else if let Some(body) = body {
req_builder = req_builder.body(body);
}
req_builder.send().await.map_err(HttpError::from)
}
pub async fn send(self) -> Result<Response, HttpError> {
let RequestBuilder {
client,
method,
url: path,
body,
multipart,
headers,
query,
body_snapshot: _,
} = self;
let full_url = client.resolve(&path)?;
Self::send_impl(client, method, full_url, headers, query, body, multipart).await
}
pub async fn send_checked(self) -> Result<Response, HttpError> {
let RequestBuilder {
client,
method,
url: path,
body,
multipart,
headers,
query,
body_snapshot,
} = self;
let full_url = client.resolve(&path)?;
let resp = Self::send_impl(
client,
method.clone(),
full_url.clone(),
headers,
query,
body,
multipart,
)
.await?;
if resp.status() != StatusCode::OK {
return Err(HttpError::from_response(
resp,
method,
full_url,
body_snapshot,
&client.capture,
)
.await);
}
Ok(resp)
}
}
#[cfg(test)]
mod tests {
use super::{Client, resolve};
fn base_url(base: &str) -> reqwest::Url {
Client::new(base).unwrap().base_url
}
fn resolve_url(base: &str, path: &str) -> String {
resolve(&base_url(base), path).unwrap().to_string()
}
#[test]
fn keep_base_path_prefix() {
assert_eq!(
resolve_url("https://memory-seek.driftcloud.cn/api", "/auth/login"),
"https://memory-seek.driftcloud.cn/api/auth/login"
);
}
#[test]
fn no_prefix_unchanged() {
assert_eq!(
resolve_url("http://127.0.0.1:7985", "/auth/login"),
"http://127.0.0.1:7985/auth/login"
);
}
#[test]
fn query_preserved() {
assert_eq!(
resolve_url(
"http://localhost:8025",
"/api/v2/messages?limit=100&order=desc"
),
"http://localhost:8025/api/v2/messages?limit=100&order=desc"
);
}
#[test]
fn absolute_url_passthrough() {
assert_eq!(
resolve_url("http://127.0.0.1:7985", "https://other.example/x"),
"https://other.example/x"
);
}
}