Skip to main content

infrawrench_sdk/
lib.rs

1/*
2 * infrawrench-sdk v1.121.0 | MIT | Copyright (c) 2026 Infrawrench Services, Inc.
3 * https://github.com/Infrawrench/Infrawrench
4 *
5 * Generated from the Infrawrench API OpenAPI 3.1 spec (API version 1.121.0).
6 *
7 * DO NOT EDIT. Regenerate with:
8 *   pnpm --filter @infrawrench/web generate:sdk
9 *
10 * Internal routes are absent by construction: the generator consumes the same
11 * published spec that /openapi.json serves, which drops every operation
12 * marked x-internal.
13 */
14
15//! Generated Rust client for the Infrawrench API.
16//!
17//! API version: 1.121.0
18//! Default base URL: https://app.infrawrench.com
19//! Operations: 943
20//!
21//! ```no_run
22//! use infrawrench_sdk::{APIV1Client, AccountsListParams, ClientConfig, Error};
23//!
24//! # async fn example() -> Result<(), Error> {
25//! let client = APIV1Client::new(ClientConfig::new().api_key("iw_…").org_id("org"))?;
26//!
27//! match client.accounts().list(AccountsListParams::new()).await {
28//!     Ok(accounts) => println!("{} accounts", accounts.len()),
29//!     Err(error) => eprintln!("{:?} {error}", error.status()),
30//! }
31//! # Ok(())
32//! # }
33//! ```
34
35pub mod client;
36pub mod models;
37pub mod params;
38
39// Re-exported flat so callers can `use infrawrench_sdk::{APIV1Client, Account};`
40// without knowing which module a name happens to live in. The generator's name
41// table guarantees the three modules never declare the same name twice.
42pub 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
54/// Replaced with the first server advertised by the spec.
55const DEFAULT_BASE_URL: &str = "https://app.infrawrench.com";
56
57/// The path parameter the client can carry as configuration rather than take on
58/// every call. Replaced with `None` if the API has no such parameter.
59const SCOPE_PARAM: Option<&str> = Some("orgId");
60
61// ---------------------------------------------------------------------------
62// Configuration
63// ---------------------------------------------------------------------------
64
65/// How to reach the API. Every field has a working default except the API key.
66///
67/// The setters consume and return `self` so a client can be built in one
68/// expression: `ClientConfig::new().api_key(key).org_id(org)`.
69#[derive(Debug, Clone, Default)]
70pub struct ClientConfig {
71    /// Base URL of the deployment. Defaults to the production API.
72    pub base_url: Option<String>,
73    /// API key or WorkOS access token, sent as `Authorization: Bearer <token>`.
74    pub api_key: Option<String>,
75    /// Default organization id, filled into org-scoped paths that omit one.
76    pub org_id: Option<String>,
77    /// Headers merged into every request.
78    pub headers: Vec<(String, String)>,
79    /// Abort requests after this long. No timeout by default.
80    pub timeout: Option<Duration>,
81    /// Supply your own `reqwest::Client` — for proxies, connection pools shared
82    /// with the rest of your process, or a custom TLS configuration.
83    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// ---------------------------------------------------------------------------
123// Errors
124// ---------------------------------------------------------------------------
125
126/// A non-2xx response, with everything needed to branch on it.
127///
128/// Prefer `code` over `message`: it is the machine-readable discriminator the
129/// API sends (`reauthentication_required` on a step-up 403, for instance),
130/// whereas the message is prose that may be reworded at any time.
131#[derive(Debug, Clone)]
132pub struct ApiError {
133    pub status: u16,
134    pub code: Option<String>,
135    /// The response body, parsed as JSON when it was JSON and kept as a string
136    /// otherwise, so an HTML error page from a proxy is not lost.
137    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/// Everything a call can fail with.
152///
153/// Marked `#[non_exhaustive]` so a future variant is not a breaking change for
154/// callers who match on it — add a `_ =>` arm.
155#[derive(Debug)]
156#[non_exhaustive]
157pub enum Error {
158    /// The API answered, and the answer was not 2xx.
159    ///
160    /// Boxed because every call in this crate returns `Result<_, Error>`, and an
161    /// inline `ApiError` would make each of those results as wide as its largest
162    /// failure — 136 bytes of error moved around on the success path too.
163    Api(Box<ApiError>),
164    /// The request never completed: DNS, TLS, connection, timeout.
165    Http(reqwest::Error),
166    /// A request body could not be serialized, or a response body did not match
167    /// the shape the spec promised.
168    Json(serde_json::Error),
169    /// A path parameter had no value from the call or from client config.
170    MissingPathParam {
171        name: String,
172        method: String,
173        path: String,
174    },
175    /// The client itself is misconfigured — a base URL that will not parse, a
176    /// header name that is not a valid header name.
177    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    /// The `ApiError` behind this, when the failure came from the API rather
226    /// than from the network or from serialization.
227    pub fn api(&self) -> Option<&ApiError> {
228        match self {
229            Error::Api(error) => Some(error.as_ref()),
230            _ => None,
231        }
232    }
233
234    /// HTTP status of an API failure.
235    pub fn status(&self) -> Option<u16> {
236        self.api().map(|error| error.status)
237    }
238
239    /// Machine-readable error code of an API failure, when the API sent one.
240    pub fn code(&self) -> Option<&str> {
241        self.api().and_then(|error| error.code.as_deref())
242    }
243}
244
245// ---------------------------------------------------------------------------
246// Request description
247// ---------------------------------------------------------------------------
248
249/// File bytes bound for a `multipart/form-data` field.
250///
251/// `Serialize`/`Deserialize` are derived only so this can sit inside generated
252/// models alongside ordinary fields; the bytes never travel as JSON.
253#[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/// One field of a `multipart/form-data` body.
277#[derive(Debug, Clone)]
278pub enum FormValue {
279    Text(String),
280    File(FileUpload),
281}
282
283/// A model that knows how to become a multipart body. Implemented by the
284/// generator for exactly those schemas the spec sends as `multipart/form-data`.
285pub trait IntoMultipart {
286    fn into_multipart(self) -> Vec<(String, FormValue)>;
287}
288
289/// What the endpoint returns, which decides both the `Accept` header and how
290/// the response body is read back.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum Accept {
293    Json,
294    Binary,
295    Empty,
296}
297
298/// A single HTTP call, as assembled by the generated namespace methods.
299///
300/// Public because the generated code builds one; it is not part of the stable
301/// surface, and `APIV1Client` is what you should reach for.
302#[derive(Debug)]
303pub struct RequestSpec {
304    pub method: &'static str,
305    /// URL template with `{param}` placeholders.
306    pub path: &'static str,
307    /// Resolved path parameters. `None` means "fall back to client config".
308    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    /// Record a path parameter. Anything `Serialize` is accepted so generated
334    /// enums (`PluginId`, `ResourceTypeId`) reach the URL as their wire value
335    /// rather than as their Rust variant name.
336    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    /// Record a query parameter, dropping it when absent or null. Arrays are
350    /// expanded into one repeated key per element.
351    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
385/// Render a JSON scalar the way a URL wants it: strings unquoted, `null`
386/// dropped, anything structural left as compact JSON.
387fn 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
397/// Percent-encode one path segment, escaping everything outside RFC 3986's
398/// unreserved set — `/` included, so an id can never smuggle in a new segment.
399fn 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// ---------------------------------------------------------------------------
413// Transport
414// ---------------------------------------------------------------------------
415
416/// Request plumbing shared by every namespace.
417///
418/// Public because the generated namespace structs borrow one; reach for
419/// `APIV1Client` instead.
420#[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        // Parsed once, here, so a typo in the base URL is a construction error
437        // rather than a surprise on the first call.
438        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    /// The base URL every call is resolved against, with no trailing slash.
474    pub fn base_url(&self) -> &str {
475        &self.base_url
476    }
477
478    /// Fill `{param}` placeholders from the call, falling back to client config
479    /// for the scope parameter.
480    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            // Content-Type is left to reqwest: it owns the multipart boundary.
549            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    /// Send `spec` and decode a JSON response.
583    pub async fn json<T: DeserializeOwned>(&self, spec: RequestSpec) -> Result<T, Error> {
584        let (status, bytes) = self.execute(spec).await?;
585        // A 204 (or an empty body from a route that declares one) is `null` as
586        // far as serde is concerned, which is what `Option<T>` and `()` want.
587        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    /// Send `spec` and return the response body verbatim.
594    pub async fn bytes(&self, spec: RequestSpec) -> Result<Vec<u8>, Error> {
595        let (_, bytes) = self.execute(spec).await?;
596        Ok(bytes)
597    }
598
599    /// Send `spec` and discard the response body.
600    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
628/// Render a value as a `multipart/form-data` text field. Used only by the
629/// generated `IntoMultipart` impls.
630pub 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}