use core::fmt;
use bytes::Bytes;
use http::{Request, Response};
use http_body_util::{BodyExt as _, Full};
use wasip3::{
clocks::monotonic_clock,
http::{client, types::ErrorCode},
http_compat::{http_from_wasi_response, http_into_wasi_request},
};
use crate::{Sleep, Transport};
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p3"))))]
#[derive(Debug)]
#[non_exhaustive]
pub enum Wasip3Error {
Http(ErrorCode),
}
impl fmt::Display for Wasip3Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Http(error) => write!(formatter, "WASI HTTP error: {error}"),
}
}
}
impl core::error::Error for Wasip3Error {}
impl From<ErrorCode> for Wasip3Error {
fn from(error: ErrorCode) -> Self {
Self::Http(error)
}
}
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p3"))))]
#[derive(Clone, Copy, Debug, Default)]
pub struct Wasip3Transport;
impl Transport for Wasip3Transport {
type Error = Wasip3Error;
async fn send(&self, request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, Self::Error> {
send(request).await
}
fn is_retryable(error: &Self::Error) -> bool {
matches!(
error,
Wasip3Error::Http(
ErrorCode::DnsTimeout
| ErrorCode::ConnectionRefused
| ErrorCode::ConnectionTerminated
| ErrorCode::ConnectionTimeout
| ErrorCode::ConnectionReadTimeout
| ErrorCode::ConnectionWriteTimeout
| ErrorCode::ConnectionLimitReached
| ErrorCode::HttpResponseTimeout
)
)
}
}
#[cfg_attr(docsrs, doc(cfg(all(target_arch = "wasm32", target_env = "p3"))))]
#[derive(Clone, Copy, Debug, Default)]
pub struct Wasip3Sleep;
impl Sleep for Wasip3Sleep {
async fn sleep(&self, duration: core::time::Duration) {
let nanoseconds = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
monotonic_clock::wait_for(nanoseconds).await;
}
}
async fn send(request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, Wasip3Error> {
let (parts, body) = request.into_parts();
let request = Request::from_parts(parts, Full::new(Bytes::from(body)));
let response = client::send(http_into_wasi_request(request)?).await?;
let (parts, body) = http_from_wasi_response(response)?.into_parts();
let body = body.collect().await?.to_bytes().to_vec();
Ok(Response::from_parts(parts, body))
}