use std::pin::Pin;
use std::time::Duration;
use futures_util::Stream;
use serde::de::DeserializeOwned;
use crate::error::{Error, Result};
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send + Sync {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + Sync + ?Sized> MaybeSend for T {}
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSend for T {}
#[cfg(not(target_arch = "wasm32"))]
pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
#[cfg(target_arch = "wasm32")]
pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
Get,
Head,
Post,
Put,
Patch,
Delete,
}
impl Method {
pub fn as_str(self) -> &'static str {
match self {
Method::Get => "GET",
Method::Head => "HEAD",
Method::Post => "POST",
Method::Put => "PUT",
Method::Patch => "PATCH",
Method::Delete => "DELETE",
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Body {
Json(serde_json::Value),
Form(Vec<(String, String)>),
Bytes {
content_type: String,
data: Vec<u8>,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
pub method: Method,
pub path: String,
pub headers: Vec<(String, String)>,
pub query: Vec<(String, String)>,
pub body: Option<Body>,
pub timeout: Option<Duration>,
}
impl Request {
pub fn new(method: Method, path: impl Into<String>) -> Self {
Request {
method,
path: path.into(),
headers: Vec::new(),
query: Vec::new(),
body: None,
timeout: None,
}
}
pub fn get(path: impl Into<String>) -> Self {
Self::new(Method::Get, path)
}
pub fn post(path: impl Into<String>) -> Self {
Self::new(Method::Post, path)
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.query.push((name.into(), value.into()));
self
}
pub fn json(mut self, body: serde_json::Value) -> Self {
self.body = Some(Body::Json(body));
self
}
pub fn form(mut self, fields: Vec<(String, String)>) -> Self {
self.body = Some(Body::Form(fields));
self
}
pub fn bearer(mut self, token: &str) -> Self {
self.headers
.retain(|(name, _)| !name.eq_ignore_ascii_case("authorization"));
self.headers
.push(("Authorization".to_owned(), format!("Bearer {token}")));
self
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Response {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl Response {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
serde_json::from_slice(&self.body)
.map_err(|e| Error::malformed(format!("unexpected answer: {e}"), None))
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct EventRequest {
pub path: String,
pub headers: Vec<(String, String)>,
pub query: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RawEvent {
pub event: String,
pub data: String,
pub id: Option<String>,
pub retry: Option<u64>,
}
pub type RawEventStream = BoxStream<Result<RawEvent>>;
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait Transport: MaybeSend {
async fn request(&self, request: Request) -> Result<Response>;
async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
Err(Error::Transport {
message: "this transport does not support server events".to_owned(),
status: None,
path: Some(request.path),
})
}
fn close(&self) {}
fn http_base_url(&self) -> Option<String> {
None
}
}