1use alloc::string::{String, ToString};
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7
8use serde::Serialize;
9use serde::de::DeserializeOwned;
10
11use crate::connect::proto::ConnectError;
12use crate::connect::tls::{TlsClient, TlsPolicy};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Status(pub u16);
22
23impl Status {
24 #[must_use]
26 pub const fn is_success(self) -> bool {
27 self.0 >= 200 && self.0 < 300
28 }
29
30 #[must_use]
32 pub const fn is_unauthorized(self) -> bool {
33 self.0 == 401
34 }
35
36 #[must_use]
38 pub const fn is_forbidden(self) -> bool {
39 self.0 == 403
40 }
41
42 #[must_use]
44 pub const fn is_busy(self) -> bool {
45 self.0 == 503
46 }
47}
48
49impl core::fmt::Display for Status {
50 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
51 write!(f, "{}", self.0)
52 }
53}
54
55#[derive(Debug, thiserror::Error)]
57#[non_exhaustive]
58pub enum Error {
59 #[error(transparent)]
61 Protocol(#[from] ConnectError),
62 #[error(transparent)]
64 Tls(#[from] crate::connect::tls::Error),
65 #[error("{operation} failed: {source}")]
67 Transport {
68 operation: &'static str,
70 source: Box<dyn core::error::Error + Send + Sync>,
72 },
73 #[error("{operation} answered {status}{}", match .detail { Some(d) => alloc::format!(": {d}"), None => String::new() })]
75 Http {
76 operation: &'static str,
78 status: Status,
80 detail: Option<String>,
82 },
83 #[error("{operation} answered with a body that is not what the schema defines: {source}")]
85 Body {
86 operation: &'static str,
88 source: serde_json::Error,
90 },
91 #[error("{0} is not a usable URL")]
93 Url(String),
94 #[error("the server's certificate changed during the pairing attempt")]
96 IdentityChanged,
97 #[error("{operation} answered with more than {max} bytes")]
99 ResponseTooLarge {
100 operation: &'static str,
102 max: usize,
104 },
105}
106
107impl Error {
108 #[must_use]
114 pub fn is_transient(&self) -> bool {
115 match self {
116 Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
118 Error::Http { status, .. } => status.is_busy(),
121 _ => false,
122 }
123 }
124}
125
126pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
140
141#[derive(Debug, Clone)]
143pub(crate) struct Http {
144 client: reqwest::Client,
145 base: url::Url,
146 tls: TlsClient,
147}
148
149impl Http {
150 pub(crate) fn new(
152 base: &str,
153 policy: &TlsPolicy,
154 timeout: core::time::Duration,
155 ) -> Result<Self, Error> {
156 let tls = TlsClient::new(policy)?;
157 let base = normalize(base)?;
158 let client = reqwest::Client::builder()
159 .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
160 .timeout(timeout)
161 .https_only(true)
164 .redirect(reqwest::redirect::Policy::none())
165 .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
166 .build()
167 .map_err(|e| Error::Transport {
168 operation: "building the HTTPS client",
169 source: Box::new(e),
170 })?;
171 Ok(Self { client, base, tls })
172 }
173
174 pub(crate) fn tls(&self) -> &TlsClient {
175 &self.tls
176 }
177
178 pub(crate) fn base(&self) -> &url::Url {
179 &self.base
180 }
181
182 pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
184 &self,
185 operation: &'static str,
186 path: &str,
187 bearer: Option<&str>,
188 body: &B,
189 ) -> Result<R, Error> {
190 let text = self.post_raw(operation, path, bearer, Some(body)).await?;
191 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
192 }
193
194 pub(crate) async fn post_bodyless<R: DeserializeOwned>(
202 &self,
203 operation: &'static str,
204 path: &str,
205 bearer: Option<&str>,
206 ) -> Result<R, Error> {
207 let url = self.join(path)?;
208 let mut request = self.client.post(url);
209 if let Some(token) = bearer {
210 request = request.bearer_auth(token);
211 }
212 let response = request.send().await.map_err(|e| Error::Transport {
213 operation,
214 source: Box::new(e),
215 })?;
216 let text = self.read(operation, response).await?;
217 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
218 }
219
220 pub(crate) async fn post_empty<B: Serialize>(
222 &self,
223 operation: &'static str,
224 path: &str,
225 bearer: Option<&str>,
226 body: Option<&B>,
227 ) -> Result<(), Error> {
228 self.post_raw(operation, path, bearer, body).await.map(drop)
229 }
230
231 pub(crate) async fn get<R: DeserializeOwned>(
233 &self,
234 operation: &'static str,
235 path: &str,
236 ) -> Result<R, Error> {
237 let url = self.join(path)?;
238 let response = self
239 .client
240 .get(url)
241 .send()
242 .await
243 .map_err(|e| Error::Transport {
244 operation,
245 source: Box::new(e),
246 })?;
247 let text = self.read(operation, response).await?;
248 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
249 }
250
251 async fn post_raw<B: Serialize>(
252 &self,
253 operation: &'static str,
254 path: &str,
255 bearer: Option<&str>,
256 body: Option<&B>,
257 ) -> Result<String, Error> {
258 let url = self.join(path)?;
259 let mut request = self.client.post(url);
260 if let Some(token) = bearer {
261 request = request.bearer_auth(token);
262 }
263 if let Some(body) = body {
264 request = request.json(body);
265 }
266 let response = request.send().await.map_err(|e| Error::Transport {
267 operation,
268 source: Box::new(e),
269 })?;
270 self.read(operation, response).await
271 }
272
273 async fn read(
274 &self,
275 operation: &'static str,
276 response: reqwest::Response,
277 ) -> Result<String, Error> {
278 let status = Status(response.status().as_u16());
279 let text = read_bounded(operation, response).await?;
280 if status.is_success() {
281 return Ok(text);
282 }
283 Err(Error::Http {
284 operation,
285 status,
286 detail: (!text.is_empty()).then_some(text),
287 })
288 }
289
290 fn join(&self, path: &str) -> Result<url::Url, Error> {
291 self.base
292 .join(path.trim_start_matches('/'))
293 .map_err(|_| Error::Url(alloc::format!("{}{path}", self.base)))
294 }
295}
296
297async fn read_bounded(
304 operation: &'static str,
305 mut response: reqwest::Response,
306) -> Result<String, Error> {
307 let too_large = || Error::ResponseTooLarge {
308 operation,
309 max: MAX_RESPONSE_BYTES,
310 };
311 if response
312 .content_length()
313 .is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
314 {
315 return Err(too_large());
316 }
317
318 let mut body: Vec<u8> = Vec::new();
319 loop {
320 let chunk = response.chunk().await.map_err(|e| Error::Transport {
321 operation,
322 source: Box::new(e),
323 })?;
324 let Some(chunk) = chunk else { break };
325 if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
326 return Err(too_large());
327 }
328 body.extend_from_slice(&chunk);
329 }
330 String::from_utf8(body).map_err(|e| Error::Transport {
333 operation,
334 source: Box::new(e),
335 })
336}
337
338fn normalize(base: &str) -> Result<url::Url, Error> {
344 let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
345 if url.scheme() != "https" {
346 return Err(Error::Url(alloc::format!(
347 "{base} is not HTTPS, and S2 Connect is HTTPS only"
348 )));
349 }
350 if !url.path().ends_with('/') {
351 let path = alloc::format!("{}/", url.path());
352 url.set_path(&path);
353 }
354 Ok(url)
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 #[test]
362 fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
363 let url = normalize("https://evse.local/v1").unwrap();
366 assert_eq!(url.as_str(), "https://evse.local/v1/");
367 assert_eq!(
368 url.join("requestPairing").unwrap().as_str(),
369 "https://evse.local/v1/requestPairing"
370 );
371 assert_eq!(
373 normalize("https://evse.local/v1/").unwrap().as_str(),
374 "https://evse.local/v1/"
375 );
376 }
377
378 #[test]
379 fn plain_http_is_refused_rather_than_upgraded() {
380 assert!(matches!(
382 normalize("http://evse.local/v1/"),
383 Err(Error::Url(_))
384 ));
385 assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
386 assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
387 }
388
389 #[test]
390 fn the_statuses_the_specification_distinguishes_are_distinguished() {
391 assert!(Status(200).is_success());
392 assert!(Status(204).is_success());
393 assert!(!Status(400).is_success());
394 assert!(Status(401).is_unauthorized());
397 assert!(Status(403).is_forbidden());
399 assert!(Status(503).is_busy());
402 }
403
404 #[test]
405 fn only_the_errors_worth_retrying_say_they_are() {
406 let busy = Error::Http {
407 operation: "requestPairing",
408 status: Status(503),
409 detail: None,
410 };
411 assert!(busy.is_transient());
412 let refused = Error::Http {
413 operation: "requestPairing",
414 status: Status(400),
415 detail: None,
416 };
417 assert!(!refused.is_transient());
418 assert!(!Error::IdentityChanged.is_transient());
419 assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
420 assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
421 }
422}