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(
99 "the endpoint offers API versions {offered:?}, none of which this crate speaks ({supported:?})"
100 )]
101 NoCommonApiVersion {
102 offered: Vec<String>,
104 supported: &'static [&'static str],
106 },
107 #[error("{operation} answered with more than {max} bytes")]
109 ResponseTooLarge {
110 operation: &'static str,
112 max: usize,
114 },
115}
116
117impl Error {
118 #[must_use]
124 pub fn is_transient(&self) -> bool {
125 match self {
126 Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
128 Error::Http { status, .. } => status.is_busy(),
131 _ => false,
132 }
133 }
134}
135
136pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
150
151pub const API_VERSIONS: &[&str] = &["v1"];
153
154#[derive(Debug, Clone)]
156pub(crate) struct Http {
157 client: reqwest::Client,
158 base: url::Url,
161 versioned: tokio::sync::OnceCell<url::Url>,
163 tls: TlsClient,
164}
165
166impl Http {
167 pub(crate) fn new(
176 base: &str,
177 policy: &TlsPolicy,
178 timeout: core::time::Duration,
179 ) -> Result<Self, Error> {
180 let tls = TlsClient::new(policy)?;
181 let base = normalize(base)?;
182 let client = reqwest::Client::builder()
183 .use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
184 .timeout(timeout)
185 .https_only(true)
188 .redirect(reqwest::redirect::Policy::none())
189 .user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
190 .build()
191 .map_err(|e| Error::Transport {
192 operation: "building the HTTPS client",
193 source: Box::new(e),
194 })?;
195 let versioned = tokio::sync::OnceCell::new();
196 if base
197 .path_segments()
198 .and_then(|mut segments| segments.rfind(|s| !s.is_empty()))
199 .is_some_and(is_version_segment)
200 {
201 let _ = versioned.set(base.clone());
202 }
203 Ok(Self {
204 client,
205 base,
206 versioned,
207 tls,
208 })
209 }
210
211 async fn versioned(&self) -> Result<&url::Url, Error> {
213 self.versioned
214 .get_or_try_init(|| async {
215 const OPERATION: &str = "the API version index";
216 let response = self
217 .client
218 .get(self.base.clone())
219 .send()
220 .await
221 .map_err(|e| Error::Transport {
222 operation: OPERATION,
223 source: Box::new(e),
224 })?;
225 let text = self.read(OPERATION, response).await?;
226 let offered: Vec<String> =
227 serde_json::from_str(&text).map_err(|source| Error::Body {
228 operation: OPERATION,
229 source,
230 })?;
231 let chosen = API_VERSIONS
232 .iter()
233 .find(|ours| offered.iter().any(|theirs| theirs == *ours))
234 .ok_or_else(|| Error::NoCommonApiVersion {
235 offered: offered.clone(),
236 supported: API_VERSIONS,
237 })?;
238 self.base
239 .join(&alloc::format!("{chosen}/"))
240 .map_err(|_| Error::Url(alloc::format!("{}{chosen}/", self.base)))
241 })
242 .await
243 }
244
245 pub(crate) fn tls(&self) -> &TlsClient {
246 &self.tls
247 }
248
249 pub(crate) fn base(&self) -> &url::Url {
250 &self.base
251 }
252
253 pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
255 &self,
256 operation: &'static str,
257 path: &str,
258 bearer: Option<&str>,
259 body: &B,
260 ) -> Result<R, Error> {
261 let text = self.post_raw(operation, path, bearer, Some(body)).await?;
262 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
263 }
264
265 pub(crate) async fn post_bodyless<R: DeserializeOwned>(
273 &self,
274 operation: &'static str,
275 path: &str,
276 bearer: Option<&str>,
277 ) -> Result<R, Error> {
278 let url = self.join(path).await?;
279 let mut request = self.client.post(url);
280 if let Some(token) = bearer {
281 request = request.bearer_auth(token);
282 }
283 let response = request.send().await.map_err(|e| Error::Transport {
284 operation,
285 source: Box::new(e),
286 })?;
287 let text = self.read(operation, response).await?;
288 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
289 }
290
291 pub(crate) async fn post_or_no_content<B: Serialize, R: DeserializeOwned>(
296 &self,
297 operation: &'static str,
298 path: &str,
299 bearer: Option<&str>,
300 body: &B,
301 ) -> Result<Option<R>, Error> {
302 let url = self.join(path).await?;
303 let mut request = self.client.post(url).json(body);
304 if let Some(token) = bearer {
305 request = request.bearer_auth(token);
306 }
307 let response = request.send().await.map_err(|e| Error::Transport {
308 operation,
309 source: Box::new(e),
310 })?;
311 if response.status() == reqwest::StatusCode::NO_CONTENT {
312 return Ok(None);
313 }
314 let text = self.read(operation, response).await?;
315 serde_json::from_str(&text)
316 .map(Some)
317 .map_err(|source| Error::Body { operation, source })
318 }
319
320 pub(crate) async fn post_empty<B: Serialize>(
322 &self,
323 operation: &'static str,
324 path: &str,
325 bearer: Option<&str>,
326 body: Option<&B>,
327 ) -> Result<(), Error> {
328 self.post_raw(operation, path, bearer, body).await.map(drop)
329 }
330
331 pub(crate) async fn get<R: DeserializeOwned>(
333 &self,
334 operation: &'static str,
335 path: &str,
336 ) -> Result<R, Error> {
337 let url = self.join(path).await?;
338 let response = self
339 .client
340 .get(url)
341 .send()
342 .await
343 .map_err(|e| Error::Transport {
344 operation,
345 source: Box::new(e),
346 })?;
347 let text = self.read(operation, response).await?;
348 serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
349 }
350
351 async fn post_raw<B: Serialize>(
352 &self,
353 operation: &'static str,
354 path: &str,
355 bearer: Option<&str>,
356 body: Option<&B>,
357 ) -> Result<String, Error> {
358 let url = self.join(path).await?;
359 let mut request = self.client.post(url);
360 if let Some(token) = bearer {
361 request = request.bearer_auth(token);
362 }
363 if let Some(body) = body {
364 request = request.json(body);
365 }
366 let response = request.send().await.map_err(|e| Error::Transport {
367 operation,
368 source: Box::new(e),
369 })?;
370 self.read(operation, response).await
371 }
372
373 async fn read(
374 &self,
375 operation: &'static str,
376 response: reqwest::Response,
377 ) -> Result<String, Error> {
378 let status = Status(response.status().as_u16());
379 let text = read_bounded(operation, response).await?;
380 if status.is_success() {
381 return Ok(text);
382 }
383 Err(Error::Http {
384 operation,
385 status,
386 detail: (!text.is_empty()).then_some(text),
387 })
388 }
389
390 async fn join(&self, path: &str) -> Result<url::Url, Error> {
391 let base = self.versioned().await?;
392 base.join(path.trim_start_matches('/'))
393 .map_err(|_| Error::Url(alloc::format!("{base}{path}")))
394 }
395}
396
397fn is_version_segment(segment: &str) -> bool {
399 segment
400 .strip_prefix('v')
401 .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))
402}
403
404async fn read_bounded(
411 operation: &'static str,
412 mut response: reqwest::Response,
413) -> Result<String, Error> {
414 let too_large = || Error::ResponseTooLarge {
415 operation,
416 max: MAX_RESPONSE_BYTES,
417 };
418 if response
419 .content_length()
420 .is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
421 {
422 return Err(too_large());
423 }
424
425 let mut body: Vec<u8> = Vec::new();
426 loop {
427 let chunk = response.chunk().await.map_err(|e| Error::Transport {
428 operation,
429 source: Box::new(e),
430 })?;
431 let Some(chunk) = chunk else { break };
432 if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
433 return Err(too_large());
434 }
435 body.extend_from_slice(&chunk);
436 }
437 String::from_utf8(body).map_err(|e| Error::Transport {
440 operation,
441 source: Box::new(e),
442 })
443}
444
445fn normalize(base: &str) -> Result<url::Url, Error> {
451 let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
452 if url.scheme() != "https" {
453 return Err(Error::Url(alloc::format!(
454 "{base} is not HTTPS, and S2 Connect is HTTPS only"
455 )));
456 }
457 if !url.path().ends_with('/') {
458 let path = alloc::format!("{}/", url.path());
459 url.set_path(&path);
460 }
461 Ok(url)
462}
463
464#[cfg(test)]
465mod tests {
466 use super::*;
467
468 #[test]
469 fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
470 let url = normalize("https://evse.local/v1").unwrap();
473 assert_eq!(url.as_str(), "https://evse.local/v1/");
474 assert_eq!(
475 url.join("requestPairing").unwrap().as_str(),
476 "https://evse.local/v1/requestPairing"
477 );
478 assert_eq!(
480 normalize("https://evse.local/v1/").unwrap().as_str(),
481 "https://evse.local/v1/"
482 );
483 }
484
485 #[test]
486 fn a_versioned_base_is_recognised_and_an_unversioned_one_is_not() {
487 assert!(is_version_segment("v1"));
488 assert!(is_version_segment("v12"));
489 assert!(!is_version_segment("v"));
490 assert!(!is_version_segment("pairing"));
491 assert!(!is_version_segment("v1beta"));
492 }
493
494 #[test]
495 fn plain_http_is_refused_rather_than_upgraded() {
496 assert!(matches!(
498 normalize("http://evse.local/v1/"),
499 Err(Error::Url(_))
500 ));
501 assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
502 assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
503 }
504
505 #[test]
506 fn the_statuses_the_specification_distinguishes_are_distinguished() {
507 assert!(Status(200).is_success());
508 assert!(Status(204).is_success());
509 assert!(!Status(400).is_success());
510 assert!(Status(401).is_unauthorized());
513 assert!(Status(403).is_forbidden());
515 assert!(Status(503).is_busy());
518 }
519
520 #[test]
521 fn only_the_errors_worth_retrying_say_they_are() {
522 let busy = Error::Http {
523 operation: "requestPairing",
524 status: Status(503),
525 detail: None,
526 };
527 assert!(busy.is_transient());
528 let refused = Error::Http {
529 operation: "requestPairing",
530 status: Status(400),
531 detail: None,
532 };
533 assert!(!refused.is_transient());
534 assert!(!Error::IdentityChanged.is_transient());
535 assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
536 assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
537 }
538}