passalong_https/
client.rs1use std::time::Duration;
6
7use passalong_core::api_key::ApiKey;
8use passalong_core::config::HttpsConfig;
9use passalong_core::random::{RandomSource, StdRandom};
10use reqwest::header::RETRY_AFTER;
11use serde::de::DeserializeOwned;
12
13use crate::api::{Viewer, Workspace};
14use crate::error::{self, HttpsError, Next, Problem};
15use crate::tls;
16
17pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
19pub const READ_TIMEOUT: Duration = Duration::from_secs(60);
21
22pub struct Client {
24 http: reqwest::Client,
25 base: String,
26 key: ApiKey,
27}
28
29impl std::fmt::Debug for Client {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 f.debug_struct("Client")
32 .field("base", &self.base)
33 .field("key", &self.key)
34 .finish_non_exhaustive()
35 }
36}
37
38impl Client {
39 pub fn new(config: &HttpsConfig, key: ApiKey) -> Result<Self, HttpsError> {
45 let setup = |reason: String| HttpsError::Transport {
46 url: config.url.clone(),
47 reason,
48 retryable: false,
49 };
50 let tls = tls::client_config(config.tls_pin)
51 .map_err(|err| setup(format!("setting up TLS: {err}")))?;
52 let http = reqwest::Client::builder()
53 .tls_backend_preconfigured(tls)
54 .https_only(true)
55 .connect_timeout(CONNECT_TIMEOUT)
56 .read_timeout(READ_TIMEOUT)
57 .user_agent(format!("passalong/{}", passalong_core::VERSION))
58 .build()
59 .map_err(|err| setup(chain(&err)))?;
60 Ok(Self {
61 http,
62 base: config.url.clone(),
63 key,
64 })
65 }
66
67 pub fn key(&self) -> &ApiKey {
69 &self.key
70 }
71
72 pub fn url(&self, path: &str) -> String {
74 format!("{}/v1{path}", self.base)
75 }
76
77 pub async fn send<F>(&self, what: &str, build: F) -> Result<reqwest::Response, HttpsError>
85 where
86 F: Fn(&reqwest::Client) -> reqwest::RequestBuilder,
87 {
88 let mut attempts = 0;
89 loop {
90 attempts += 1;
91 let request_id = format!("{:016x}", StdRandom::new().next_u64());
92 tracing::debug!(request = %request_id, what, attempt = attempts, "sending");
93 let result = build(&self.http)
94 .bearer_auth(self.key.expose())
95 .header("X-Request-Id", &request_id)
96 .send()
97 .await;
98 let err = match result {
99 Ok(response) if response.status().is_success() => return Ok(response),
100 Ok(response) => refused(response).await,
101 Err(err) => transport(&self.base, &err),
102 };
103 match error::next(&err, attempts) {
104 Next::Stop => return Err(err),
105 Next::RetryAfter(wait) => {
106 tracing::info!(request = %request_id, what, error = %err, wait_ms = wait.as_millis(), "retrying");
107 tokio::time::sleep(wait).await;
108 }
109 }
110 }
111 }
112
113 pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T, HttpsError> {
120 let url = self.url(path);
121 let response = self.send(path, |http| http.get(&url)).await?;
122 json(response).await
123 }
124
125 pub async fn viewer(&self) -> Result<Viewer, HttpsError> {
131 self.get_json("/viewer").await
132 }
133
134 pub async fn workspace(&self) -> Result<Workspace, HttpsError> {
140 self.get_json("/workspace").await
141 }
142}
143
144pub async fn json<T: DeserializeOwned>(response: reqwest::Response) -> Result<T, HttpsError> {
151 let url = response.url().to_string();
152 let body = response
153 .bytes()
154 .await
155 .map_err(|err| transport(&url, &err))?;
156 serde_json::from_slice(&body).map_err(|err| HttpsError::Protocol(format!("{url}: {err}")))
157}
158
159async fn refused(response: reqwest::Response) -> HttpsError {
161 let status = response.status();
162 let retry_after = response
163 .headers()
164 .get(RETRY_AFTER)
165 .and_then(|value| value.to_str().ok())
166 .and_then(|value| value.trim().parse::<u64>().ok())
167 .map(Duration::from_secs);
168 let url = response.url().to_string();
169 match response.bytes().await {
170 Ok(body) => match serde_json::from_slice::<Problem>(&body) {
171 Ok(problem) => HttpsError::Refused {
172 problem,
173 retry_after,
174 },
175 Err(_) => HttpsError::Protocol(format!("{url}: HTTP {status} without a problem")),
176 },
177 Err(err) => transport(&url, &err),
178 }
179}
180
181fn transport(url: &str, err: &reqwest::Error) -> HttpsError {
184 let certificate = sources(err).any(refuses_certificate);
185 HttpsError::Transport {
186 url: url.to_owned(),
187 reason: chain(err),
188 retryable: !certificate
189 && (err.is_connect() || err.is_timeout() || err.is_request() || err.is_body()),
190 }
191}
192
193fn refuses_certificate(err: &(dyn std::error::Error + 'static)) -> bool {
197 let mut current = Some(err);
198 while let Some(error) = current {
199 if error
200 .downcast_ref::<rustls::Error>()
201 .is_some_and(|tls| matches!(tls, rustls::Error::InvalidCertificate(_)))
202 {
203 return true;
204 }
205 current = error
206 .downcast_ref::<std::io::Error>()
207 .and_then(std::io::Error::get_ref)
208 .map(|inner| inner as &(dyn std::error::Error + 'static));
209 }
210 false
211}
212
213fn sources<'a>(
215 err: &'a (dyn std::error::Error + 'static),
216) -> impl Iterator<Item = &'a (dyn std::error::Error + 'static)> {
217 std::iter::successors(Some(err), |err| err.source())
218}
219
220pub(crate) fn chain(err: &(dyn std::error::Error + 'static)) -> String {
223 let mut text = String::new();
224 for source in sources(err) {
225 let part = source.to_string();
226 if !text.contains(&part) {
227 if !text.is_empty() {
228 text.push_str(": ");
229 }
230 text.push_str(&part);
231 }
232 }
233 text
234}