Skip to main content

redseat_api/
call.rs

1//! A call to a server or the cloud without its I/O: the [`Request`] to send and how to
2//! read its [`Response`]. The async clients run calls through a [`crate::Transport`]
3//! ([`crate::RedseatClient::run`], [`crate::CloudClient::run`]); a host that sends
4//! requests itself (a WebAssembly module that cannot run async code, a binding to
5//! another language) builds the same calls with the `calls` modules
6//! ([`crate::server::calls`], [`crate::library::calls`], [`crate::cloud::calls`]),
7//! sends [`Call::request`] and reads the answer with [`Call::parse`].
8//!
9//! Requests to a server carry no token: add it with [`Request::bearer`]. When
10//! [`Call::parse`] fails with [`crate::ErrorKind::Unauthorized`], the token was refused:
11//! get a new one ([`crate::cloud::calls::fetch_server_token`]), send the request again
12//! with it, and parse that answer with the same call.
13
14use serde::de::DeserializeOwned;
15
16use crate::error::{Error, Result};
17use crate::transport::{Request, Response};
18
19type Read<T> = dyn Fn(Result<Response>) -> Result<T> + Send + Sync;
20
21/// One request and how to read its answer into a `T`. Build it with a `calls` module,
22/// send [`Self::request`], then [`Self::parse`] the response.
23pub struct Call<T> {
24    /// The request to send. Its `path` is relative to the server (or the cloud).
25    pub request: Request,
26    read: Box<Read<T>>,
27}
28
29impl<T> std::fmt::Debug for Call<T> {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("Call")
32            .field("request", &self.request)
33            .finish_non_exhaustive()
34    }
35}
36
37impl<T> Call<T> {
38    pub(crate) fn new(
39        request: Request,
40        read: impl Fn(Result<Response>) -> Result<T> + Send + Sync + 'static,
41    ) -> Self {
42        Call {
43            request,
44            read: Box::new(read),
45        }
46    }
47
48    /// Reads the response the server gave, whatever its status: a status other than
49    /// 2xx is read as [`Error::from_status`] (or as what the call makes of it: an
50    /// expired cloud session is `None`). Can be called again, for the answer to the
51    /// same request sent once more.
52    pub fn parse(&self, response: Response) -> Result<T> {
53        let result = if (200..300).contains(&response.status) {
54            Ok(response)
55        } else {
56            Err(Error::from_status(
57                response.status,
58                Some(&self.request.path),
59                &response.body,
60            ))
61        };
62        self.read(result)
63    }
64
65    /// Reads what a [`crate::Transport`] gave for the request: a 2xx response, or the
66    /// error of any other status or of a failure to send it.
67    pub fn read(&self, result: Result<Response>) -> Result<T> {
68        (self.read)(result)
69    }
70
71    /// The request, and the reader of its answer.
72    pub(crate) fn into_parts(self) -> (Request, Box<Read<T>>) {
73        (self.request, self.read)
74    }
75
76    /// The same request, its answer then turned into a `U` by `then`.
77    pub(crate) fn map<U>(self, then: impl Fn(T) -> Result<U> + Send + Sync + 'static) -> Call<U>
78    where
79        T: 'static,
80    {
81        let read = self.read;
82        Call::new(self.request, move |result| read(result).and_then(&then))
83    }
84}
85
86impl<T: DeserializeOwned + 'static> Call<T> {
87    /// A call whose answer is read as JSON.
88    pub(crate) fn json(request: Request) -> Self {
89        let path = request.path.clone();
90        Call::new(request, move |result| {
91            serde_json::from_slice(&result?.body)
92                .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), Some(&path)))
93        })
94    }
95}
96
97impl Call<()> {
98    /// A call whose answer has no body to read.
99    pub(crate) fn empty(request: Request) -> Self {
100        Call::new(request, |result| result.map(|_| ()))
101    }
102}
103
104impl Call<Vec<u8>> {
105    /// A call whose answer is the body, as bytes.
106    pub(crate) fn bytes(request: Request) -> Self {
107        Call::new(request, |result| result.map(|response| response.body))
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::ErrorKind;
115
116    fn response(status: u16, body: &str) -> Response {
117        Response {
118            status,
119            headers: Vec::new(),
120            body: body.as_bytes().to_vec(),
121        }
122    }
123
124    #[test]
125    fn reads_a_status_like_the_transports() {
126        let call: Call<Vec<u32>> = Call::json(Request::get("/x"));
127        assert_eq!(call.parse(response(200, "[1,2]")).unwrap(), vec![1, 2]);
128
129        let refused = call.parse(response(401, r#"{"message":"expired"}"#));
130        let refused = refused.unwrap_err();
131        assert_eq!(refused.kind(), ErrorKind::Unauthorized);
132        assert_eq!(refused.to_string(), "expired");
133        assert_eq!(refused.path(), Some("/x"));
134
135        let malformed = call.parse(response(200, "nope")).unwrap_err();
136        assert_eq!(malformed.kind(), ErrorKind::MalformedResponse);
137        assert_eq!(malformed.path(), Some("/x"));
138        assert_eq!(
139            call.read(Err(Error::transport("offline")))
140                .unwrap_err()
141                .kind(),
142            ErrorKind::Transport
143        );
144    }
145
146    #[test]
147    fn maps_an_answer() {
148        let call = Call::json(Request::get("/count")).map(|n: u64| Ok(n * 2));
149        assert_eq!(call.parse(response(200, "21")).unwrap(), 42);
150        assert!(
151            Call::empty(Request::get("/"))
152                .parse(response(204, ""))
153                .is_ok()
154        );
155        assert_eq!(
156            Call::bytes(Request::get("/"))
157                .parse(response(200, "ab"))
158                .unwrap(),
159            b"ab".to_vec()
160        );
161    }
162
163    #[test]
164    fn never_prints_a_token() {
165        let call = Call::empty(Request::get("/x").bearer("secret"));
166        let printed = format!("{call:?}");
167        assert!(printed.contains("/x"));
168        assert!(!printed.contains("secret"));
169    }
170}