1use crate::{
2 ApiError, ApiResponse, Config, Error, RequestOptions, Result, WebSocketConnection, auth::Auth,
3 config::validate_limits, error::invalid,
4};
5use reqwest::{
6 Body, Method, Url,
7 header::{HeaderMap, HeaderName, HeaderValue},
8};
9use serde::Serialize;
10use serde_json::Value;
11use std::{
12 sync::Arc,
13 time::{Duration, SystemTime},
14};
15
16#[derive(Clone)]
17pub struct Client {
18 pub(crate) inner: Arc<Inner>,
19}
20pub(crate) struct Inner {
21 pub config: Config,
22 http: reqwest::Client,
23 auth: Auth,
24 token_url: String,
25}
26impl std::fmt::Debug for Client {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 f.debug_struct("Client").finish_non_exhaustive()
29 }
30}
31impl Client {
32 pub fn new(config: Config) -> Result<Self> {
34 config.validate()?;
35 let token_url = config
36 .token_url
37 .clone()
38 .unwrap_or(config.endpoint("iam", "https://iam.basaltic.sh")? + "/v1/oauth/token");
39 let http = reqwest::Client::builder()
40 .no_proxy()
41 .redirect(reqwest::redirect::Policy::none())
42 .retry(reqwest::retry::never())
43 .build()?;
44 let auth = Auth::new(config.credentials.clone())?;
45 Ok(Self {
46 inner: Arc::new(Inner {
47 config,
48 http,
49 auth,
50 token_url,
51 }),
52 })
53 }
54 pub fn from_env() -> Result<Self> {
55 Self::new(Config::from_env()?)
56 }
57}
58
59pub(crate) struct QueryEncoding {
60 pub name: &'static str,
61 pub style: &'static str,
62 pub explode: bool,
63}
64pub(crate) struct Operation {
65 pub id: &'static str,
66 pub method: &'static str,
67 pub path: &'static str,
68 pub authenticated: bool,
69 pub required_query: &'static [&'static str],
70 pub required_headers: &'static [&'static str],
71 pub content_type: &'static str,
72 pub accept: &'static str,
73 pub query_encoding: &'static [QueryEncoding],
74}
75pub(crate) enum Payload {
76 Empty,
77 Bytes(Vec<u8>),
78 Stream(Option<Body>),
79}
80impl Payload {
81 pub fn json<T: Serialize>(body: &T) -> Result<Self> {
82 Ok(Self::Bytes(serde_json::to_vec(body)?))
83 }
84 #[allow(dead_code)]
86 pub fn form<T: Serialize>(body: &T) -> Result<Self> {
87 Ok(Self::Bytes(
88 encode_query(&serde_json::to_value(body)?, &[])?.into_bytes(),
89 ))
90 }
91 pub fn binary(body: Body) -> Self {
92 if let Some(bytes) = body.as_bytes() {
93 Self::Bytes(bytes.to_vec())
94 } else {
95 Self::Stream(Some(body))
96 }
97 }
98 fn try_clone(&self) -> Result<Self> {
99 match self {
100 Self::Empty => Ok(Self::Empty),
101 Self::Bytes(v) => Ok(Self::Bytes(v.clone())),
102 Self::Stream(_) => Err(invalid("Streaming bodies cannot be replayed")),
103 }
104 }
105}
106
107pub(crate) struct Core {
108 pub client: Client,
109 pub service: &'static str,
110 pub endpoint: &'static str,
111 pub op: &'static Operation,
112 pub path: Vec<(String, String)>,
113 pub body: Payload,
114 pub query: Value,
115 pub options: RequestOptions,
116}
117impl Core {
118 pub fn new(
119 client: Client,
120 service: &'static str,
121 endpoint: &'static str,
122 op: &'static Operation,
123 path: &[(&str, &str)],
124 body: Result<Payload>,
125 query: Result<Value>,
126 ) -> Result<Self> {
127 Ok(Self {
128 client,
129 service,
130 endpoint,
131 op,
132 path: path
133 .iter()
134 .map(|(k, v)| (k.to_string(), v.to_string()))
135 .collect(),
136 body: body?,
137 query: query?,
138 options: RequestOptions::default(),
139 })
140 }
141 pub fn try_clone(&self) -> Result<Self> {
142 Ok(Self {
143 client: self.client.clone(),
144 service: self.service,
145 endpoint: self.endpoint,
146 op: self.op,
147 path: self.path.clone(),
148 body: self.body.try_clone()?,
149 query: self.query.clone(),
150 options: self.options.clone(),
151 })
152 }
153 fn prepare(&self) -> Result<(Url, HeaderMap, Duration, u8)> {
154 let config = &self.client.inner.config;
155 let options = &self.options;
156 let timeout = options.timeout.unwrap_or(config.timeout);
157 let attempts = if matches!(self.body, Payload::Stream(_)) {
158 1
159 } else {
160 options.max_attempts.unwrap_or(config.max_attempts)
161 };
162 validate_limits(timeout, options.max_attempts.unwrap_or(config.max_attempts))?;
163 let mut route = self.op.path.to_owned();
164 for (key, value) in &self.path {
165 if value.is_empty() || value == "." || value == ".." {
166 return Err(invalid(
167 "Path parameters must be nonempty and cannot be dot segments",
168 ));
169 }
170 route = route.replace(&format!("{{{key}}}"), &percent(value));
171 }
172 if route.contains('{') {
173 return Err(invalid("Missing path parameter"));
174 }
175 for key in self.op.required_query {
176 if self.query.get(*key).is_none_or(Value::is_null) {
177 return Err(invalid("Missing required query parameter"));
178 }
179 }
180 let query = encode_query(&self.query, self.op.query_encoding)?;
181 let url = Url::parse(
182 &(config.endpoint(self.service, self.endpoint)?
183 + &route
184 + if query.is_empty() {
185 String::new()
186 } else {
187 "?".to_string() + &query
188 }
189 .as_str()),
190 )
191 .map_err(|_| invalid("Invalid request URL"))?;
192 let mut headers = HeaderMap::new();
193 header(&mut headers, "accept", self.op.accept)?;
194 header(
195 &mut headers,
196 "user-agent",
197 concat!("basaltic-rust/", env!("CARGO_PKG_VERSION")),
198 )?;
199 if !matches!(self.body, Payload::Empty) && !self.op.content_type.is_empty() {
200 header(&mut headers, "content-type", self.op.content_type)?;
201 }
202 let account = options.account_id.as_ref().unwrap_or(&config.account_id);
203 if !account.is_empty() {
204 header(&mut headers, "x-account-id", account)?;
205 }
206 if let Some(key) = &options.idempotency_key {
207 if key.trim().is_empty() {
208 return Err(invalid("Idempotency key cannot be empty"));
209 }
210 header(&mut headers, "idempotency-key", key)?;
211 }
212 for (key, value) in &options.headers {
213 if matches!(
214 key.as_str(),
215 "authorization"
216 | "host"
217 | "cookie"
218 | "content-length"
219 | "content-type"
220 | "accept"
221 | "user-agent"
222 | "x-account-id"
223 | "idempotency-key"
224 | "transfer-encoding"
225 ) {
226 return Err(invalid("Cannot override a managed HTTP header"));
227 }
228 if value.as_bytes().iter().any(|b| b.is_ascii_control()) {
229 return Err(invalid("HTTP header contains a control character"));
230 }
231 headers.insert(key.clone(), value.clone());
232 }
233 for key in self.op.required_headers {
234 if headers.get(*key).is_none_or(|v| v.is_empty()) {
235 return Err(invalid("Missing required header"));
236 }
237 }
238 Ok((url, headers, timeout, attempts))
239 }
240 async fn token(&self) -> Result<String> {
241 if !self.op.authenticated {
242 return Ok(String::new());
243 }
244 let inner = &self.client.inner;
245 inner
246 .auth
247 .token(
248 &inner.http,
249 &inner.token_url,
250 self.options.timeout.unwrap_or(inner.config.timeout),
251 )
252 .await
253 }
254 pub async fn websocket(&self) -> Result<WebSocketConnection> {
255 let (mut url, mut headers, _, _) = self.prepare()?;
256 let scheme = if url.scheme() == "https" { "wss" } else { "ws" };
257 url.set_scheme(scheme)
258 .map_err(|_| invalid("Invalid websocket URL"))?;
259 let token = self.token().await?;
260 if !token.is_empty() {
261 header(&mut headers, "authorization", &format!("Bearer {token}"))?;
262 }
263 Ok(WebSocketConnection {
264 url: url.into(),
265 headers,
266 })
267 }
268 pub async fn send(mut self) -> Result<reqwest::Response> {
269 let (url, headers, timeout, attempts) = self.prepare()?;
270 let repeatable = matches!(
271 self.op.method,
272 "GET" | "HEAD" | "OPTIONS" | "PUT" | "DELETE"
273 ) || self.options.idempotency_key.is_some();
274 let method = Method::from_bytes(self.op.method.as_bytes())
275 .map_err(|_| invalid("Invalid operation method"))?;
276 let mut refreshed = false;
277 for attempt in 1..=attempts {
278 let token = self.token().await?;
279 let inner = &self.client.inner;
280 let mut request = inner
281 .http
282 .request(method.clone(), url.clone())
283 .headers(headers.clone())
284 .timeout(timeout);
285 if !token.is_empty() {
286 request = request.bearer_auth(&token);
287 }
288 request = match &mut self.body {
289 Payload::Empty => request,
290 Payload::Bytes(v) => request.body(v.clone()),
291 Payload::Stream(body) => request.body(
292 body.take()
293 .ok_or_else(|| invalid("Streaming body was already consumed"))?,
294 ),
295 };
296 match request.send().await {
297 Ok(response) if response.status().is_success() => return Ok(response),
298 Ok(response) => {
299 let status = response.status().as_u16();
300 if status == 401
301 && self.op.authenticated
302 && !refreshed
303 && attempt < attempts
304 && inner.auth.refreshable()
305 {
306 drop(response);
307 inner.auth.invalidate(&token).await;
308 refreshed = true;
309 continue;
310 }
311 if repeatable
312 && attempt < attempts
313 && matches!(status, 429 | 500 | 502 | 503 | 504)
314 && let Some(delay) = retry_delay(
315 &inner.config,
316 attempt,
317 response
318 .headers()
319 .get("retry-after")
320 .and_then(|v| v.to_str().ok()),
321 )
322 {
323 drop(response);
324 tokio::time::sleep(delay).await;
325 continue;
326 }
327 return Err(api_error(response, self.op.id).await);
328 }
329 Err(e) => {
330 let failure = Error::from(e);
331 if !repeatable || attempt == attempts {
332 return Err(failure);
333 }
334 tokio::time::sleep(backoff(&inner.config, attempt)).await;
335 }
336 }
337 }
338 Err(Error::Transport)
339 }
340}
341
342fn header(headers: &mut HeaderMap, key: &str, value: &str) -> Result<()> {
343 if value.bytes().any(|b| b.is_ascii_control()) {
344 return Err(invalid("HTTP header contains a control character"));
345 }
346 let name =
347 HeaderName::from_bytes(key.as_bytes()).map_err(|_| invalid("Invalid HTTP header name"))?;
348 let mut value =
349 HeaderValue::from_str(value).map_err(|_| invalid("Invalid HTTP header value"))?;
350 if name == "authorization" {
351 value.set_sensitive(true);
352 }
353 headers.insert(name, value);
354 Ok(())
355}
356fn percent(value: &str) -> String {
357 let mut encoded = String::new();
358 for b in value.bytes() {
359 if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
360 encoded.push(b as char);
361 } else {
362 use std::fmt::Write;
363 let _ = write!(encoded, "%{b:02X}");
364 }
365 }
366 encoded
367}
368fn scalar(value: &Value) -> Result<String> {
369 match value {
370 Value::String(v) => Ok(v.clone()),
371 Value::Number(v) => Ok(v.to_string()),
372 Value::Bool(v) => Ok(v.to_string()),
373 _ => Err(invalid("Query values must be scalars or arrays of scalars")),
374 }
375}
376pub(crate) fn encode_query(value: &Value, encodings: &[QueryEncoding]) -> Result<String> {
377 if value.is_null() {
378 return Ok(String::new());
379 }
380 let values = value
381 .as_object()
382 .ok_or_else(|| invalid("Query or form body must be an object"))?;
383 let mut pairs = Vec::new();
384 for (key, value) in values {
385 if value.is_null() {
386 continue;
387 }
388 let prefix = percent(key) + "=";
389 if let Some(values) = value.as_array() {
390 let values = values.iter().map(scalar).collect::<Result<Vec<_>>>()?;
391 let encoding = encodings.iter().find(|e| e.name == key);
392 if encoding.is_none_or(|e| e.explode) {
393 pairs.extend(values.iter().map(|v| prefix.clone() + &percent(v)));
394 } else {
395 let separator = match encoding.map(|e| e.style) {
396 Some("spaceDelimited") => " ",
397 Some("pipeDelimited") => "|",
398 _ => ",",
399 };
400 pairs.push(prefix + &percent(&values.join(separator)));
401 }
402 } else {
403 pairs.push(prefix + &percent(&scalar(value)?));
404 }
405 }
406 Ok(pairs.join("&"))
407}
408fn backoff(config: &Config, attempt: u8) -> Duration {
409 config
410 .base_delay
411 .saturating_mul(1u32 << (attempt - 1))
412 .min(config.max_delay)
413 .mul_f64(fastrand::f64())
414}
415fn retry_delay(config: &Config, attempt: u8, value: Option<&str>) -> Option<Duration> {
416 let Some(value) = value else {
417 return Some(backoff(config, attempt));
418 };
419 let parsed = if value.bytes().all(|b| b.is_ascii_digit()) && !value.is_empty() {
420 Some(Duration::from_secs(value.parse::<u64>().ok()?))
421 } else {
422 httpdate::parse_http_date(value)
423 .ok()
424 .map(|date| date.duration_since(SystemTime::now()).unwrap_or_default())
425 };
426 match parsed {
427 Some(delay) if delay > config.max_delay => None,
428 Some(delay) => Some(delay),
429 None => Some(backoff(config, attempt)),
430 }
431}
432async fn api_error(mut response: reqwest::Response, operation: &str) -> Error {
433 let status = response.status().as_u16();
434 let headers = response.headers().clone();
435 let mut raw = Vec::new();
436 while let Ok(Some(chunk)) = response.chunk().await {
437 let count = chunk.len().min(1_048_576 - raw.len());
438 raw.extend_from_slice(&chunk[..count]);
439 if raw.len() == 1_048_576 {
440 break;
441 }
442 }
443 let data: Value = serde_json::from_slice(&raw).unwrap_or(Value::Null);
444 let get = |key: &str| {
445 data.get("error")
446 .and_then(|v| v.get(key))
447 .and_then(Value::as_str)
448 };
449 Error::Api(Box::new(ApiError {
450 status,
451 code: get("code").unwrap_or("").into(),
452 message: get("message").unwrap_or("Unexpected API response").into(),
453 request_id: get("request_id")
454 .unwrap_or_else(|| {
455 headers
456 .get("x-request-id")
457 .and_then(|v| v.to_str().ok())
458 .unwrap_or("")
459 })
460 .into(),
461 operation: operation.into(),
462 headers,
463 }))
464}
465pub(crate) async fn json_response(response: reqwest::Response) -> Result<ApiResponse<Value>> {
466 let status = response.status().as_u16();
467 let headers = response.headers().clone();
468 let bytes = response.bytes().await?;
469 let data: Value = if bytes.iter().all(u8::is_ascii_whitespace) {
470 serde_json::json!({})
471 } else {
472 serde_json::from_slice(&bytes)?
473 };
474 if !data.is_object() && !data.is_array() {
475 return Err(Error::Protocol("Expected a JSON object or array".into()));
476 }
477 Ok(ApiResponse {
478 data,
479 status,
480 headers,
481 })
482}