datadog_api_client/datadogV2/api/
api_org_connections.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use flate2::{
6    write::{GzEncoder, ZlibEncoder},
7    Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13/// CreateOrgConnectionsError is a struct for typed errors of method [`OrgConnectionsAPI::create_org_connections`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum CreateOrgConnectionsError {
17    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// DeleteOrgConnectionsError is a struct for typed errors of method [`OrgConnectionsAPI::delete_org_connections`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum DeleteOrgConnectionsError {
25    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// ListOrgConnectionsError is a struct for typed errors of method [`OrgConnectionsAPI::list_org_connections`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum ListOrgConnectionsError {
33    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// UpdateOrgConnectionsError is a struct for typed errors of method [`OrgConnectionsAPI::update_org_connections`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum UpdateOrgConnectionsError {
41    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// Manage connections between organizations. Org connections allow for controlled sharing of data between different Datadog organizations. See the [Cross-Organization Visibiltiy](<https://docs.datadoghq.com/account_management/org_settings/cross_org_visibility/>) page for more information.
46#[derive(Debug, Clone)]
47pub struct OrgConnectionsAPI {
48    config: datadog::Configuration,
49    client: reqwest_middleware::ClientWithMiddleware,
50}
51
52impl Default for OrgConnectionsAPI {
53    fn default() -> Self {
54        Self::with_config(datadog::Configuration::default())
55    }
56}
57
58impl OrgConnectionsAPI {
59    pub fn new() -> Self {
60        Self::default()
61    }
62    pub fn with_config(config: datadog::Configuration) -> Self {
63        let mut reqwest_client_builder = reqwest::Client::builder();
64
65        if let Some(proxy_url) = &config.proxy_url {
66            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
67            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
68        }
69
70        let mut middleware_client_builder =
71            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
72
73        if config.enable_retry {
74            struct RetryableStatus;
75            impl reqwest_retry::RetryableStrategy for RetryableStatus {
76                fn handle(
77                    &self,
78                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
79                ) -> Option<reqwest_retry::Retryable> {
80                    match res {
81                        Ok(success) => reqwest_retry::default_on_request_success(success),
82                        Err(_) => None,
83                    }
84                }
85            }
86            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
87                .build_with_max_retries(config.max_retries);
88
89            let retry_middleware =
90                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
91                    backoff_policy,
92                    RetryableStatus,
93                );
94
95            middleware_client_builder = middleware_client_builder.with(retry_middleware);
96        }
97
98        let client = middleware_client_builder.build();
99
100        Self { config, client }
101    }
102
103    pub fn with_client_and_config(
104        config: datadog::Configuration,
105        client: reqwest_middleware::ClientWithMiddleware,
106    ) -> Self {
107        Self { config, client }
108    }
109
110    /// Create a new org connection between the current org and a target org.
111    pub async fn create_org_connections(
112        &self,
113        body: crate::datadogV2::model::OrgConnectionCreateRequest,
114    ) -> Result<
115        crate::datadogV2::model::OrgConnectionResponse,
116        datadog::Error<CreateOrgConnectionsError>,
117    > {
118        match self.create_org_connections_with_http_info(body).await {
119            Ok(response_content) => {
120                if let Some(e) = response_content.entity {
121                    Ok(e)
122                } else {
123                    Err(datadog::Error::Serde(serde::de::Error::custom(
124                        "response content was None",
125                    )))
126                }
127            }
128            Err(err) => Err(err),
129        }
130    }
131
132    /// Create a new org connection between the current org and a target org.
133    pub async fn create_org_connections_with_http_info(
134        &self,
135        body: crate::datadogV2::model::OrgConnectionCreateRequest,
136    ) -> Result<
137        datadog::ResponseContent<crate::datadogV2::model::OrgConnectionResponse>,
138        datadog::Error<CreateOrgConnectionsError>,
139    > {
140        let local_configuration = &self.config;
141        let operation_id = "v2.create_org_connections";
142
143        let local_client = &self.client;
144
145        let local_uri_str = format!(
146            "{}/api/v2/org_connections",
147            local_configuration.get_operation_host(operation_id)
148        );
149        let mut local_req_builder =
150            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
151
152        // build headers
153        let mut headers = HeaderMap::new();
154        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
155        headers.insert("Accept", HeaderValue::from_static("application/json"));
156
157        // build user agent
158        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
159            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
160            Err(e) => {
161                log::warn!("Failed to parse user agent header: {e}, falling back to default");
162                headers.insert(
163                    reqwest::header::USER_AGENT,
164                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
165                )
166            }
167        };
168
169        // build auth
170        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
171            headers.insert(
172                "DD-API-KEY",
173                HeaderValue::from_str(local_key.key.as_str())
174                    .expect("failed to parse DD-API-KEY header"),
175            );
176        };
177        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
178            headers.insert(
179                "DD-APPLICATION-KEY",
180                HeaderValue::from_str(local_key.key.as_str())
181                    .expect("failed to parse DD-APPLICATION-KEY header"),
182            );
183        };
184
185        // build body parameters
186        let output = Vec::new();
187        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
188        if body.serialize(&mut ser).is_ok() {
189            if let Some(content_encoding) = headers.get("Content-Encoding") {
190                match content_encoding.to_str().unwrap_or_default() {
191                    "gzip" => {
192                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
193                        let _ = enc.write_all(ser.into_inner().as_slice());
194                        match enc.finish() {
195                            Ok(buf) => {
196                                local_req_builder = local_req_builder.body(buf);
197                            }
198                            Err(e) => return Err(datadog::Error::Io(e)),
199                        }
200                    }
201                    "deflate" => {
202                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
203                        let _ = enc.write_all(ser.into_inner().as_slice());
204                        match enc.finish() {
205                            Ok(buf) => {
206                                local_req_builder = local_req_builder.body(buf);
207                            }
208                            Err(e) => return Err(datadog::Error::Io(e)),
209                        }
210                    }
211                    "zstd1" => {
212                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
213                        let _ = enc.write_all(ser.into_inner().as_slice());
214                        match enc.finish() {
215                            Ok(buf) => {
216                                local_req_builder = local_req_builder.body(buf);
217                            }
218                            Err(e) => return Err(datadog::Error::Io(e)),
219                        }
220                    }
221                    _ => {
222                        local_req_builder = local_req_builder.body(ser.into_inner());
223                    }
224                }
225            } else {
226                local_req_builder = local_req_builder.body(ser.into_inner());
227            }
228        }
229
230        local_req_builder = local_req_builder.headers(headers);
231        let local_req = local_req_builder.build()?;
232        log::debug!("request content: {:?}", local_req.body());
233        let local_resp = local_client.execute(local_req).await?;
234
235        let local_status = local_resp.status();
236        let local_content = local_resp.text().await?;
237        log::debug!("response content: {}", local_content);
238
239        if !local_status.is_client_error() && !local_status.is_server_error() {
240            match serde_json::from_str::<crate::datadogV2::model::OrgConnectionResponse>(
241                &local_content,
242            ) {
243                Ok(e) => {
244                    return Ok(datadog::ResponseContent {
245                        status: local_status,
246                        content: local_content,
247                        entity: Some(e),
248                    })
249                }
250                Err(e) => return Err(datadog::Error::Serde(e)),
251            };
252        } else {
253            let local_entity: Option<CreateOrgConnectionsError> =
254                serde_json::from_str(&local_content).ok();
255            let local_error = datadog::ResponseContent {
256                status: local_status,
257                content: local_content,
258                entity: local_entity,
259            };
260            Err(datadog::Error::ResponseError(local_error))
261        }
262    }
263
264    /// Delete an existing org connection.
265    pub async fn delete_org_connections(
266        &self,
267        connection_id: uuid::Uuid,
268    ) -> Result<(), datadog::Error<DeleteOrgConnectionsError>> {
269        match self
270            .delete_org_connections_with_http_info(connection_id)
271            .await
272        {
273            Ok(_) => Ok(()),
274            Err(err) => Err(err),
275        }
276    }
277
278    /// Delete an existing org connection.
279    pub async fn delete_org_connections_with_http_info(
280        &self,
281        connection_id: uuid::Uuid,
282    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteOrgConnectionsError>> {
283        let local_configuration = &self.config;
284        let operation_id = "v2.delete_org_connections";
285
286        let local_client = &self.client;
287
288        let local_uri_str = format!(
289            "{}/api/v2/org_connections/{connection_id}",
290            local_configuration.get_operation_host(operation_id),
291            connection_id = datadog::urlencode(connection_id.to_string())
292        );
293        let mut local_req_builder =
294            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
295
296        // build headers
297        let mut headers = HeaderMap::new();
298        headers.insert("Accept", HeaderValue::from_static("*/*"));
299
300        // build user agent
301        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
302            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
303            Err(e) => {
304                log::warn!("Failed to parse user agent header: {e}, falling back to default");
305                headers.insert(
306                    reqwest::header::USER_AGENT,
307                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
308                )
309            }
310        };
311
312        // build auth
313        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
314            headers.insert(
315                "DD-API-KEY",
316                HeaderValue::from_str(local_key.key.as_str())
317                    .expect("failed to parse DD-API-KEY header"),
318            );
319        };
320        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
321            headers.insert(
322                "DD-APPLICATION-KEY",
323                HeaderValue::from_str(local_key.key.as_str())
324                    .expect("failed to parse DD-APPLICATION-KEY header"),
325            );
326        };
327
328        local_req_builder = local_req_builder.headers(headers);
329        let local_req = local_req_builder.build()?;
330        log::debug!("request content: {:?}", local_req.body());
331        let local_resp = local_client.execute(local_req).await?;
332
333        let local_status = local_resp.status();
334        let local_content = local_resp.text().await?;
335        log::debug!("response content: {}", local_content);
336
337        if !local_status.is_client_error() && !local_status.is_server_error() {
338            Ok(datadog::ResponseContent {
339                status: local_status,
340                content: local_content,
341                entity: None,
342            })
343        } else {
344            let local_entity: Option<DeleteOrgConnectionsError> =
345                serde_json::from_str(&local_content).ok();
346            let local_error = datadog::ResponseContent {
347                status: local_status,
348                content: local_content,
349                entity: local_entity,
350            };
351            Err(datadog::Error::ResponseError(local_error))
352        }
353    }
354
355    /// Returns a list of org connections.
356    pub async fn list_org_connections(
357        &self,
358    ) -> Result<
359        crate::datadogV2::model::OrgConnectionListResponse,
360        datadog::Error<ListOrgConnectionsError>,
361    > {
362        match self.list_org_connections_with_http_info().await {
363            Ok(response_content) => {
364                if let Some(e) = response_content.entity {
365                    Ok(e)
366                } else {
367                    Err(datadog::Error::Serde(serde::de::Error::custom(
368                        "response content was None",
369                    )))
370                }
371            }
372            Err(err) => Err(err),
373        }
374    }
375
376    /// Returns a list of org connections.
377    pub async fn list_org_connections_with_http_info(
378        &self,
379    ) -> Result<
380        datadog::ResponseContent<crate::datadogV2::model::OrgConnectionListResponse>,
381        datadog::Error<ListOrgConnectionsError>,
382    > {
383        let local_configuration = &self.config;
384        let operation_id = "v2.list_org_connections";
385
386        let local_client = &self.client;
387
388        let local_uri_str = format!(
389            "{}/api/v2/org_connections",
390            local_configuration.get_operation_host(operation_id)
391        );
392        let mut local_req_builder =
393            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
394
395        // build headers
396        let mut headers = HeaderMap::new();
397        headers.insert("Accept", HeaderValue::from_static("application/json"));
398
399        // build user agent
400        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
401            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
402            Err(e) => {
403                log::warn!("Failed to parse user agent header: {e}, falling back to default");
404                headers.insert(
405                    reqwest::header::USER_AGENT,
406                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
407                )
408            }
409        };
410
411        // build auth
412        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
413            headers.insert(
414                "DD-API-KEY",
415                HeaderValue::from_str(local_key.key.as_str())
416                    .expect("failed to parse DD-API-KEY header"),
417            );
418        };
419        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
420            headers.insert(
421                "DD-APPLICATION-KEY",
422                HeaderValue::from_str(local_key.key.as_str())
423                    .expect("failed to parse DD-APPLICATION-KEY header"),
424            );
425        };
426
427        local_req_builder = local_req_builder.headers(headers);
428        let local_req = local_req_builder.build()?;
429        log::debug!("request content: {:?}", local_req.body());
430        let local_resp = local_client.execute(local_req).await?;
431
432        let local_status = local_resp.status();
433        let local_content = local_resp.text().await?;
434        log::debug!("response content: {}", local_content);
435
436        if !local_status.is_client_error() && !local_status.is_server_error() {
437            match serde_json::from_str::<crate::datadogV2::model::OrgConnectionListResponse>(
438                &local_content,
439            ) {
440                Ok(e) => {
441                    return Ok(datadog::ResponseContent {
442                        status: local_status,
443                        content: local_content,
444                        entity: Some(e),
445                    })
446                }
447                Err(e) => return Err(datadog::Error::Serde(e)),
448            };
449        } else {
450            let local_entity: Option<ListOrgConnectionsError> =
451                serde_json::from_str(&local_content).ok();
452            let local_error = datadog::ResponseContent {
453                status: local_status,
454                content: local_content,
455                entity: local_entity,
456            };
457            Err(datadog::Error::ResponseError(local_error))
458        }
459    }
460
461    /// Update an existing org connection.
462    pub async fn update_org_connections(
463        &self,
464        connection_id: uuid::Uuid,
465        body: crate::datadogV2::model::OrgConnectionUpdateRequest,
466    ) -> Result<
467        crate::datadogV2::model::OrgConnectionResponse,
468        datadog::Error<UpdateOrgConnectionsError>,
469    > {
470        match self
471            .update_org_connections_with_http_info(connection_id, body)
472            .await
473        {
474            Ok(response_content) => {
475                if let Some(e) = response_content.entity {
476                    Ok(e)
477                } else {
478                    Err(datadog::Error::Serde(serde::de::Error::custom(
479                        "response content was None",
480                    )))
481                }
482            }
483            Err(err) => Err(err),
484        }
485    }
486
487    /// Update an existing org connection.
488    pub async fn update_org_connections_with_http_info(
489        &self,
490        connection_id: uuid::Uuid,
491        body: crate::datadogV2::model::OrgConnectionUpdateRequest,
492    ) -> Result<
493        datadog::ResponseContent<crate::datadogV2::model::OrgConnectionResponse>,
494        datadog::Error<UpdateOrgConnectionsError>,
495    > {
496        let local_configuration = &self.config;
497        let operation_id = "v2.update_org_connections";
498
499        let local_client = &self.client;
500
501        let local_uri_str = format!(
502            "{}/api/v2/org_connections/{connection_id}",
503            local_configuration.get_operation_host(operation_id),
504            connection_id = datadog::urlencode(connection_id.to_string())
505        );
506        let mut local_req_builder =
507            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
508
509        // build headers
510        let mut headers = HeaderMap::new();
511        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
512        headers.insert("Accept", HeaderValue::from_static("application/json"));
513
514        // build user agent
515        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
516            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
517            Err(e) => {
518                log::warn!("Failed to parse user agent header: {e}, falling back to default");
519                headers.insert(
520                    reqwest::header::USER_AGENT,
521                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
522                )
523            }
524        };
525
526        // build auth
527        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
528            headers.insert(
529                "DD-API-KEY",
530                HeaderValue::from_str(local_key.key.as_str())
531                    .expect("failed to parse DD-API-KEY header"),
532            );
533        };
534        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
535            headers.insert(
536                "DD-APPLICATION-KEY",
537                HeaderValue::from_str(local_key.key.as_str())
538                    .expect("failed to parse DD-APPLICATION-KEY header"),
539            );
540        };
541
542        // build body parameters
543        let output = Vec::new();
544        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
545        if body.serialize(&mut ser).is_ok() {
546            if let Some(content_encoding) = headers.get("Content-Encoding") {
547                match content_encoding.to_str().unwrap_or_default() {
548                    "gzip" => {
549                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
550                        let _ = enc.write_all(ser.into_inner().as_slice());
551                        match enc.finish() {
552                            Ok(buf) => {
553                                local_req_builder = local_req_builder.body(buf);
554                            }
555                            Err(e) => return Err(datadog::Error::Io(e)),
556                        }
557                    }
558                    "deflate" => {
559                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
560                        let _ = enc.write_all(ser.into_inner().as_slice());
561                        match enc.finish() {
562                            Ok(buf) => {
563                                local_req_builder = local_req_builder.body(buf);
564                            }
565                            Err(e) => return Err(datadog::Error::Io(e)),
566                        }
567                    }
568                    "zstd1" => {
569                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
570                        let _ = enc.write_all(ser.into_inner().as_slice());
571                        match enc.finish() {
572                            Ok(buf) => {
573                                local_req_builder = local_req_builder.body(buf);
574                            }
575                            Err(e) => return Err(datadog::Error::Io(e)),
576                        }
577                    }
578                    _ => {
579                        local_req_builder = local_req_builder.body(ser.into_inner());
580                    }
581                }
582            } else {
583                local_req_builder = local_req_builder.body(ser.into_inner());
584            }
585        }
586
587        local_req_builder = local_req_builder.headers(headers);
588        let local_req = local_req_builder.build()?;
589        log::debug!("request content: {:?}", local_req.body());
590        let local_resp = local_client.execute(local_req).await?;
591
592        let local_status = local_resp.status();
593        let local_content = local_resp.text().await?;
594        log::debug!("response content: {}", local_content);
595
596        if !local_status.is_client_error() && !local_status.is_server_error() {
597            match serde_json::from_str::<crate::datadogV2::model::OrgConnectionResponse>(
598                &local_content,
599            ) {
600                Ok(e) => {
601                    return Ok(datadog::ResponseContent {
602                        status: local_status,
603                        content: local_content,
604                        entity: Some(e),
605                    })
606                }
607                Err(e) => return Err(datadog::Error::Serde(e)),
608            };
609        } else {
610            let local_entity: Option<UpdateOrgConnectionsError> =
611                serde_json::from_str(&local_content).ok();
612            let local_error = datadog::ResponseContent {
613                status: local_status,
614                content: local_content,
615                entity: local_entity,
616            };
617            Err(datadog::Error::ResponseError(local_error))
618        }
619    }
620}