1use 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
21pub struct Call<T> {
24 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 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 pub fn read(&self, result: Result<Response>) -> Result<T> {
68 (self.read)(result)
69 }
70
71 pub(crate) fn into_parts(self) -> (Request, Box<Read<T>>) {
73 (self.request, self.read)
74 }
75
76 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 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 pub(crate) fn empty(request: Request) -> Self {
100 Call::new(request, |result| result.map(|_| ()))
101 }
102}
103
104impl Call<Vec<u8>> {
105 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}