Skip to main content

redseat_api/
transport.rs

1//! The `Transport` trait: how the client reaches a server. Port of `@redseat/api`
2//! `transport.ts`. The HTTP implementation is [`crate::http::HttpTransport`]; WebRTC can
3//! come later behind its own feature.
4
5use std::pin::Pin;
6use std::time::Duration;
7
8use futures_util::Stream;
9use serde::de::DeserializeOwned;
10
11use crate::error::{Error, Result};
12
13/// `Send + Sync` on native targets, nothing on wasm, where futures and JS handles are
14/// single-threaded.
15#[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/// `Send + Sync` on native targets, nothing on wasm, where futures and JS handles are
21/// single-threaded.
22#[cfg(target_arch = "wasm32")]
23pub trait MaybeSend {}
24#[cfg(target_arch = "wasm32")]
25impl<T: ?Sized> MaybeSend for T {}
26
27/// A boxed stream, `Send` on native targets.
28#[cfg(not(target_arch = "wasm32"))]
29pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
30/// A boxed stream, `Send` on native targets.
31#[cfg(target_arch = "wasm32")]
32pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;
33
34/// HTTP-like method.
35#[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    /// The method name, upper case.
47    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/// Body of a request.
60#[derive(Debug, Clone, PartialEq)]
61pub enum Body {
62    Json(serde_json::Value),
63    /// `application/x-www-form-urlencoded`.
64    Form(Vec<(String, String)>),
65    Bytes {
66        content_type: String,
67        data: Vec<u8>,
68    },
69}
70
71/// A request. `path` is relative to the transport's base URL (`/libraries`), or absolute.
72#[derive(Debug, Clone, PartialEq)]
73pub struct Request {
74    pub method: Method,
75    pub path: String,
76    pub headers: Vec<(String, String)>,
77    pub query: Vec<(String, String)>,
78    pub body: Option<Body>,
79    /// Overrides the transport's default timeout.
80    pub timeout: Option<Duration>,
81}
82
83impl Request {
84    pub fn new(method: Method, path: impl Into<String>) -> Self {
85        Request {
86            method,
87            path: path.into(),
88            headers: Vec::new(),
89            query: Vec::new(),
90            body: None,
91            timeout: None,
92        }
93    }
94
95    pub fn get(path: impl Into<String>) -> Self {
96        Self::new(Method::Get, path)
97    }
98
99    pub fn post(path: impl Into<String>) -> Self {
100        Self::new(Method::Post, path)
101    }
102
103    pub fn patch(path: impl Into<String>) -> Self {
104        Self::new(Method::Patch, path)
105    }
106
107    pub fn delete(path: impl Into<String>) -> Self {
108        Self::new(Method::Delete, path)
109    }
110
111    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
112        self.headers.push((name.into(), value.into()));
113        self
114    }
115
116    pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
117        self.query.push((name.into(), value.into()));
118        self
119    }
120
121    pub fn json(mut self, body: serde_json::Value) -> Self {
122        self.body = Some(Body::Json(body));
123        self
124    }
125
126    pub fn form(mut self, fields: Vec<(String, String)>) -> Self {
127        self.body = Some(Body::Form(fields));
128        self
129    }
130
131    /// Sets `Authorization: Bearer <token>`, replacing any previous one.
132    pub fn bearer(mut self, token: &str) -> Self {
133        self.headers
134            .retain(|(name, _)| !name.eq_ignore_ascii_case("authorization"));
135        self.headers
136            .push(("Authorization".to_owned(), format!("Bearer {token}")));
137        self
138    }
139}
140
141/// A successful response (status 2xx). Failures come back as [`Error`].
142#[derive(Debug, Clone, PartialEq, Default)]
143pub struct Response {
144    pub status: u16,
145    pub headers: Vec<(String, String)>,
146    pub body: Vec<u8>,
147}
148
149impl Response {
150    /// The first header with this name, ignoring case.
151    pub fn header(&self, name: &str) -> Option<&str> {
152        self.headers
153            .iter()
154            .find(|(n, _)| n.eq_ignore_ascii_case(name))
155            .map(|(_, v)| v.as_str())
156    }
157
158    /// The body read as JSON.
159    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
160        serde_json::from_slice(&self.body)
161            .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), None))
162    }
163}
164
165/// A request for a server-pushed event stream.
166#[derive(Debug, Clone, PartialEq, Default)]
167pub struct EventRequest {
168    pub path: String,
169    pub headers: Vec<(String, String)>,
170    pub query: Vec<(String, String)>,
171}
172
173/// A server event as the transport received it: name and raw `data` (JSON text).
174#[derive(Debug, Clone, PartialEq, Eq, Default)]
175pub struct RawEvent {
176    pub event: String,
177    pub data: String,
178    pub id: Option<String>,
179    pub retry: Option<u64>,
180}
181
182/// Stream of raw events. It ends when the server closes it; drop it to disconnect.
183pub type RawEventStream = BoxStream<Result<RawEvent>>;
184
185/// How the client reaches a server (or the cloud). Port of `RedseatTransport`.
186///
187/// `request` returns the response of a 2xx status and maps any other status to an
188/// [`Error`] with [`Error::from_status`].
189#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
190#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
191pub trait Transport: MaybeSend {
192    async fn request(&self, request: Request) -> Result<Response>;
193
194    /// Opens a server-pushed event stream. The protocol (SSE, DataChannel...) is a
195    /// transport detail.
196    async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
197        Err(Error::Transport {
198            message: "this transport does not support server events".to_owned(),
199            status: None,
200            path: Some(request.path),
201        })
202    }
203
204    /// Stops the transport. Later calls fail.
205    fn close(&self) {}
206
207    /// The `http(s)://host:port` base of the server, when it is reachable over plain
208    /// HTTP. Lets code that fetches files itself (a video player) build URLs for them,
209    /// see [`crate::RedseatClient::authorized_url`]. `None` (the default) for
210    /// transports that are not HTTP.
211    fn http_base_url(&self) -> Option<String> {
212        None
213    }
214}