1pub mod client;
36pub mod models;
37pub mod params;
38
39pub use client::*;
43pub use models::*;
44pub use params::*;
45
46use std::fmt;
47use std::time::Duration;
48
49use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
50use reqwest::{Method, StatusCode, Url};
51use serde::de::DeserializeOwned;
52use serde::{Deserialize, Serialize};
53
54const DEFAULT_BASE_URL: &str = "https://app.infrawrench.com";
56
57const SCOPE_PARAM: Option<&str> = Some("orgId");
60
61#[derive(Debug, Clone, Default)]
70pub struct ClientConfig {
71 pub base_url: Option<String>,
73 pub api_key: Option<String>,
75 pub org_id: Option<String>,
77 pub headers: Vec<(String, String)>,
79 pub timeout: Option<Duration>,
81 pub http_client: Option<reqwest::Client>,
84}
85
86impl ClientConfig {
87 pub fn new() -> Self {
88 Self::default()
89 }
90
91 pub fn base_url(mut self, value: impl Into<String>) -> Self {
92 self.base_url = Some(value.into());
93 self
94 }
95
96 pub fn api_key(mut self, value: impl Into<String>) -> Self {
97 self.api_key = Some(value.into());
98 self
99 }
100
101 pub fn org_id(mut self, value: impl Into<String>) -> Self {
102 self.org_id = Some(value.into());
103 self
104 }
105
106 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
107 self.headers.push((name.into(), value.into()));
108 self
109 }
110
111 pub fn timeout(mut self, value: Duration) -> Self {
112 self.timeout = Some(value);
113 self
114 }
115
116 pub fn http_client(mut self, value: reqwest::Client) -> Self {
117 self.http_client = Some(value);
118 self
119 }
120}
121
122#[derive(Debug, Clone)]
132pub struct ApiError {
133 pub status: u16,
134 pub code: Option<String>,
135 pub body: serde_json::Value,
138 pub message: String,
139 pub method: String,
140 pub url: String,
141}
142
143impl fmt::Display for ApiError {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 write!(f, "{}", self.message)
146 }
147}
148
149impl std::error::Error for ApiError {}
150
151#[derive(Debug)]
156#[non_exhaustive]
157pub enum Error {
158 Api(Box<ApiError>),
164 Http(reqwest::Error),
166 Json(serde_json::Error),
169 MissingPathParam {
171 name: String,
172 method: String,
173 path: String,
174 },
175 Config(String),
178}
179
180impl fmt::Display for Error {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 match self {
183 Error::Api(error) => write!(f, "{error}"),
184 Error::Http(error) => write!(f, "request failed: {error}"),
185 Error::Json(error) => write!(f, "could not encode or decode JSON: {error}"),
186 Error::MissingPathParam { name, method, path } => {
187 write!(f, "missing path parameter `{name}` for {method} {path}")?;
188 if SCOPE_PARAM == Some(name.as_str()) {
189 write!(
190 f,
191 " — pass it on the call, or set `{name}` on the ClientConfig"
192 )?;
193 }
194 Ok(())
195 }
196 Error::Config(message) => write!(f, "client is misconfigured: {message}"),
197 }
198 }
199}
200
201impl std::error::Error for Error {
202 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
203 match self {
204 Error::Api(error) => Some(error.as_ref()),
205 Error::Http(error) => Some(error),
206 Error::Json(error) => Some(error),
207 _ => None,
208 }
209 }
210}
211
212impl From<reqwest::Error> for Error {
213 fn from(error: reqwest::Error) -> Self {
214 Error::Http(error)
215 }
216}
217
218impl From<serde_json::Error> for Error {
219 fn from(error: serde_json::Error) -> Self {
220 Error::Json(error)
221 }
222}
223
224impl Error {
225 pub fn api(&self) -> Option<&ApiError> {
228 match self {
229 Error::Api(error) => Some(error.as_ref()),
230 _ => None,
231 }
232 }
233
234 pub fn status(&self) -> Option<u16> {
236 self.api().map(|error| error.status)
237 }
238
239 pub fn code(&self) -> Option<&str> {
241 self.api().and_then(|error| error.code.as_deref())
242 }
243}
244
245#[derive(Debug, Clone, Serialize, Deserialize)]
254pub struct FileUpload {
255 pub file_name: String,
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub content_type: Option<String>,
258 pub bytes: Vec<u8>,
259}
260
261impl FileUpload {
262 pub fn new(file_name: impl Into<String>, bytes: Vec<u8>) -> Self {
263 Self {
264 file_name: file_name.into(),
265 content_type: None,
266 bytes,
267 }
268 }
269
270 pub fn content_type(mut self, value: impl Into<String>) -> Self {
271 self.content_type = Some(value.into());
272 self
273 }
274}
275
276#[derive(Debug, Clone)]
278pub enum FormValue {
279 Text(String),
280 File(FileUpload),
281}
282
283pub trait IntoMultipart {
286 fn into_multipart(self) -> Vec<(String, FormValue)>;
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Accept {
293 Json,
294 Binary,
295 Empty,
296}
297
298#[derive(Debug)]
303pub struct RequestSpec {
304 pub method: &'static str,
305 pub path: &'static str,
307 pub path_params: Vec<(&'static str, Option<String>)>,
309 pub query: Vec<(String, String)>,
310 pub body: Option<serde_json::Value>,
311 pub form: Option<Vec<(String, FormValue)>>,
312 pub accept: Accept,
313}
314
315impl RequestSpec {
316 pub fn new(method: &'static str, path: &'static str) -> Self {
317 Self {
318 method,
319 path,
320 path_params: Vec::new(),
321 query: Vec::new(),
322 body: None,
323 form: None,
324 accept: Accept::Json,
325 }
326 }
327
328 pub fn accept(mut self, accept: Accept) -> Self {
329 self.accept = accept;
330 self
331 }
332
333 pub fn path_param<T: Serialize>(
337 &mut self,
338 name: &'static str,
339 value: Option<&T>,
340 ) -> Result<(), Error> {
341 let rendered = match value {
342 Some(value) => scalar_to_string(&serde_json::to_value(value)?),
343 None => None,
344 };
345 self.path_params.push((name, rendered));
346 Ok(())
347 }
348
349 pub fn query_param<T: Serialize>(
352 &mut self,
353 name: &str,
354 value: Option<&T>,
355 ) -> Result<(), Error> {
356 let Some(value) = value else { return Ok(()) };
357 match serde_json::to_value(value)? {
358 serde_json::Value::Null => {}
359 serde_json::Value::Array(items) => {
360 for item in items {
361 if let Some(rendered) = scalar_to_string(&item) {
362 self.query.push((name.to_owned(), rendered));
363 }
364 }
365 }
366 other => {
367 if let Some(rendered) = scalar_to_string(&other) {
368 self.query.push((name.to_owned(), rendered));
369 }
370 }
371 }
372 Ok(())
373 }
374
375 pub fn json_body<T: Serialize>(&mut self, value: &T) -> Result<(), Error> {
376 self.body = Some(serde_json::to_value(value)?);
377 Ok(())
378 }
379
380 pub fn multipart_body<T: IntoMultipart>(&mut self, value: T) {
381 self.form = Some(value.into_multipart());
382 }
383}
384
385fn scalar_to_string(value: &serde_json::Value) -> Option<String> {
388 match value {
389 serde_json::Value::Null => None,
390 serde_json::Value::String(text) => Some(text.clone()),
391 serde_json::Value::Bool(flag) => Some(flag.to_string()),
392 serde_json::Value::Number(number) => Some(number.to_string()),
393 other => Some(other.to_string()),
394 }
395}
396
397fn encode_path_segment(value: &str) -> String {
400 let mut out = String::with_capacity(value.len());
401 for byte in value.as_bytes() {
402 match byte {
403 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
404 out.push(*byte as char)
405 }
406 _ => out.push_str(&format!("%{byte:02X}")),
407 }
408 }
409 out
410}
411
412#[derive(Debug, Clone)]
421pub struct Transport {
422 base_url: String,
423 api_key: Option<String>,
424 org_id: Option<String>,
425 headers: HeaderMap,
426 http: reqwest::Client,
427}
428
429impl Transport {
430 pub fn new(config: ClientConfig) -> Result<Self, Error> {
431 let base_url = config
432 .base_url
433 .unwrap_or_else(|| DEFAULT_BASE_URL.to_owned())
434 .trim_end_matches('/')
435 .to_owned();
436 Url::parse(&base_url).map_err(|error| {
439 Error::Config(format!("base URL `{base_url}` does not parse: {error}"))
440 })?;
441
442 let mut headers = HeaderMap::new();
443 for (name, value) in config.headers {
444 let name = HeaderName::try_from(name.as_str())
445 .map_err(|_| Error::Config(format!("`{name}` is not a valid header name")))?;
446 let value = HeaderValue::try_from(value.as_str())
447 .map_err(|_| Error::Config(format!("`{value}` is not a valid header value")))?;
448 headers.insert(name, value);
449 }
450
451 let http = match config.http_client {
452 Some(client) => client,
453 None => {
454 let mut builder = reqwest::Client::builder();
455 if let Some(timeout) = config.timeout {
456 builder = builder.timeout(timeout);
457 }
458 builder.build().map_err(|error| {
459 Error::Config(format!("could not build an HTTP client: {error}"))
460 })?
461 }
462 };
463
464 Ok(Self {
465 base_url,
466 api_key: config.api_key,
467 org_id: config.org_id,
468 headers,
469 http,
470 })
471 }
472
473 pub fn base_url(&self) -> &str {
475 &self.base_url
476 }
477
478 fn resolve_path(&self, spec: &RequestSpec) -> Result<String, Error> {
481 let mut out = String::with_capacity(spec.path.len());
482 let mut rest = spec.path;
483 while let Some(open) = rest.find('{') {
484 let Some(offset) = rest[open..].find('}') else {
485 break;
486 };
487 let close = open + offset;
488 out.push_str(&rest[..open]);
489 let name = &rest[open + 1..close];
490 let value = spec
491 .path_params
492 .iter()
493 .find(|(key, _)| *key == name)
494 .and_then(|(_, value)| value.clone())
495 .or_else(|| {
496 if SCOPE_PARAM == Some(name) {
497 self.org_id.clone()
498 } else {
499 None
500 }
501 })
502 .filter(|value| !value.is_empty())
503 .ok_or_else(|| Error::MissingPathParam {
504 name: name.to_owned(),
505 method: spec.method.to_owned(),
506 path: spec.path.to_owned(),
507 })?;
508 out.push_str(&encode_path_segment(&value));
509 rest = &rest[close + 1..];
510 }
511 out.push_str(rest);
512 Ok(out)
513 }
514
515 fn build_url(&self, spec: &RequestSpec) -> Result<Url, Error> {
516 let path = self.resolve_path(spec)?;
517 let mut url = Url::parse(&format!("{}{}", self.base_url, path))
518 .map_err(|error| Error::Config(format!("could not build a URL: {error}")))?;
519 if !spec.query.is_empty() {
520 let mut pairs = url.query_pairs_mut();
521 for (key, value) in &spec.query {
522 pairs.append_pair(key, value);
523 }
524 }
525 Ok(url)
526 }
527
528 async fn execute(&self, spec: RequestSpec) -> Result<(StatusCode, Vec<u8>), Error> {
529 let url = self.build_url(&spec)?;
530 let method_name = spec.method;
531 let method = Method::from_bytes(method_name.as_bytes())
532 .map_err(|_| Error::Config(format!("`{method_name}` is not an HTTP method")))?;
533
534 let mut request = self.http.request(method, url.clone());
535 request = request.headers(self.headers.clone());
536 request = request.header(
537 reqwest::header::ACCEPT,
538 match spec.accept {
539 Accept::Binary => "application/octet-stream",
540 Accept::Json | Accept::Empty => "application/json",
541 },
542 );
543 if let Some(api_key) = self.api_key.as_deref().filter(|key| !key.is_empty()) {
544 request = request.bearer_auth(api_key);
545 }
546
547 if let Some(fields) = spec.form {
548 let mut form = reqwest::multipart::Form::new();
550 for (name, value) in fields {
551 form = match value {
552 FormValue::Text(text) => form.text(name, text),
553 FormValue::File(file) => {
554 let mut part =
555 reqwest::multipart::Part::bytes(file.bytes).file_name(file.file_name);
556 if let Some(content_type) = file.content_type {
557 part = part.mime_str(&content_type)?;
558 }
559 form.part(name, part)
560 }
561 };
562 }
563 request = request.multipart(form);
564 } else if let Some(body) = spec.body.as_ref() {
565 request = request.json(body);
566 }
567
568 let response = request.send().await?;
569 let status = response.status();
570 let bytes = response.bytes().await?.to_vec();
571 if !status.is_success() {
572 return Err(Error::Api(Box::new(to_api_error(
573 status,
574 &bytes,
575 method_name,
576 url.as_str(),
577 ))));
578 }
579 Ok((status, bytes))
580 }
581
582 pub async fn json<T: DeserializeOwned>(&self, spec: RequestSpec) -> Result<T, Error> {
584 let (status, bytes) = self.execute(spec).await?;
585 if bytes.is_empty() || status == StatusCode::NO_CONTENT {
588 return Ok(serde_json::from_value(serde_json::Value::Null)?);
589 }
590 Ok(serde_json::from_slice(&bytes)?)
591 }
592
593 pub async fn bytes(&self, spec: RequestSpec) -> Result<Vec<u8>, Error> {
595 let (_, bytes) = self.execute(spec).await?;
596 Ok(bytes)
597 }
598
599 pub async fn empty(&self, spec: RequestSpec) -> Result<(), Error> {
601 self.execute(spec).await?;
602 Ok(())
603 }
604}
605
606fn to_api_error(status: StatusCode, bytes: &[u8], method: &str, url: &str) -> ApiError {
607 let body = serde_json::from_slice::<serde_json::Value>(bytes)
608 .unwrap_or_else(|_| serde_json::Value::String(String::from_utf8_lossy(bytes).into_owned()));
609 let detail = body
610 .get("error")
611 .and_then(|value| value.as_str())
612 .or_else(|| body.get("message").and_then(|value| value.as_str()))
613 .map(|text| text.to_owned())
614 .unwrap_or_else(|| status.to_string());
615 ApiError {
616 status: status.as_u16(),
617 code: body
618 .get("code")
619 .and_then(|value| value.as_str())
620 .map(|text| text.to_owned()),
621 message: format!("{method} {url} failed: {detail}"),
622 body,
623 method: method.to_owned(),
624 url: url.to_owned(),
625 }
626}
627
628pub fn form_text<T: Serialize>(value: &T) -> FormValue {
631 let rendered = serde_json::to_value(value)
632 .ok()
633 .and_then(|value| scalar_to_string(&value))
634 .unwrap_or_default();
635 FormValue::Text(rendered)
636}