ubi-rs 0.1.6

A Rust cli and library for ubicloud API
Documentation
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use crate::client::{HTTPClient, encode_param};
use crate::errors::UbiClientError;
use crate::{make_json_request, make_request};
use bytes::Bytes;
use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;

pub struct KCClient {
    http_client: Arc<HTTPClient>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct QueryParams {
    start_after: Option<String>,
    page_size: Option<u32>,
    order_column: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct ReqClusterCreate {
    pub version: String,
    pub worker_size: String,
    pub cp_nodes: u32,
    pub worker_nodes: u32,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct ResponseListKubernetesClusters {
    pub count: u32,
    pub items: Vec<ClusterItem>,
}

#[derive(Debug, Serialize, Deserialize, Default)]

pub struct ClusterItem {
    pub cp_node_count: u32,
    pub cp_vms: Option<Vec<VirtualMachine>>,
    pub display_state: String,
    pub id: String,
    pub location: String,
    pub name: String,
    pub node_size: String,
    pub nodepools: Option<Vec<NodePool>>,
    pub services_load_balancer_url: Option<String>,
    pub version: String,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct NodePool {
    pub kubernetes_cluster_id: String,
    pub id: String,
    pub name: String,
    pub node_count: u32,
    pub node_size: String,
    pub vms: Vec<VirtualMachine>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct VirtualMachine {
    pub id: String,
    pub ip4: String,
    pub ip4_enabled: bool,
    pub ip6: String,
    pub location: String,
    pub name: String,
    pub size: String,
    pub state: String,
    pub storage_size_gib: u32,
    pub unix_user: String,
}

impl KCClient {
    pub fn new(http_client: Arc<HTTPClient>) -> Self {
        KCClient { http_client }
    }

    /// List KubernetesClusters in a specific location of a project
    /// https://api.ubicloud.com/project/{project_id}/kubernetes-cluster
    ///
    /// project_id
    /// string
    /// required
    pub async fn list_kubernetes_clusters(
        &self,
        project_id: &str,
        query_params: Option<QueryParams>,
    ) -> Result<ResponseListKubernetesClusters, UbiClientError> {
        let url = &format!("project/{}/kubernetes-cluster", project_id);

        let body_empty = serde_json::json!({});
        make_json_request!(
            self,
            reqwest::Method::GET,
            url,
            body_empty,
            query_params,
            ResponseListKubernetesClusters
        )
    }

    /// Create a new KubernetesCluster in a specific location of a project
    /// https://api.ubicloud.com/project/{project_id}/location/{location}/kubernetes-cluster/{kubernetes_cluster_reference}
    ///
    /// # Arguments:
    /// * `project_id` - The ID of the project.
    /// * `location` - The location/region of the Kubernetes cluster.
    /// * `kubernetes_cluster_reference` - The ID or name of the Kubernetes cluster.
    /// * `payload` - The request body containing the details of the Kubernetes cluster to create.
    ///
    /// This function sends a POST request to create a new Kubernetes cluster with the specified parameters.
    pub async fn create_kubernetes_cluster(
        &self,
        project_id: &str,
        location: &str,
        kubernetes_cluster_reference: &str,
        payload: &ReqClusterCreate,
    ) -> Result<ClusterItem, UbiClientError> {
        let url = &format!(
            "project/{}/location/{}/kubernetes-cluster/{}",
            project_id, location, kubernetes_cluster_reference
        );

        let query_params = [(); 0]; // Option<QueryParams>
        make_json_request!(
            self,
            reqwest::Method::POST,
            url,
            payload,
            query_params,
            ClusterItem
        )
    }

    /// Delete a specific KubernetesCluster
    /// https://api.ubicloud.com/project/{project_id}/location/{location}/kubernetes-cluster/{kubernetes_cluster_reference}
    ///
    /// # Arguments:
    /// * `project_id` - The ID of the project.
    /// * `location` - The location/region of the Kubernetes cluster.
    /// * `kubernetes_cluster_reference` - The ID or name of the Kubernetes cluster.
    ///
    /// This function sends a DELETE request to remove the specified Kubernetes cluster.
    ///
    pub async fn delete_kubernetes_cluster(
        &self,
        project_id: &str,
        location: &str,
        kubernetes_cluster_reference: &str,
    ) -> Result<(), UbiClientError> {
        let url = &format!(
            "project/{}/location/{}/kubernetes-cluster/{}",
            project_id, location, kubernetes_cluster_reference
        );

        let _response = make_request!(self, reqwest::Method::DELETE, url)?;
        Ok(())
    }

    /// Download the kubeconfig file for a specific Kubernetes cluster
    /// https://api.ubicloud.com/project/{project_id}/location/{location}/kubernetes-cluster/{kubernetes_cluster_reference}/kubeconfig
    /// ///
    /// # Arguments:
    /// * `project_id` - The ID of the project.
    /// * `location` - The location/region of the Kubernetes cluster.
    /// * `kubernetes_cluster_reference` - The ID or name of the Kubernetes cluster.
    pub async fn download_kc_config(
        &self,
        project_id: &str,
        location: &str,
        kubernetes_cluster_reference: &str,
    ) -> Result<Bytes, UbiClientError> {
        let url = &format!(
            "project/{}/location/{}/kubernetes-cluster/{}/kubeconfig",
            encode_param(project_id),
            location,
            kubernetes_cluster_reference
        );

        let response: reqwest::Response = make_request!(self, reqwest::Method::GET, &url)?;
        Ok(response.bytes().await?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::HTTPClient;
    use mockito::{Matcher, Server};
    use std::sync::Arc;

    fn create_test_client(server_url: &str) -> KCClient {
        let reqwest_client = reqwest::Client::new();
        let http_client = HTTPClient::new(server_url, reqwest_client, "v1");
        KCClient::new(Arc::new(http_client))
    }

    #[tokio::test]
    async fn test_list_kubernetes_clusters_success() {
        let mut server = Server::new_async().await;
        let mock_response = ResponseListKubernetesClusters {
            count: 2,
            items: vec![
                ClusterItem {
                    cp_node_count: 3,
                    cp_vms: None,
                    display_state: "running".to_string(),
                    id: "cluster-1".to_string(),
                    location: "us-east".to_string(),
                    name: "test-cluster-1".to_string(),
                    node_size: "standard-2".to_string(),
                    nodepools: None,
                    services_load_balancer_url: Some("http://lb.example.com".to_string()),
                    version: "1.28.0".to_string(),
                },
                ClusterItem {
                    cp_node_count: 1,
                    cp_vms: None,
                    display_state: "creating".to_string(),
                    id: "cluster-2".to_string(),
                    location: "us-west".to_string(),
                    name: "test-cluster-2".to_string(),
                    node_size: "standard-1".to_string(),
                    nodepools: None,
                    services_load_balancer_url: None,
                    version: "1.27.0".to_string(),
                },
            ],
        };

        let mock = server
            .mock("GET", "/v1/project/test-project/kubernetes-cluster")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::to_string(&mock_response).unwrap())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .list_kubernetes_clusters("test-project", None)
            .await
            .unwrap();

        mock.assert_async().await;
        assert_eq!(result.count, 2);
        assert_eq!(result.items.len(), 2);
        assert_eq!(result.items[0].name, "test-cluster-1");
        assert_eq!(result.items[1].name, "test-cluster-2");
    }

    #[tokio::test]
    async fn test_list_kubernetes_clusters_with_query_params() {
        let mut server = Server::new_async().await;
        let mock_response = ResponseListKubernetesClusters {
            count: 1,
            items: vec![ClusterItem {
                cp_node_count: 3,
                cp_vms: None,
                display_state: "running".to_string(),
                id: "cluster-1".to_string(),
                location: "us-east".to_string(),
                name: "test-cluster-1".to_string(),
                node_size: "standard-2".to_string(),
                nodepools: None,
                services_load_balancer_url: Some("http://lb.example.com".to_string()),
                version: "1.28.0".to_string(),
            }],
        };

        let mock = server
            .mock("GET", "/v1/project/test-project/kubernetes-cluster")
            .match_query(Matcher::AllOf(vec![
                Matcher::UrlEncoded("page_size".to_string(), "10".to_string()),
                Matcher::UrlEncoded("order_column".to_string(), "name".to_string()),
            ]))
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::to_string(&mock_response).unwrap())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let query_params = QueryParams {
            start_after: None,
            page_size: Some(10),
            order_column: Some("name".to_string()),
        };

        let result = client
            .list_kubernetes_clusters("test-project", Some(query_params))
            .await
            .unwrap();

        mock.assert_async().await;
        assert_eq!(result.count, 1);
        assert_eq!(result.items.len(), 1);
    }

    #[tokio::test]
    async fn test_create_kubernetes_cluster_success() {
        let mut server = Server::new_async().await;
        let mock_response = ClusterItem {
            cp_node_count: 3,
            cp_vms: None,
            display_state: "creating".to_string(),
            id: "new-cluster".to_string(),
            location: "us-east".to_string(),
            name: "new-test-cluster".to_string(),
            node_size: "standard-2".to_string(),
            nodepools: None,
            services_load_balancer_url: None,
            version: "1.28.0".to_string(),
        };

        let mock = server
            .mock(
                "POST",
                "/v1/project/test-project/location/us-east/kubernetes-cluster/new-test-cluster",
            )
            .with_status(201)
            .with_header("content-type", "application/json")
            .with_body(serde_json::to_string(&mock_response).unwrap())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let payload = ReqClusterCreate {
            version: "1.28.0".to_string(),
            worker_size: "standard-2".to_string(),
            cp_nodes: 3,
            worker_nodes: 2,
        };

        let result = client
            .create_kubernetes_cluster("test-project", "us-east", "new-test-cluster", &payload)
            .await
            .unwrap();

        mock.assert_async().await;
        assert_eq!(result.name, "new-test-cluster");
        assert_eq!(result.location, "us-east");
        assert_eq!(result.version, "1.28.0");
        assert_eq!(result.display_state, "creating");
    }

    #[tokio::test]
    async fn test_delete_kubernetes_cluster_success() {
        let mut server = Server::new_async().await;

        let mock = server
            .mock(
                "DELETE",
                "/v1/project/test-project/location/us-east/kubernetes-cluster/test-cluster",
            )
            .with_status(204)
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .delete_kubernetes_cluster("test-project", "us-east", "test-cluster")
            .await;

        mock.assert_async().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_download_kc_config_success() {
        let mut server = Server::new_async().await;
        let kubeconfig_content = r#"apiVersion: v1
kind: Config
clusters:
- cluster:
    server: https://test-cluster.example.com
  name: test-cluster
contexts:
- context:
    cluster: test-cluster
    user: test-user
  name: test-context
current-context: test-context
users:
- name: test-user
  user:
    token: test-token"#;

        let mock = server
            .mock("GET", "/v1/project/test-project/location/us-east/kubernetes-cluster/test-cluster/kubeconfig")
            .with_status(200)
            .with_header("content-type", "application/yaml")
            .with_body(kubeconfig_content)
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .download_kc_config("test-project", "us-east", "test-cluster")
            .await
            .unwrap();

        mock.assert_async().await;
        let downloaded_content = String::from_utf8(result.to_vec()).unwrap();
        assert!(downloaded_content.contains("apiVersion: v1"));
        assert!(downloaded_content.contains("kind: Config"));
        assert!(downloaded_content.contains("test-cluster"));
    }

    #[tokio::test]
    async fn test_list_kubernetes_clusters_api_error() {
        let mut server = Server::new_async().await;
        let error_response = serde_json::json!({
            "error": {
                "type": "NotFound",
                "message": "Project not found",
                "details": "The specified project does not exist"
            }
        });

        let mock = server
            .mock("GET", "/v1/project/nonexistent-project/kubernetes-cluster")
            .with_status(404)
            .with_header("content-type", "application/json")
            .with_body(error_response.to_string())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .list_kubernetes_clusters("nonexistent-project", None)
            .await;

        mock.assert_async().await;
        assert!(result.is_err());

        if let Err(UbiClientError::APIResponseError {
            etype,
            message,
            details,
        }) = result
        {
            assert_eq!(etype, "NotFound");
            assert_eq!(message, "Project not found");
            assert_eq!(
                details,
                Some("The specified project does not exist".to_string())
            );
        } else {
            panic!("Expected APIResponseError");
        }
    }

    #[tokio::test]
    async fn test_create_kubernetes_cluster_validation_error() {
        let mut server = Server::new_async().await;
        let error_response = serde_json::json!({
            "error": {
                "type": "ValidationError",
                "message": "Invalid cluster configuration",
                "details": "Worker nodes count must be greater than 0"
            }
        });

        let mock = server
            .mock(
                "POST",
                "/v1/project/test-project/location/us-east/kubernetes-cluster/invalid-cluster",
            )
            .with_status(400)
            .with_header("content-type", "application/json")
            .with_body(error_response.to_string())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let payload = ReqClusterCreate {
            version: "1.28.0".to_string(),
            worker_size: "standard-2".to_string(),
            cp_nodes: 3,
            worker_nodes: 0, // Invalid value
        };

        let result = client
            .create_kubernetes_cluster("test-project", "us-east", "invalid-cluster", &payload)
            .await;

        mock.assert_async().await;
        assert!(result.is_err());

        if let Err(UbiClientError::APIResponseError { etype, message, .. }) = result {
            assert_eq!(etype, "ValidationError");
            assert_eq!(message, "Invalid cluster configuration");
        } else {
            panic!("Expected APIResponseError");
        }
    }

    #[tokio::test]
    async fn test_delete_kubernetes_cluster_not_found() {
        let mut server = Server::new_async().await;
        let error_response = serde_json::json!({
            "error": {
                "type": "NotFound",
                "message": "Kubernetes cluster not found",
                "details": null
            }
        });

        let mock = server
            .mock(
                "DELETE",
                "/v1/project/test-project/location/us-east/kubernetes-cluster/nonexistent-cluster",
            )
            .with_status(404)
            .with_header("content-type", "application/json")
            .with_body(error_response.to_string())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .delete_kubernetes_cluster("test-project", "us-east", "nonexistent-cluster")
            .await;

        mock.assert_async().await;
        assert!(result.is_err());

        if let Err(UbiClientError::APIResponseError { etype, message, .. }) = result {
            assert_eq!(etype, "NotFound");
            assert_eq!(message, "Kubernetes cluster not found");
        } else {
            panic!("Expected APIResponseError");
        }
    }

    #[tokio::test]
    async fn test_encode_param_in_urls() {
        let mut server = Server::new_async().await;
        let mock_response = ResponseListKubernetesClusters {
            count: 0,
            items: vec![],
        };

        // Test with normal project ID for list_kubernetes_clusters which doesn't use encode_param
        let project_id = "test-project";

        let mock = server
            .mock(
                "GET",
                format!("/v1/project/{}/kubernetes-cluster", project_id).as_str(),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::to_string(&mock_response).unwrap())
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .list_kubernetes_clusters(project_id, None)
            .await
            .unwrap();

        mock.assert_async().await;
        assert_eq!(result.count, 0);
    }

    #[tokio::test]
    async fn test_download_kc_config_with_encoded_params() {
        let mut server = Server::new_async().await;
        let kubeconfig_content = "test-config";

        // Test with a project ID that contains special characters that need encoding
        let project_id_with_special_chars = "test-project@domain.com";

        let mock = server
            .mock("GET", "/v1/project/test%2Dproject%40domain%2Ecom/location/us-east/kubernetes-cluster/test-cluster/kubeconfig")
            .with_status(200)
            .with_header("content-type", "application/yaml")
            .with_body(kubeconfig_content)
            .create_async()
            .await;

        let client = create_test_client(&server.url());
        let result = client
            .download_kc_config(project_id_with_special_chars, "us-east", "test-cluster")
            .await
            .unwrap();

        mock.assert_async().await;
        let downloaded_content = String::from_utf8(result.to_vec()).unwrap();
        assert_eq!(downloaded_content, "test-config");
    }

    #[test]
    fn test_query_params_default() {
        let params = QueryParams::default();
        assert!(params.start_after.is_none());
        assert!(params.page_size.is_none());
        assert!(params.order_column.is_none());
    }

    #[test]
    fn test_req_cluster_create_default() {
        let req = ReqClusterCreate::default();
        assert_eq!(req.version, "");
        assert_eq!(req.worker_size, "");
        assert_eq!(req.cp_nodes, 0);
        assert_eq!(req.worker_nodes, 0);
    }

    #[test]
    fn test_cluster_item_serialization() {
        let cluster = ClusterItem {
            cp_node_count: 3,
            cp_vms: None,
            display_state: "running".to_string(),
            id: "test-cluster".to_string(),
            location: "us-east".to_string(),
            name: "My Test Cluster".to_string(),
            node_size: "standard-2".to_string(),
            nodepools: None,
            services_load_balancer_url: Some("http://lb.example.com".to_string()),
            version: "1.28.0".to_string(),
        };

        let serialized = serde_json::to_string(&cluster).unwrap();
        let deserialized: ClusterItem = serde_json::from_str(&serialized).unwrap();

        assert_eq!(cluster.id, deserialized.id);
        assert_eq!(cluster.name, deserialized.name);
        assert_eq!(cluster.location, deserialized.location);
        assert_eq!(cluster.version, deserialized.version);
    }
}