1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! A fully generated, opinionated API client library for Oxide.
//!
//! [![docs.rs](https://docs.rs/oxide-api/badge.svg)](https://docs.rs/oxide-api)
//!
//! ## API Details
//!
//! API for interacting with the Oxide control plane
//!
//!
//!
//! ### Contact
//!
//!
//! | url | email |
//! |----|----|
//! | <https://oxide.computer> | api@oxide.computer |
//!
//!
//!
//! ## Client Details
//!
//! This client is generated from the [Oxide OpenAPI
//! specs](https://github.com/oxidecomputer/omicron) based on API spec version `0.0.1`. This way it will remain
//! up to date as features are added. The documentation for the crate is generated
//! along with the code to make this library easy to use.
//!
//!
//! To install the library, add the following to your `Cargo.toml` file.
//!
//! ```toml
//! [dependencies]
//! oxide-api = "0.1.0-rc.38"
//! ```
//!
//! ## Basic example
//!
//! Typical use will require intializing a `Client`. This requires
//! a user agent string and set of credentials.
//!
//! ```
//! use oxide_api::Client;
//!
//! let oxide = Client::new(String::from("api-key"), String::from("host"));
//! ```
//!
//! Alternatively, the library can search for most of the variables required for
//! the client in the environment:
//!
//! - `OXIDE_TOKEN`
//! - `OXIDE_HOST`
//!
//! And then you can create a client from the environment.
//!
//! ```
//! use oxide_api::Client;
//!
//! let oxide = Client::new_from_env();
//! ```
#![feature(derive_default_enum)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::nonstandard_macro_braces)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::tabs_in_doc_comments)]
#![allow(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

/// Virtual disks are used to store instance-local data which includes the operating system.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod disks;
/// Firewall operation controls the flow of network data into a VPC.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod firewall;
/// TODO operations that will not ship to customers.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod hidden;
/// Images are read-only Virtual Disks that may be used to boot Virtual Machines.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod images;
/// Images are read-only Virtual Disks that may be used to boot Virtual Machines. These images are scoped globally.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod images_global;
/// Virtual machine instances are the basic unit of computation. These operations are used for provisioning, controlling, and destroying instances.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod instances;
/// IP Pools contain external IP addresses that can be assigned to virtual machine Instances.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod ip_pools;
/// Authentication endpoints.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod login;
/// Metrics provide insight into the operation of the Oxide deployment. These include telemetry on hardware and software components that can be used to understand the current state as well as to diagnose issues.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod metrics;
/// Organizations represent a subset of users and projects in an Oxide deployment.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod organizations;
/// System-wide IAM policy.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod policy;
/// Projects are a grouping of associated resources such as instances and disks within an organization for purposes of billing and access control.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod projects;
/// These operations pertain to hardware inventory and management. Racks are the unit of expansion of an Oxide deployment. Racks are in turn composed of sleds, switches, power supplies, and a cabled backplane.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod racks;
/// Roles are a component of Identity and Access Management (IAM) that allow a user or agent account access to additional permissions.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod roles;
/// Routers direct the flow of network traffic into, out of, and within a VPC via routes.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod routers;
/// Routes define router policy.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod routes;
/// Sagas are the abstraction used to represent multi-step operations within the Oxide deployment. These operations can be used to query saga status and report errors.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod sagas;
/// Silos represent a logical partition of users and resources.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod silos;
/// This tag should be moved into hardware.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod sleds;
/// Snapshots of Virtual Disks at a particular point in time.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod snapshots;
/// Public SSH keys for an individual user.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod sshkeys;
/// This tag should be moved into a generic network tag.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod subnets;
/// Internal system information.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod system;
#[cfg(test)]
mod tests;
pub mod types;
/// This tag should be moved into a operations tag.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod updates;
#[doc(hidden)]
pub mod utils;
/// A Virtual Private Cloud (VPC) is an isolated network environment that should probaby be moved into a more generic networking tag.
///
///FROM: http://oxide.computer/docs/#xxx
pub mod vpcs;

use anyhow::{anyhow, Error, Result};

mod progenitor_support {
    use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};

    const PATH_SET: &AsciiSet = &CONTROLS
        .add(b' ')
        .add(b'"')
        .add(b'#')
        .add(b'<')
        .add(b'>')
        .add(b'?')
        .add(b'`')
        .add(b'{')
        .add(b'}');

    #[allow(dead_code)]
    pub(crate) fn encode_path(pc: &str) -> String {
        utf8_percent_encode(pc, PATH_SET).to_string()
    }
}

