1use std::pin::Pin;
6use std::time::Duration;
7
8use futures_util::Stream;
9use serde::de::DeserializeOwned;
10
11use crate::error::{Error, Result};
12
13#[cfg(not(target_arch = "wasm32"))]
16pub trait MaybeSend: Send + Sync {}
17#[cfg(not(target_arch = "wasm32"))]
18impl<T: Send + Sync + ?Sized> MaybeSend for T {}
19
20#[cfg(target_arch = "wasm32")]
23pub trait MaybeSend {}
24#[cfg(target_arch = "wasm32")]
25impl<T: ?Sized> MaybeSend for T {}
26
27#[cfg(not(target_arch = "wasm32"))]
29pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
30#[cfg(target_arch = "wasm32")]
32pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum Method {
37 Get,
38 Head,
39 Post,
40 Put,
41 Patch,
42 Delete,
43}
44
45impl Method {
46 pub fn as_str(self) -> &'static str {
48 match self {
49 Method::Get => "GET",
50 Method::Head => "HEAD",
51 Method::Post => "POST",
52 Method::Put => "PUT",
53 Method::Patch => "PATCH",
54 Method::Delete => "DELETE",
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq)]
61pub enum Body {
62 Json(serde_json::Value),
63 Form(Vec<(String, String)>),
65 Bytes {
66 content_type: String,
67 data: Vec<u8>,
68 },
69}
70
71#[derive(Clone, PartialEq)]
74pub struct Request {
75 pub method: Method,
76 pub path: String,
77 pub headers: Vec<(String, String)>,
78 pub query: Vec<(String, String)>,
79 pub body: Option<Body>,
80 pub timeout: Option<Duration>,
82}
83
84impl std::fmt::Debug for Request {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 let headers: Vec<(&str, &str)> = self
88 .headers
89 .iter()
90 .map(|(name, value)| {
91 if name.eq_ignore_ascii_case("authorization") {
92 (name.as_str(), "<hidden>")
93 } else {
94 (name.as_str(), value.as_str())
95 }
96 })
97 .collect();
98 f.debug_struct("Request")
99 .field("method", &self.method)
100 .field("path", &self.path)
101 .field("headers", &headers)
102 .field("query", &self.query)
103 .field("body", &self.body)
104 .field("timeout", &self.timeout)
105 .finish()
106 }
107}
108
109impl Request {
110 pub fn new(method: Method, path: impl Into<String>) -> Self {
111 Request {
112 method,
113 path: path.into(),
114 headers: Vec::new(),
115 query: Vec::new(),
116 body: None,
117 timeout: None,
118 }
119 }
120
121 pub fn get(path: impl Into<String>) -> Self {
122 Self::new(Method::Get, path)
123 }
124
125 pub fn post(path: impl Into<String>) -> Self {
126 Self::new(Method::Post, path)
127 }
128
129 pub fn patch(path: impl Into<String>) -> Self {
130 Self::new(Method::Patch, path)
131 }
132
133 pub fn delete(path: impl Into<String>) -> Self {
134 Self::new(Method::Delete, path)
135 }
136
137 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
138 self.headers.push((name.into(), value.into()));
139 self
140 }
141
142 pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
143 self.query.push((name.into(), value.into()));
144 self
145 }
146
147 pub fn json(mut self, body: serde_json::Value) -> Self {
148 self.body = Some(Body::Json(body));
149 self
150 }
151
152 pub fn form(mut self, fields: Vec<(String, String)>) -> Self {
153 self.body = Some(Body::Form(fields));
154 self
155 }
156
157 pub fn bearer(mut self, token: &str) -> Self {
159 self.headers
160 .retain(|(name, _)| !name.eq_ignore_ascii_case("authorization"));
161 self.headers
162 .push(("Authorization".to_owned(), format!("Bearer {token}")));
163 self
164 }
165}
166
167#[derive(Debug, Clone, PartialEq, Default)]
169pub struct Response {
170 pub status: u16,
171 pub headers: Vec<(String, String)>,
172 pub body: Vec<u8>,
173}
174
175impl Response {
176 pub fn header(&self, name: &str) -> Option<&str> {
178 self.headers
179 .iter()
180 .find(|(n, _)| n.eq_ignore_ascii_case(name))
181 .map(|(_, v)| v.as_str())
182 }
183
184 pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
186 serde_json::from_slice(&self.body)
187 .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), None))
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Default)]
193pub struct EventRequest {
194 pub path: String,
195 pub headers: Vec<(String, String)>,
196 pub query: Vec<(String, String)>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Default)]
201pub struct RawEvent {
202 pub event: String,
203 pub data: String,
204 pub id: Option<String>,
205 pub retry: Option<u64>,
206}
207
208pub type RawEventStream = BoxStream<Result<RawEvent>>;
210
211#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
216#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
217pub trait Transport: MaybeSend {
218 async fn request(&self, request: Request) -> Result<Response>;
219
220 async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
223 Err(Error::Transport {
224 message: "this transport does not support server events".to_owned(),
225 status: None,
226 path: Some(request.path),
227 })
228 }
229
230 fn close(&self) {}
232
233 fn http_base_url(&self) -> Option<String> {
238 None
239 }
240}