1use alloc::string::{String, ToString};
5use alloc::sync::Arc;
6
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9
10use crate::connect::proto::ConnectError;
11use crate::connect::tls::{TlsClient, TlsPolicy};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct Status(pub u16);
21
22impl Status {
23 #[must_use]
25 pub const fn is_success(self) -> bool {
26 self.0 >= 200 && self.0 < 300
27 }
28
29 #[must_use]
31 pub const fn is_unauthorized(self) -> bool {
32 self.0 == 401
33 }
34
35 #[must_use]
37 pub const fn is_forbidden(self) -> bool {
38 self.0 == 403
39 }
40
41 #[must_use]
43 pub const fn is_busy(self) -> bool {
44 self.0 == 503
45 }
46}
47
48impl core::fmt::Display for Status {
49 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
50 write!(f, "{}", self.0)
51 }
52}
53
54#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum Error {
58 #[error(transparent)]
60 Protocol(#[from] ConnectError),
61 #[error(transparent)]
63 Tls(#[from] crate::connect::tls::Error),
64 #[error("{operation} failed: {source}")]
66 Transport {
67 operation: &'static str,
69 source: Box<dyn core::error::Error + Send + Sync>,
71 },
72 #[error("{operation} answered {status}{}", match .detail { Some(d) => alloc::format!(": {d}"), None => String::new() })]
74 Http {
75 operation: &'static str,
77 status: Status,
79 detail: Option<String>,
81 },
82 #[error("{operation} answered with a body that is not what the schema defines: {source}")]
84 Body {
85 operation: &'static str,
87 source: serde_json::Error,
89 },
90 #[error("{0} is not a usable URL")]
92 Url(String),
93 #[error("the server's certificate changed during the pairing attempt")]
95 IdentityChanged,
96}
97
98impl Error {
99 #[must_use]
105 pub fn is_transient(&self) -> bool {
106 match self {
107 Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
109 Error::Http { status, .. } => status.is_busy(),
112 _ => false,
113 }
114 }
115}
116
117#[derive(Debug, Clone)]
119pub(crate) struct Http {
120 client: reqwest::Client,
121 base: url::Url,
122 tls: TlsClient,
123}
124
125impl Http {
126 pub(crate) fn new(
128 base: &str,
129 policy: &TlsPolicy,
130 timeout: core::time::Duration,
131 ) -> Result<Self, Error> {
132 let tls = TlsClient::new(policy)?;
133 let base = normalize(base)?;
134 let client = reqwest::Client::builder()
135 .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
136 .timeout(timeout)
137 .https_only(true)
140 .redirect(reqwest::redirect::Policy::none())
141 .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
142 .build()
143 .map_err(|e| Error::Transport {
144 operation: "building the HTTPS client",
145 source: Box::new(e),
146 })?;
147 Ok(Self { client, base, tls })
148 }
149
150 pub(crate) fn tls(&self) -> &TlsClient {
151 &self.tls
152 }
153
154 pub(crate) fn base(&self) -> &url::Url {
155 &self.base
156 }
157
158 pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
160 &self,
161 operation: &'static str,
162 path: &str,
163 bearer: Option<&str>,
164 body: &B,
165 ) -> Result<R, Error> {
166 let text = self.post_raw(operation, path, bearer, Some(body)).await?;
167 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
168 }
169
170 pub(crate) async fn post_empty<B: Serialize>(
172 &self,
173 operation: &'static str,
174 path: &str,
175 bearer: Option<&str>,
176 body: Option<&B>,
177 ) -> Result<(), Error> {
178 self.post_raw(operation, path, bearer, body).await.map(drop)
179 }
180
181 pub(crate) async fn get<R: DeserializeOwned>(
183 &self,
184 operation: &'static str,
185 path: &str,
186 ) -> Result<R, Error> {
187 let url = self.join(path)?;
188 let response = self
189 .client
190 .get(url)
191 .send()
192 .await
193 .map_err(|e| Error::Transport {
194 operation,
195 source: Box::new(e),
196 })?;
197 let text = self.read(operation, response).await?;
198 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
199 }
200
201 async fn post_raw<B: Serialize>(
202 &self,
203 operation: &'static str,
204 path: &str,
205 bearer: Option<&str>,
206 body: Option<&B>,
207 ) -> Result<String, Error> {
208 let url = self.join(path)?;
209 let mut request = self.client.post(url);
210 if let Some(token) = bearer {
211 request = request.bearer_auth(token);
212 }
213 if let Some(body) = body {
214 request = request.json(body);
215 }
216 let response = request.send().await.map_err(|e| Error::Transport {
217 operation,
218 source: Box::new(e),
219 })?;
220 self.read(operation, response).await
221 }
222
223 async fn read(
224 &self,
225 operation: &'static str,
226 response: reqwest::Response,
227 ) -> Result<String, Error> {
228 let status = Status(response.status().as_u16());
229 let text = response.text().await.unwrap_or_default();
230 if status.is_success() {
231 return Ok(text);
232 }
233 Err(Error::Http {
234 operation,
235 status,
236 detail: (!text.is_empty()).then_some(text),
237 })
238 }
239
240 fn join(&self, path: &str) -> Result<url::Url, Error> {
241 self.base
242 .join(path.trim_start_matches('/'))
243 .map_err(|_| Error::Url(alloc::format!("{}{path}", self.base)))
244 }
245}
246
247fn normalize(base: &str) -> Result<url::Url, Error> {
253 let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
254 if url.scheme() != "https" {
255 return Err(Error::Url(alloc::format!(
256 "{base} is not HTTPS, and S2 Connect is HTTPS only"
257 )));
258 }
259 if !url.path().ends_with('/') {
260 let path = alloc::format!("{}/", url.path());
261 url.set_path(&path);
262 }
263 Ok(url)
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 #[test]
271 fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
272 let url = normalize("https://evse.local/v1").unwrap();
275 assert_eq!(url.as_str(), "https://evse.local/v1/");
276 assert_eq!(
277 url.join("requestPairing").unwrap().as_str(),
278 "https://evse.local/v1/requestPairing"
279 );
280 assert_eq!(
282 normalize("https://evse.local/v1/").unwrap().as_str(),
283 "https://evse.local/v1/"
284 );
285 }
286
287 #[test]
288 fn plain_http_is_refused_rather_than_upgraded() {
289 assert!(matches!(
291 normalize("http://evse.local/v1/"),
292 Err(Error::Url(_))
293 ));
294 assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
295 assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
296 }
297
298 #[test]
299 fn the_statuses_the_specification_distinguishes_are_distinguished() {
300 assert!(Status(200).is_success());
301 assert!(Status(204).is_success());
302 assert!(!Status(400).is_success());
303 assert!(Status(401).is_unauthorized());
306 assert!(Status(403).is_forbidden());
308 assert!(Status(503).is_busy());
311 }
312
313 #[test]
314 fn only_the_errors_worth_retrying_say_they_are() {
315 let busy = Error::Http {
316 operation: "requestPairing",
317 status: Status(503),
318 detail: None,
319 };
320 assert!(busy.is_transient());
321 let refused = Error::Http {
322 operation: "requestPairing",
323 status: Status(400),
324 detail: None,
325 };
326 assert!(!refused.is_transient());
327 assert!(!Error::IdentityChanged.is_transient());
328 assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
329 assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
330 }
331}