use std::env;

/// Entrypoint for interacting with the API client.
#[derive(Clone)]
pub struct Client {
    host: String,
    token: String,

    client: reqwest::Client,
}

impl Client {
    /// Create a new Client struct. It takes a type that can convert into
    /// an &str (`String` or `Vec<u8>` for example). As long as the function is
    /// given a valid API key your requests will work.
    pub fn new<T, H>(token: T, host: H) -> Self
    where
        T: ToString,
        H: ToString,
    {
        let client = reqwest::Client::builder().build();
        match client {
            Ok(c) => Client {
                host: host.to_string(),
                token: token.to_string(),

                client: c,
            },
            Err(e) => panic!("creating reqwest client failed: {:?}", e),
        }
    }

    /// Create a new Client struct from environment variables: OXIDE_TOKEN and OXIDE_HOST.
    pub fn new_from_env() -> Self {
        let token = env::var("OXIDE_TOKEN").expect("must set OXIDE_TOKEN");
        let host = env::var("OXIDE_HOST").expect("must set OXIDE_HOST");

        Client::new(token, host)
    }

    async fn url_and_auth(&self, uri: &str) -> Result<(reqwest::Url, Option<String>)> {
        let parsed_url = uri.parse::<reqwest::Url>();

        let auth = format!("Bearer {}", self.token);
        parsed_url.map(|u| (u, Some(auth))).map_err(Error::from)
    }

    pub async fn request_raw(
        &self,
        method: reqwest::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<reqwest::RequestBuilder> {
        let u = if uri.starts_with("https://") || uri.starts_with("http://") {
            uri.to_string()
        } else {
            (self.host.clone() + uri).to_string()
        };
        let (url, auth) = self.url_and_auth(&u).await?;

        let instance = <&Client>::clone(&self);

        let mut req = instance.client.request(method.clone(), url);

        // Set the default headers.
        req = req.header(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );
        req = req.header(
            reqwest::header::CONTENT_TYPE,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        if let Some(auth_str) = auth {
            req = req.header(http::header::AUTHORIZATION, &*auth_str);
        }

        if let Some(body) = body {
            log::debug!(
                "body: {:?}",
                String::from_utf8(body.as_bytes().unwrap().to_vec()).unwrap()
            );
            req = req.body(body);
        }
        log::debug!("request: {:?}", &req);
        Ok(req)
    }

    pub async fn response_raw(
        &self,
        method: reqwest::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<reqwest::Response> {
        let req = self.request_raw(method, uri, body).await?;
        Ok(req.send().await?)
    }

    async fn request<Out>(
        &self,
        method: reqwest::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<Out>
    where
        Out: serde::de::DeserializeOwned + 'static + Send,
    {
        let response = self.response_raw(method, uri, body).await?;

        let status = response.status();

        let response_body = response.bytes().await?;

        if status.is_success() {
            log::debug!(
                "response payload {}",
                String::from_utf8_lossy(&response_body)
            );
            let parsed_response = if status == http::StatusCode::NO_CONTENT
                || std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
            {
                serde_json::from_str("null")
            } else {
                serde_json::from_slice::<Out>(&response_body)
            };
            parsed_response.map_err(Error::from)
        } else {
            let error: anyhow::Error = if response_body.is_empty() {
                anyhow!("code: {}, empty response", status)
            } else {
                // Parse the error as the error type.
                match serde_json::from_slice::<crate::types::ErrorResponse>(&response_body) {
                    Ok(resp) => {
                        let e: crate::types::Error = resp.into();
                        e.into()
                    }
                    Err(_) => {
                        anyhow!(
                            "code: {}, error: {:?}",
                            status,
                            String::from_utf8_lossy(&response_body),
                        )
                    }
                }
            };

            Err(error)
        }
    }

    async fn request_entity<D>(
        &self,
        method: http::Method,
        uri: &str,
        body: Option<reqwest::Body>,
    ) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        let r = self.request(method, uri, body).await?;
        Ok(r)
    }

    async fn get<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(http::Method::GET, &(self.host.to_string() + uri), message)
            .await
    }

    async fn post<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(http::Method::POST, &(self.host.to_string() + uri), message)
            .await
    }

    #[allow(dead_code)]
    async fn patch<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(http::Method::PATCH, &(self.host.to_string() + uri), message)
            .await
    }

