pub use bytes::Bytes;
pub use http::{
HeaderMap, HeaderValue, Method, Request, Response, StatusCode, Uri, request::Builder,
};
mod erased;
pub mod framing;
pub mod middleware;
pub mod multipart;
use crate::wasm_compat::*;
pub use erased::DynHttpClient;
pub use middleware::{Exchange, HttpMiddleware};
pub use multipart::MultipartForm;
#[cfg(not(target_family = "wasm"))]
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
#[cfg(target_family = "wasm")]
pub type BoxError = Box<dyn std::error::Error + 'static>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("Http error: {0}")]
Protocol(#[from] http::Error),
#[error("Invalid status code {status} with message: {body}")]
InvalidStatusCodeWithDetails {
status: StatusCode,
body: String,
headers: http::HeaderMap,
},
#[error("Stream ended")]
StreamEnded,
#[error("Invalid content type was returned: {0:?}")]
InvalidContentType(HeaderValue),
#[error("Http client error: {0}")]
Transient(#[source] BoxError),
#[error("Http client error: {0}")]
Permanent(#[source] BoxError),
}
impl Error {
pub fn non_success_status(&self) -> Option<StatusCode> {
match self {
Self::InvalidStatusCodeWithDetails { status, .. } => Some(*status),
_ => None,
}
}
pub fn non_success_body(&self) -> Option<&str> {
match self {
Self::InvalidStatusCodeWithDetails { body, .. } => Some(body.as_str()),
_ => None,
}
}
pub fn non_success_with_details(status: StatusCode, headers: HeaderMap, body: String) -> Self {
Self::InvalidStatusCodeWithDetails {
status,
body,
headers,
}
}
pub fn non_success_headers(&self) -> Option<&HeaderMap> {
match self {
Self::InvalidStatusCodeWithDetails { headers, .. } => Some(headers),
_ => None,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl Error {
pub fn is_transient(&self) -> bool {
match self {
Self::StreamEnded | Self::Transient(_) => true,
Self::InvalidStatusCodeWithDetails { status, .. } => {
retryable_status(Some(status.as_u16()))
}
_ => false,
}
}
pub fn transient(error: impl Into<BoxError>) -> Self {
Self::Transient(error.into())
}
pub fn permanent(error: impl Into<BoxError>) -> Self {
Self::Permanent(error.into())
}
}
pub const fn retryable_status(status: Option<u16>) -> bool {
match status {
None => false,
Some(408 | 425 | 429) => true,
Some(s) => s >= 500 && s <= 599,
}
}
pub type LazyBody = WasmBoxedFuture<'static, Result<Bytes>>;
pub type BoxedStream = WasmBoxedStream<'static, Result<Bytes>>;
pub type StreamingResponse = Response<BoxedStream>;
#[derive(Debug, Clone, Copy)]
pub struct NoBody;
impl From<NoBody> for Bytes {
fn from(_: NoBody) -> Self {
Bytes::new()
}
}
pub async fn text(response: Response<LazyBody>) -> Result<String> {
let text = response.into_body().await?;
Ok(String::from(String::from_utf8_lossy(&text)))
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not an HTTP client Rig can send through",
label = "not an `HttpClientExt`",
note = "use `rig_reqwest::ReqwestClient` (wrap a configured `reqwest::Client` with `ReqwestClient::from(client)`), erase a client with `DynHttpClient::new(client)`, or implement `HttpClientExt`; a provider configuration takes it with `.connect(client)`"
)]
pub trait HttpClientExt: WasmCompatSend + WasmCompatSync {
fn send(
&self,
req: Request<Bytes>,
) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static;
fn send_multipart(
&self,
req: Request<MultipartForm>,
) -> impl Future<Output = Result<Response<LazyBody>>> + WasmCompatSend + 'static;
fn send_streaming(
&self,
req: Request<Bytes>,
) -> impl Future<Output = Result<StreamingResponse>> + WasmCompatSend;
}
#[cfg(test)]
mod non_success_header_tests;