use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::connect::proto::ConnectError;
use crate::connect::tls::{TlsClient, TlsPolicy};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Status(pub u16);
impl Status {
#[must_use]
pub const fn is_success(self) -> bool {
self.0 >= 200 && self.0 < 300
}
#[must_use]
pub const fn is_unauthorized(self) -> bool {
self.0 == 401
}
#[must_use]
pub const fn is_forbidden(self) -> bool {
self.0 == 403
}
#[must_use]
pub const fn is_busy(self) -> bool {
self.0 == 503
}
}
impl core::fmt::Display for Status {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Protocol(#[from] ConnectError),
#[error(transparent)]
Tls(#[from] crate::connect::tls::Error),
#[error("{operation} failed: {source}")]
Transport {
operation: &'static str,
source: Box<dyn core::error::Error + Send + Sync>,
},
#[error("{operation} answered {status}{}", match .detail { Some(d) => alloc::format!(": {d}"), None => String::new() })]
Http {
operation: &'static str,
status: Status,
detail: Option<String>,
},
#[error("{operation} answered with a body that is not what the schema defines: {source}")]
Body {
operation: &'static str,
source: serde_json::Error,
},
#[error("{0} is not a usable URL")]
Url(String),
#[error("the server's certificate changed during the pairing attempt")]
IdentityChanged,
#[error("{operation} answered with more than {max} bytes")]
ResponseTooLarge {
operation: &'static str,
max: usize,
},
}
impl Error {
#[must_use]
pub fn is_transient(&self) -> bool {
match self {
Error::Transport { .. } | Error::Protocol(ConnectError::RateLimited) => true,
Error::Http { status, .. } => status.is_busy(),
_ => false,
}
}
}
pub const MAX_RESPONSE_BYTES: usize = 256 * 1024;
#[derive(Debug, Clone)]
pub(crate) struct Http {
client: reqwest::Client,
base: url::Url,
tls: TlsClient,
}
impl Http {
pub(crate) fn new(
base: &str,
policy: &TlsPolicy,
timeout: core::time::Duration,
) -> Result<Self, Error> {
let tls = TlsClient::new(policy)?;
let base = normalize(base)?;
let client = reqwest::Client::builder()
.use_preconfigured_tls(Arc::unwrap_or_clone(tls.config()))
.timeout(timeout)
.https_only(true)
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("s2-kit/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| Error::Transport {
operation: "building the HTTPS client",
source: Box::new(e),
})?;
Ok(Self { client, base, tls })
}
pub(crate) fn tls(&self) -> &TlsClient {
&self.tls
}
pub(crate) fn base(&self) -> &url::Url {
&self.base
}
pub(crate) async fn post<B: Serialize, R: DeserializeOwned>(
&self,
operation: &'static str,
path: &str,
bearer: Option<&str>,
body: &B,
) -> Result<R, Error> {
let text = self.post_raw(operation, path, bearer, Some(body)).await?;
serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
}
pub(crate) async fn post_bodyless<R: DeserializeOwned>(
&self,
operation: &'static str,
path: &str,
bearer: Option<&str>,
) -> Result<R, Error> {
let url = self.join(path)?;
let mut request = self.client.post(url);
if let Some(token) = bearer {
request = request.bearer_auth(token);
}
let response = request.send().await.map_err(|e| Error::Transport {
operation,
source: Box::new(e),
})?;
let text = self.read(operation, response).await?;
serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
}
pub(crate) async fn post_empty<B: Serialize>(
&self,
operation: &'static str,
path: &str,
bearer: Option<&str>,
body: Option<&B>,
) -> Result<(), Error> {
self.post_raw(operation, path, bearer, body).await.map(drop)
}
pub(crate) async fn get<R: DeserializeOwned>(
&self,
operation: &'static str,
path: &str,
) -> Result<R, Error> {
let url = self.join(path)?;
let response = self
.client
.get(url)
.send()
.await
.map_err(|e| Error::Transport {
operation,
source: Box::new(e),
})?;
let text = self.read(operation, response).await?;
serde_json::from_str(&text).map_err(|source| Error::Body { operation, source })
}
async fn post_raw<B: Serialize>(
&self,
operation: &'static str,
path: &str,
bearer: Option<&str>,
body: Option<&B>,
) -> Result<String, Error> {
let url = self.join(path)?;
let mut request = self.client.post(url);
if let Some(token) = bearer {
request = request.bearer_auth(token);
}
if let Some(body) = body {
request = request.json(body);
}
let response = request.send().await.map_err(|e| Error::Transport {
operation,
source: Box::new(e),
})?;
self.read(operation, response).await
}
async fn read(
&self,
operation: &'static str,
response: reqwest::Response,
) -> Result<String, Error> {
let status = Status(response.status().as_u16());
let text = read_bounded(operation, response).await?;
if status.is_success() {
return Ok(text);
}
Err(Error::Http {
operation,
status,
detail: (!text.is_empty()).then_some(text),
})
}
fn join(&self, path: &str) -> Result<url::Url, Error> {
self.base
.join(path.trim_start_matches('/'))
.map_err(|_| Error::Url(alloc::format!("{}{path}", self.base)))
}
}
async fn read_bounded(
operation: &'static str,
mut response: reqwest::Response,
) -> Result<String, Error> {
let too_large = || Error::ResponseTooLarge {
operation,
max: MAX_RESPONSE_BYTES,
};
if response
.content_length()
.is_some_and(|len| len > MAX_RESPONSE_BYTES as u64)
{
return Err(too_large());
}
let mut body: Vec<u8> = Vec::new();
loop {
let chunk = response.chunk().await.map_err(|e| Error::Transport {
operation,
source: Box::new(e),
})?;
let Some(chunk) = chunk else { break };
if body.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
return Err(too_large());
}
body.extend_from_slice(&chunk);
}
String::from_utf8(body).map_err(|e| Error::Transport {
operation,
source: Box::new(e),
})
}
fn normalize(base: &str) -> Result<url::Url, Error> {
let mut url = url::Url::parse(base).map_err(|_| Error::Url(base.to_string()))?;
if url.scheme() != "https" {
return Err(Error::Url(alloc::format!(
"{base} is not HTTPS, and S2 Connect is HTTPS only"
)));
}
if !url.path().ends_with('/') {
let path = alloc::format!("{}/", url.path());
url.set_path(&path);
}
Ok(url)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_base_url_without_a_trailing_slash_still_joins_correctly() {
let url = normalize("https://evse.local/v1").unwrap();
assert_eq!(url.as_str(), "https://evse.local/v1/");
assert_eq!(
url.join("requestPairing").unwrap().as_str(),
"https://evse.local/v1/requestPairing"
);
assert_eq!(
normalize("https://evse.local/v1/").unwrap().as_str(),
"https://evse.local/v1/"
);
}
#[test]
fn plain_http_is_refused_rather_than_upgraded() {
assert!(matches!(
normalize("http://evse.local/v1/"),
Err(Error::Url(_))
));
assert!(matches!(normalize("ws://evse.local/"), Err(Error::Url(_))));
assert!(matches!(normalize("not a url"), Err(Error::Url(_))));
}
#[test]
fn the_statuses_the_specification_distinguishes_are_distinguished() {
assert!(Status(200).is_success());
assert!(Status(204).is_success());
assert!(!Status(400).is_success());
assert!(Status(401).is_unauthorized());
assert!(Status(403).is_forbidden());
assert!(Status(503).is_busy());
}
#[test]
fn only_the_errors_worth_retrying_say_they_are() {
let busy = Error::Http {
operation: "requestPairing",
status: Status(503),
detail: None,
};
assert!(busy.is_transient());
let refused = Error::Http {
operation: "requestPairing",
status: Status(400),
detail: None,
};
assert!(!refused.is_transient());
assert!(!Error::IdentityChanged.is_transient());
assert!(Error::Protocol(ConnectError::RateLimited).is_transient());
assert!(!Error::Protocol(ConnectError::ChallengeFailed).is_transient());
}
}