    async fn put<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(http::Method::PUT, &(self.host.to_string() + uri), message)
            .await
    }

    async fn delete<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
    where
        D: serde::de::DeserializeOwned + 'static + Send,
    {
        self.request_entity(
            http::Method::DELETE,
            &(self.host.to_string() + uri),
            message,
        )
        .await
    }

    /// Virtual disks are used to store instance-local data which includes the operating system.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn disks(&self) -> disks::Disks {
        disks::Disks::new(self.clone())
    }

    /// Firewall operation controls the flow of network data into a VPC.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn firewall(&self) -> firewall::Firewall {
        firewall::Firewall::new(self.clone())
    }

    /// TODO operations that will not ship to customers.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn hidden(&self) -> hidden::Hidden {
        hidden::Hidden::new(self.clone())
    }

    /// Images are read-only Virtual Disks that may be used to boot Virtual Machines.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn images(&self) -> images::Images {
        images::Images::new(self.clone())
    }

    /// Images are read-only Virtual Disks that may be used to boot Virtual Machines. These images are scoped globally.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn images_global(&self) -> images_global::ImagesGlobal {
        images_global::ImagesGlobal::new(self.clone())
    }

    /// Virtual machine instances are the basic unit of computation. These operations are used for provisioning, controlling, and destroying instances.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn instances(&self) -> instances::Instances {
        instances::Instances::new(self.clone())
    }

    /// IP Pools contain external IP addresses that can be assigned to virtual machine Instances.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn ip_pools(&self) -> ip_pools::IpPools {
        ip_pools::IpPools::new(self.clone())
    }

    /// Authentication endpoints.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn login(&self) -> login::Login {
        login::Login::new(self.clone())
    }

    /// Metrics provide insight into the operation of the Oxide deployment. These include telemetry on hardware and software components that can be used to understand the current state as well as to diagnose issues.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn metrics(&self) -> metrics::Metrics {
        metrics::Metrics::new(self.clone())
    }

    /// Organizations represent a subset of users and projects in an Oxide deployment.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn organizations(&self) -> organizations::Organizations {
        organizations::Organizations::new(self.clone())
    }

    /// System-wide IAM policy.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn policy(&self) -> policy::Policy {
        policy::Policy::new(self.clone())
    }

    /// Projects are a grouping of associated resources such as instances and disks within an organization for purposes of billing and access control.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn projects(&self) -> projects::Projects {
        projects::Projects::new(self.clone())
    }

    /// These operations pertain to hardware inventory and management. Racks are the unit of expansion of an Oxide deployment. Racks are in turn composed of sleds, switches, power supplies, and a cabled backplane.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn racks(&self) -> racks::Racks {
        racks::Racks::new(self.clone())
    }

    /// Roles are a component of Identity and Access Management (IAM) that allow a user or agent account access to additional permissions.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn roles(&self) -> roles::Roles {
        roles::Roles::new(self.clone())
    }

    /// Routers direct the flow of network traffic into, out of, and within a VPC via routes.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn routers(&self) -> routers::Routers {
        routers::Routers::new(self.clone())
    }

    /// Routes define router policy.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn routes(&self) -> routes::Routes {
        routes::Routes::new(self.clone())
    }

    /// Sagas are the abstraction used to represent multi-step operations within the Oxide deployment. These operations can be used to query saga status and report errors.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn sagas(&self) -> sagas::Sagas {
        sagas::Sagas::new(self.clone())
    }

    /// Silos represent a logical partition of users and resources.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn silos(&self) -> silos::Silos {
        silos::Silos::new(self.clone())
    }

    /// This tag should be moved into hardware.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn sleds(&self) -> sleds::Sleds {
        sleds::Sleds::new(self.clone())
    }

    /// Snapshots of Virtual Disks at a particular point in time.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn snapshots(&self) -> snapshots::Snapshots {
        snapshots::Snapshots::new(self.clone())
    }

    /// Public SSH keys for an individual user.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn sshkeys(&self) -> sshkeys::Sshkeys {
        sshkeys::Sshkeys::new(self.clone())
    }

    /// This tag should be moved into a generic network tag.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn subnets(&self) -> subnets::Subnets {
        subnets::Subnets::new(self.clone())
    }

    /// Internal system information.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn system(&self) -> system::System {
        system::System::new(self.clone())
    }

    /// This tag should be moved into a operations tag.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn updates(&self) -> updates::Updates {
        updates::Updates::new(self.clone())
    }

    /// A Virtual Private Cloud (VPC) is an isolated network environment that should probaby be moved into a more generic networking tag.
    ///
    ///FROM: http://oxide.computer/docs/#xxx
    pub fn vpcs(&self) -> vpcs::Vpcs {
        vpcs::Vpcs::new(self.clone())
    }
}