datadog_api_client/datadogV2/api/
api_aws_integration.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 log::warn;
10use reqwest::header::{HeaderMap, HeaderValue};
11use serde::{Deserialize, Serialize};
12use std::io::Write;
13
14/// ListAWSAccountsOptionalParams is a struct for passing parameters to the method [`AWSIntegrationAPI::list_aws_accounts`]
15#[non_exhaustive]
16#[derive(Clone, Default, Debug)]
17pub struct ListAWSAccountsOptionalParams {
18    /// Optional query parameter to filter accounts by AWS Account ID. If not provided, all accounts are returned.
19    pub aws_account_id: Option<String>,
20}
21
22impl ListAWSAccountsOptionalParams {
23    /// Optional query parameter to filter accounts by AWS Account ID. If not provided, all accounts are returned.
24    pub fn aws_account_id(mut self, value: String) -> Self {
25        self.aws_account_id = Some(value);
26        self
27    }
28}
29
30/// CreateAWSAccountError is a struct for typed errors of method [`AWSIntegrationAPI::create_aws_account`]
31#[derive(Debug, Clone, Serialize, Deserialize)]
32#[serde(untagged)]
33pub enum CreateAWSAccountError {
34    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
35    UnknownValue(serde_json::Value),
36}
37
38/// CreateNewAWSExternalIDError is a struct for typed errors of method [`AWSIntegrationAPI::create_new_aws_external_id`]
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[serde(untagged)]
41pub enum CreateNewAWSExternalIDError {
42    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
43    UnknownValue(serde_json::Value),
44}
45
46/// DeleteAWSAccountError is a struct for typed errors of method [`AWSIntegrationAPI::delete_aws_account`]
47#[derive(Debug, Clone, Serialize, Deserialize)]
48#[serde(untagged)]
49pub enum DeleteAWSAccountError {
50    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
51    UnknownValue(serde_json::Value),
52}
53
54/// GetAWSAccountError is a struct for typed errors of method [`AWSIntegrationAPI::get_aws_account`]
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(untagged)]
57pub enum GetAWSAccountError {
58    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
59    UnknownValue(serde_json::Value),
60}
61
62/// GetAWSIntegrationIAMPermissionsError is a struct for typed errors of method [`AWSIntegrationAPI::get_aws_integration_iam_permissions`]
63#[derive(Debug, Clone, Serialize, Deserialize)]
64#[serde(untagged)]
65pub enum GetAWSIntegrationIAMPermissionsError {
66    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
67    UnknownValue(serde_json::Value),
68}
69
70/// ListAWSAccountsError is a struct for typed errors of method [`AWSIntegrationAPI::list_aws_accounts`]
71#[derive(Debug, Clone, Serialize, Deserialize)]
72#[serde(untagged)]
73pub enum ListAWSAccountsError {
74    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
75    UnknownValue(serde_json::Value),
76}
77
78/// ListAWSNamespacesError is a struct for typed errors of method [`AWSIntegrationAPI::list_aws_namespaces`]
79#[derive(Debug, Clone, Serialize, Deserialize)]
80#[serde(untagged)]
81pub enum ListAWSNamespacesError {
82    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
83    UnknownValue(serde_json::Value),
84}
85
86/// UpdateAWSAccountError is a struct for typed errors of method [`AWSIntegrationAPI::update_aws_account`]
87#[derive(Debug, Clone, Serialize, Deserialize)]
88#[serde(untagged)]
89pub enum UpdateAWSAccountError {
90    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
91    UnknownValue(serde_json::Value),
92}
93
94/// Configure your Datadog-AWS integration directly through the Datadog API.
95/// For more information, see the [AWS integration page](<https://docs.datadoghq.com/integrations/amazon_web_services>).
96#[derive(Debug, Clone)]
97pub struct AWSIntegrationAPI {
98    config: datadog::Configuration,
99    client: reqwest_middleware::ClientWithMiddleware,
100}
101
102impl Default for AWSIntegrationAPI {
103    fn default() -> Self {
104        Self::with_config(datadog::Configuration::default())
105    }
106}
107
108impl AWSIntegrationAPI {
109    pub fn new() -> Self {
110        Self::default()
111    }
112    pub fn with_config(config: datadog::Configuration) -> Self {
113        let mut reqwest_client_builder = reqwest::Client::builder();
114
115        if let Some(proxy_url) = &config.proxy_url {
116            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
117            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
118        }
119
120        let mut middleware_client_builder =
121            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
122
123        if config.enable_retry {
124            struct RetryableStatus;
125            impl reqwest_retry::RetryableStrategy for RetryableStatus {
126                fn handle(
127                    &self,
128                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
129                ) -> Option<reqwest_retry::Retryable> {
130                    match res {
131                        Ok(success) => reqwest_retry::default_on_request_success(success),
132                        Err(_) => None,
133                    }
134                }
135            }
136            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
137                .build_with_max_retries(config.max_retries);
138
139            let retry_middleware =
140                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
141                    backoff_policy,
142                    RetryableStatus,
143                );
144
145            middleware_client_builder = middleware_client_builder.with(retry_middleware);
146        }
147
148        let client = middleware_client_builder.build();
149
150        Self { config, client }
151    }
152
153    pub fn with_client_and_config(
154        config: datadog::Configuration,
155        client: reqwest_middleware::ClientWithMiddleware,
156    ) -> Self {
157        Self { config, client }
158    }
159
160    /// Create a new AWS Account Integration Config.
161    pub async fn create_aws_account(
162        &self,
163        body: crate::datadogV2::model::AWSAccountCreateRequest,
164    ) -> Result<crate::datadogV2::model::AWSAccountResponse, datadog::Error<CreateAWSAccountError>>
165    {
166        match self.create_aws_account_with_http_info(body).await {
167            Ok(response_content) => {
168                if let Some(e) = response_content.entity {
169                    Ok(e)
170                } else {
171                    Err(datadog::Error::Serde(serde::de::Error::custom(
172                        "response content was None",
173                    )))
174                }
175            }
176            Err(err) => Err(err),
177        }
178    }
179
180    /// Create a new AWS Account Integration Config.
181    pub async fn create_aws_account_with_http_info(
182        &self,
183        body: crate::datadogV2::model::AWSAccountCreateRequest,
184    ) -> Result<
185        datadog::ResponseContent<crate::datadogV2::model::AWSAccountResponse>,
186        datadog::Error<CreateAWSAccountError>,
187    > {
188        let local_configuration = &self.config;
189        let operation_id = "v2.create_aws_account";
190        if local_configuration.is_unstable_operation_enabled(operation_id) {
191            warn!("Using unstable operation {operation_id}");
192        } else {
193            let local_error = datadog::UnstableOperationDisabledError {
194                msg: "Operation 'v2.create_aws_account' is not enabled".to_string(),
195            };
196            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
197        }
198
199        let local_client = &self.client;
200
201        let local_uri_str = format!(
202            "{}/api/v2/integration/aws/accounts",
203            local_configuration.get_operation_host(operation_id)
204        );
205        let mut local_req_builder =
206            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
207
208        // build headers
209        let mut headers = HeaderMap::new();
210        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
211        headers.insert("Accept", HeaderValue::from_static("application/json"));
212
213        // build user agent
214        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
215            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
216            Err(e) => {
217                log::warn!("Failed to parse user agent header: {e}, falling back to default");
218                headers.insert(
219                    reqwest::header::USER_AGENT,
220                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
221                )
222            }
223        };
224
225        // build auth
226        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
227            headers.insert(
228                "DD-API-KEY",
229                HeaderValue::from_str(local_key.key.as_str())
230                    .expect("failed to parse DD-API-KEY header"),
231            );
232        };
233        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
234            headers.insert(
235                "DD-APPLICATION-KEY",
236                HeaderValue::from_str(local_key.key.as_str())
237                    .expect("failed to parse DD-APPLICATION-KEY header"),
238            );
239        };
240
241        // build body parameters
242        let output = Vec::new();
243        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
244        if body.serialize(&mut ser).is_ok() {
245            if let Some(content_encoding) = headers.get("Content-Encoding") {
246                match content_encoding.to_str().unwrap_or_default() {
247                    "gzip" => {
248                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
249                        let _ = enc.write_all(ser.into_inner().as_slice());
250                        match enc.finish() {
251                            Ok(buf) => {
252                                local_req_builder = local_req_builder.body(buf);
253                            }
254                            Err(e) => return Err(datadog::Error::Io(e)),
255                        }
256                    }
257                    "deflate" => {
258                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
259                        let _ = enc.write_all(ser.into_inner().as_slice());
260                        match enc.finish() {
261                            Ok(buf) => {
262                                local_req_builder = local_req_builder.body(buf);
263                            }
264                            Err(e) => return Err(datadog::Error::Io(e)),
265                        }
266                    }
267                    "zstd1" => {
268                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
269                        let _ = enc.write_all(ser.into_inner().as_slice());
270                        match enc.finish() {
271                            Ok(buf) => {
272                                local_req_builder = local_req_builder.body(buf);
273                            }
274                            Err(e) => return Err(datadog::Error::Io(e)),
275                        }
276                    }
277                    _ => {
278                        local_req_builder = local_req_builder.body(ser.into_inner());
279                    }
280                }
281            } else {
282                local_req_builder = local_req_builder.body(ser.into_inner());
283            }
284        }
285
286        local_req_builder = local_req_builder.headers(headers);
287        let local_req = local_req_builder.build()?;
288        log::debug!("request content: {:?}", local_req.body());
289        let local_resp = local_client.execute(local_req).await?;
290
291        let local_status = local_resp.status();
292        let local_content = local_resp.text().await?;
293        log::debug!("response content: {}", local_content);
294
295        if !local_status.is_client_error() && !local_status.is_server_error() {
296            match serde_json::from_str::<crate::datadogV2::model::AWSAccountResponse>(
297                &local_content,
298            ) {
299                Ok(e) => {
300                    return Ok(datadog::ResponseContent {
301                        status: local_status,
302                        content: local_content,
303                        entity: Some(e),
304                    })
305                }
306                Err(e) => return Err(datadog::Error::Serde(e)),
307            };
308        } else {
309            let local_entity: Option<CreateAWSAccountError> =
310                serde_json::from_str(&local_content).ok();
311            let local_error = datadog::ResponseContent {
312                status: local_status,
313                content: local_content,
314                entity: local_entity,
315            };
316            Err(datadog::Error::ResponseError(local_error))
317        }
318    }
319
320    /// Generate a new external ID for AWS role-based authentication.
321    pub async fn create_new_aws_external_id(
322        &self,
323    ) -> Result<
324        crate::datadogV2::model::AWSNewExternalIDResponse,
325        datadog::Error<CreateNewAWSExternalIDError>,
326    > {
327        match self.create_new_aws_external_id_with_http_info().await {
328            Ok(response_content) => {
329                if let Some(e) = response_content.entity {
330                    Ok(e)
331                } else {
332                    Err(datadog::Error::Serde(serde::de::Error::custom(
333                        "response content was None",
334                    )))
335                }
336            }
337            Err(err) => Err(err),
338        }
339    }
340
341    /// Generate a new external ID for AWS role-based authentication.
342    pub async fn create_new_aws_external_id_with_http_info(
343        &self,
344    ) -> Result<
345        datadog::ResponseContent<crate::datadogV2::model::AWSNewExternalIDResponse>,
346        datadog::Error<CreateNewAWSExternalIDError>,
347    > {
348        let local_configuration = &self.config;
349        let operation_id = "v2.create_new_aws_external_id";
350        if local_configuration.is_unstable_operation_enabled(operation_id) {
351            warn!("Using unstable operation {operation_id}");
352        } else {
353            let local_error = datadog::UnstableOperationDisabledError {
354                msg: "Operation 'v2.create_new_aws_external_id' is not enabled".to_string(),
355            };
356            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
357        }
358
359        let local_client = &self.client;
360
361        let local_uri_str = format!(
362            "{}/api/v2/integration/aws/generate_new_external_id",
363            local_configuration.get_operation_host(operation_id)
364        );
365        let mut local_req_builder =
366            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
367
368        // build headers
369        let mut headers = HeaderMap::new();
370        headers.insert("Accept", HeaderValue::from_static("application/json"));
371
372        // build user agent
373        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
374            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
375            Err(e) => {
376                log::warn!("Failed to parse user agent header: {e}, falling back to default");
377                headers.insert(
378                    reqwest::header::USER_AGENT,
379                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
380                )
381            }
382        };
383
384        // build auth
385        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
386            headers.insert(
387                "DD-API-KEY",
388                HeaderValue::from_str(local_key.key.as_str())
389                    .expect("failed to parse DD-API-KEY header"),
390            );
391        };
392        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
393            headers.insert(
394                "DD-APPLICATION-KEY",
395                HeaderValue::from_str(local_key.key.as_str())
396                    .expect("failed to parse DD-APPLICATION-KEY header"),
397            );
398        };
399
400        local_req_builder = local_req_builder.headers(headers);
401        let local_req = local_req_builder.build()?;
402        log::debug!("request content: {:?}", local_req.body());
403        let local_resp = local_client.execute(local_req).await?;
404
405        let local_status = local_resp.status();
406        let local_content = local_resp.text().await?;
407        log::debug!("response content: {}", local_content);
408
409        if !local_status.is_client_error() && !local_status.is_server_error() {
410            match serde_json::from_str::<crate::datadogV2::model::AWSNewExternalIDResponse>(
411                &local_content,
412            ) {
413                Ok(e) => {
414                    return Ok(datadog::ResponseContent {
415                        status: local_status,
416                        content: local_content,
417                        entity: Some(e),
418                    })
419                }
420                Err(e) => return Err(datadog::Error::Serde(e)),
421            };
422        } else {
423            let local_entity: Option<CreateNewAWSExternalIDError> =
424                serde_json::from_str(&local_content).ok();
425            let local_error = datadog::ResponseContent {
426                status: local_status,
427                content: local_content,
428                entity: local_entity,
429            };
430            Err(datadog::Error::ResponseError(local_error))
431        }
432    }
433
434    /// Delete an AWS Account Integration Config by config ID.
435    pub async fn delete_aws_account(
436        &self,
437        aws_account_config_id: String,
438    ) -> Result<(), datadog::Error<DeleteAWSAccountError>> {
439        match self
440            .delete_aws_account_with_http_info(aws_account_config_id)
441            .await
442        {
443            Ok(_) => Ok(()),
444            Err(err) => Err(err),
445        }
446    }
447
448    /// Delete an AWS Account Integration Config by config ID.
449    pub async fn delete_aws_account_with_http_info(
450        &self,
451        aws_account_config_id: String,
452    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteAWSAccountError>> {
453        let local_configuration = &self.config;
454        let operation_id = "v2.delete_aws_account";
455        if local_configuration.is_unstable_operation_enabled(operation_id) {
456            warn!("Using unstable operation {operation_id}");
457        } else {
458            let local_error = datadog::UnstableOperationDisabledError {
459                msg: "Operation 'v2.delete_aws_account' is not enabled".to_string(),
460            };
461            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
462        }
463
464        let local_client = &self.client;
465
466        let local_uri_str = format!(
467            "{}/api/v2/integration/aws/accounts/{aws_account_config_id}",
468            local_configuration.get_operation_host(operation_id),
469            aws_account_config_id = datadog::urlencode(aws_account_config_id)
470        );
471        let mut local_req_builder =
472            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
473
474        // build headers
475        let mut headers = HeaderMap::new();
476        headers.insert("Accept", HeaderValue::from_static("*/*"));
477
478        // build user agent
479        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
480            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
481            Err(e) => {
482                log::warn!("Failed to parse user agent header: {e}, falling back to default");
483                headers.insert(
484                    reqwest::header::USER_AGENT,
485                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
486                )
487            }
488        };
489
490        // build auth
491        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
492            headers.insert(
493                "DD-API-KEY",
494                HeaderValue::from_str(local_key.key.as_str())
495                    .expect("failed to parse DD-API-KEY header"),
496            );
497        };
498        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
499            headers.insert(
500                "DD-APPLICATION-KEY",
501                HeaderValue::from_str(local_key.key.as_str())
502                    .expect("failed to parse DD-APPLICATION-KEY header"),
503            );
504        };
505
506        local_req_builder = local_req_builder.headers(headers);
507        let local_req = local_req_builder.build()?;
508        log::debug!("request content: {:?}", local_req.body());
509        let local_resp = local_client.execute(local_req).await?;
510
511        let local_status = local_resp.status();
512        let local_content = local_resp.text().await?;
513        log::debug!("response content: {}", local_content);
514
515        if !local_status.is_client_error() && !local_status.is_server_error() {
516            Ok(datadog::ResponseContent {
517                status: local_status,
518                content: local_content,
519                entity: None,
520            })
521        } else {
522            let local_entity: Option<DeleteAWSAccountError> =
523                serde_json::from_str(&local_content).ok();
524            let local_error = datadog::ResponseContent {
525                status: local_status,
526                content: local_content,
527                entity: local_entity,
528            };
529            Err(datadog::Error::ResponseError(local_error))
530        }
531    }
532
533    /// Get an AWS Account Integration Config by config ID.
534    pub async fn get_aws_account(
535        &self,
536        aws_account_config_id: String,
537    ) -> Result<crate::datadogV2::model::AWSAccountResponse, datadog::Error<GetAWSAccountError>>
538    {
539        match self
540            .get_aws_account_with_http_info(aws_account_config_id)
541            .await
542        {
543            Ok(response_content) => {
544                if let Some(e) = response_content.entity {
545                    Ok(e)
546                } else {
547                    Err(datadog::Error::Serde(serde::de::Error::custom(
548                        "response content was None",
549                    )))
550                }
551            }
552            Err(err) => Err(err),
553        }
554    }
555
556    /// Get an AWS Account Integration Config by config ID.
557    pub async fn get_aws_account_with_http_info(
558        &self,
559        aws_account_config_id: String,
560    ) -> Result<
561        datadog::ResponseContent<crate::datadogV2::model::AWSAccountResponse>,
562        datadog::Error<GetAWSAccountError>,
563    > {
564        let local_configuration = &self.config;
565        let operation_id = "v2.get_aws_account";
566        if local_configuration.is_unstable_operation_enabled(operation_id) {
567            warn!("Using unstable operation {operation_id}");
568        } else {
569            let local_error = datadog::UnstableOperationDisabledError {
570                msg: "Operation 'v2.get_aws_account' is not enabled".to_string(),
571            };
572            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
573        }
574
575        let local_client = &self.client;
576
577        let local_uri_str = format!(
578            "{}/api/v2/integration/aws/accounts/{aws_account_config_id}",
579            local_configuration.get_operation_host(operation_id),
580            aws_account_config_id = datadog::urlencode(aws_account_config_id)
581        );
582        let mut local_req_builder =
583            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
584
585        // build headers
586        let mut headers = HeaderMap::new();
587        headers.insert("Accept", HeaderValue::from_static("application/json"));
588
589        // build user agent
590        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
591            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
592            Err(e) => {
593                log::warn!("Failed to parse user agent header: {e}, falling back to default");
594                headers.insert(
595                    reqwest::header::USER_AGENT,
596                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
597                )
598            }
599        };
600
601        // build auth
602        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
603            headers.insert(
604                "DD-API-KEY",
605                HeaderValue::from_str(local_key.key.as_str())
606                    .expect("failed to parse DD-API-KEY header"),
607            );
608        };
609        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
610            headers.insert(
611                "DD-APPLICATION-KEY",
612                HeaderValue::from_str(local_key.key.as_str())
613                    .expect("failed to parse DD-APPLICATION-KEY header"),
614            );
615        };
616
617        local_req_builder = local_req_builder.headers(headers);
618        let local_req = local_req_builder.build()?;
619        log::debug!("request content: {:?}", local_req.body());
620        let local_resp = local_client.execute(local_req).await?;
621
622        let local_status = local_resp.status();
623        let local_content = local_resp.text().await?;
624        log::debug!("response content: {}", local_content);
625
626        if !local_status.is_client_error() && !local_status.is_server_error() {
627            match serde_json::from_str::<crate::datadogV2::model::AWSAccountResponse>(
628                &local_content,
629            ) {
630                Ok(e) => {
631                    return Ok(datadog::ResponseContent {
632                        status: local_status,
633                        content: local_content,
634                        entity: Some(e),
635                    })
636                }
637                Err(e) => return Err(datadog::Error::Serde(e)),
638            };
639        } else {
640            let local_entity: Option<GetAWSAccountError> =
641                serde_json::from_str(&local_content).ok();
642            let local_error = datadog::ResponseContent {
643                status: local_status,
644                content: local_content,
645                entity: local_entity,
646            };
647            Err(datadog::Error::ResponseError(local_error))
648        }
649    }
650
651    /// Get all AWS IAM permissions required for the AWS integration.
652    pub async fn get_aws_integration_iam_permissions(
653        &self,
654    ) -> Result<
655        crate::datadogV2::model::AWSIntegrationIamPermissionsResponse,
656        datadog::Error<GetAWSIntegrationIAMPermissionsError>,
657    > {
658        match self
659            .get_aws_integration_iam_permissions_with_http_info()
660            .await
661        {
662            Ok(response_content) => {
663                if let Some(e) = response_content.entity {
664                    Ok(e)
665                } else {
666                    Err(datadog::Error::Serde(serde::de::Error::custom(
667                        "response content was None",
668                    )))
669                }
670            }
671            Err(err) => Err(err),
672        }
673    }
674
675    /// Get all AWS IAM permissions required for the AWS integration.
676    pub async fn get_aws_integration_iam_permissions_with_http_info(
677        &self,
678    ) -> Result<
679        datadog::ResponseContent<crate::datadogV2::model::AWSIntegrationIamPermissionsResponse>,
680        datadog::Error<GetAWSIntegrationIAMPermissionsError>,
681    > {
682        let local_configuration = &self.config;
683        let operation_id = "v2.get_aws_integration_iam_permissions";
684
685        let local_client = &self.client;
686
687        let local_uri_str = format!(
688            "{}/api/v2/integration/aws/iam_permissions",
689            local_configuration.get_operation_host(operation_id)
690        );
691        let mut local_req_builder =
692            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
693
694        // build headers
695        let mut headers = HeaderMap::new();
696        headers.insert("Accept", HeaderValue::from_static("application/json"));
697
698        // build user agent
699        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
700            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
701            Err(e) => {
702                log::warn!("Failed to parse user agent header: {e}, falling back to default");
703                headers.insert(
704                    reqwest::header::USER_AGENT,
705                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
706                )
707            }
708        };
709
710        // build auth
711        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
712            headers.insert(
713                "DD-API-KEY",
714                HeaderValue::from_str(local_key.key.as_str())
715                    .expect("failed to parse DD-API-KEY header"),
716            );
717        };
718        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
719            headers.insert(
720                "DD-APPLICATION-KEY",
721                HeaderValue::from_str(local_key.key.as_str())
722                    .expect("failed to parse DD-APPLICATION-KEY header"),
723            );
724        };
725
726        local_req_builder = local_req_builder.headers(headers);
727        let local_req = local_req_builder.build()?;
728        log::debug!("request content: {:?}", local_req.body());
729        let local_resp = local_client.execute(local_req).await?;
730
731        let local_status = local_resp.status();
732        let local_content = local_resp.text().await?;
733        log::debug!("response content: {}", local_content);
734
735        if !local_status.is_client_error() && !local_status.is_server_error() {
736            match serde_json::from_str::<
737                crate::datadogV2::model::AWSIntegrationIamPermissionsResponse,
738            >(&local_content)
739            {
740                Ok(e) => {
741                    return Ok(datadog::ResponseContent {
742                        status: local_status,
743                        content: local_content,
744                        entity: Some(e),
745                    })
746                }
747                Err(e) => return Err(datadog::Error::Serde(e)),
748            };
749        } else {
750            let local_entity: Option<GetAWSIntegrationIAMPermissionsError> =
751                serde_json::from_str(&local_content).ok();
752            let local_error = datadog::ResponseContent {
753                status: local_status,
754                content: local_content,
755                entity: local_entity,
756            };
757            Err(datadog::Error::ResponseError(local_error))
758        }
759    }
760
761    /// Get a list of AWS Account Integration Configs.
762    pub async fn list_aws_accounts(
763        &self,
764        params: ListAWSAccountsOptionalParams,
765    ) -> Result<crate::datadogV2::model::AWSAccountsResponse, datadog::Error<ListAWSAccountsError>>
766    {
767        match self.list_aws_accounts_with_http_info(params).await {
768            Ok(response_content) => {
769                if let Some(e) = response_content.entity {
770                    Ok(e)
771                } else {
772                    Err(datadog::Error::Serde(serde::de::Error::custom(
773                        "response content was None",
774                    )))
775                }
776            }
777            Err(err) => Err(err),
778        }
779    }
780
781    /// Get a list of AWS Account Integration Configs.
782    pub async fn list_aws_accounts_with_http_info(
783        &self,
784        params: ListAWSAccountsOptionalParams,
785    ) -> Result<
786        datadog::ResponseContent<crate::datadogV2::model::AWSAccountsResponse>,
787        datadog::Error<ListAWSAccountsError>,
788    > {
789        let local_configuration = &self.config;
790        let operation_id = "v2.list_aws_accounts";
791        if local_configuration.is_unstable_operation_enabled(operation_id) {
792            warn!("Using unstable operation {operation_id}");
793        } else {
794            let local_error = datadog::UnstableOperationDisabledError {
795                msg: "Operation 'v2.list_aws_accounts' is not enabled".to_string(),
796            };
797            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
798        }
799
800        // unbox and build optional parameters
801        let aws_account_id = params.aws_account_id;
802
803        let local_client = &self.client;
804
805        let local_uri_str = format!(
806            "{}/api/v2/integration/aws/accounts",
807            local_configuration.get_operation_host(operation_id)
808        );
809        let mut local_req_builder =
810            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
811
812        if let Some(ref local_query_param) = aws_account_id {
813            local_req_builder =
814                local_req_builder.query(&[("aws_account_id", &local_query_param.to_string())]);
815        };
816
817        // build headers
818        let mut headers = HeaderMap::new();
819        headers.insert("Accept", HeaderValue::from_static("application/json"));
820
821        // build user agent
822        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
823            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
824            Err(e) => {
825                log::warn!("Failed to parse user agent header: {e}, falling back to default");
826                headers.insert(
827                    reqwest::header::USER_AGENT,
828                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
829                )
830            }
831        };
832
833        // build auth
834        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
835            headers.insert(
836                "DD-API-KEY",
837                HeaderValue::from_str(local_key.key.as_str())
838                    .expect("failed to parse DD-API-KEY header"),
839            );
840        };
841        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
842            headers.insert(
843                "DD-APPLICATION-KEY",
844                HeaderValue::from_str(local_key.key.as_str())
845                    .expect("failed to parse DD-APPLICATION-KEY header"),
846            );
847        };
848
849        local_req_builder = local_req_builder.headers(headers);
850        let local_req = local_req_builder.build()?;
851        log::debug!("request content: {:?}", local_req.body());
852        let local_resp = local_client.execute(local_req).await?;
853
854        let local_status = local_resp.status();
855        let local_content = local_resp.text().await?;
856        log::debug!("response content: {}", local_content);
857
858        if !local_status.is_client_error() && !local_status.is_server_error() {
859            match serde_json::from_str::<crate::datadogV2::model::AWSAccountsResponse>(
860                &local_content,
861            ) {
862                Ok(e) => {
863                    return Ok(datadog::ResponseContent {
864                        status: local_status,
865                        content: local_content,
866                        entity: Some(e),
867                    })
868                }
869                Err(e) => return Err(datadog::Error::Serde(e)),
870            };
871        } else {
872            let local_entity: Option<ListAWSAccountsError> =
873                serde_json::from_str(&local_content).ok();
874            let local_error = datadog::ResponseContent {
875                status: local_status,
876                content: local_content,
877                entity: local_entity,
878            };
879            Err(datadog::Error::ResponseError(local_error))
880        }
881    }
882
883    /// Get a list of available AWS CloudWatch namespaces that can send metrics to Datadog.
884    pub async fn list_aws_namespaces(
885        &self,
886    ) -> Result<
887        crate::datadogV2::model::AWSNamespacesResponse,
888        datadog::Error<ListAWSNamespacesError>,
889    > {
890        match self.list_aws_namespaces_with_http_info().await {
891            Ok(response_content) => {
892                if let Some(e) = response_content.entity {
893                    Ok(e)
894                } else {
895                    Err(datadog::Error::Serde(serde::de::Error::custom(
896                        "response content was None",
897                    )))
898                }
899            }
900            Err(err) => Err(err),
901        }
902    }
903
904    /// Get a list of available AWS CloudWatch namespaces that can send metrics to Datadog.
905    pub async fn list_aws_namespaces_with_http_info(
906        &self,
907    ) -> Result<
908        datadog::ResponseContent<crate::datadogV2::model::AWSNamespacesResponse>,
909        datadog::Error<ListAWSNamespacesError>,
910    > {
911        let local_configuration = &self.config;
912        let operation_id = "v2.list_aws_namespaces";
913        if local_configuration.is_unstable_operation_enabled(operation_id) {
914            warn!("Using unstable operation {operation_id}");
915        } else {
916            let local_error = datadog::UnstableOperationDisabledError {
917                msg: "Operation 'v2.list_aws_namespaces' is not enabled".to_string(),
918            };
919            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
920        }
921
922        let local_client = &self.client;
923
924        let local_uri_str = format!(
925            "{}/api/v2/integration/aws/available_namespaces",
926            local_configuration.get_operation_host(operation_id)
927        );
928        let mut local_req_builder =
929            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
930
931        // build headers
932        let mut headers = HeaderMap::new();
933        headers.insert("Accept", HeaderValue::from_static("application/json"));
934
935        // build user agent
936        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
937            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
938            Err(e) => {
939                log::warn!("Failed to parse user agent header: {e}, falling back to default");
940                headers.insert(
941                    reqwest::header::USER_AGENT,
942                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
943                )
944            }
945        };
946
947        // build auth
948        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
949            headers.insert(
950                "DD-API-KEY",
951                HeaderValue::from_str(local_key.key.as_str())
952                    .expect("failed to parse DD-API-KEY header"),
953            );
954        };
955        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
956            headers.insert(
957                "DD-APPLICATION-KEY",
958                HeaderValue::from_str(local_key.key.as_str())
959                    .expect("failed to parse DD-APPLICATION-KEY header"),
960            );
961        };
962
963        local_req_builder = local_req_builder.headers(headers);
964        let local_req = local_req_builder.build()?;
965        log::debug!("request content: {:?}", local_req.body());
966        let local_resp = local_client.execute(local_req).await?;
967
968        let local_status = local_resp.status();
969        let local_content = local_resp.text().await?;
970        log::debug!("response content: {}", local_content);
971
972        if !local_status.is_client_error() && !local_status.is_server_error() {
973            match serde_json::from_str::<crate::datadogV2::model::AWSNamespacesResponse>(
974                &local_content,
975            ) {
976                Ok(e) => {
977                    return Ok(datadog::ResponseContent {
978                        status: local_status,
979                        content: local_content,
980                        entity: Some(e),
981                    })
982                }
983                Err(e) => return Err(datadog::Error::Serde(e)),
984            };
985        } else {
986            let local_entity: Option<ListAWSNamespacesError> =
987                serde_json::from_str(&local_content).ok();
988            let local_error = datadog::ResponseContent {
989                status: local_status,
990                content: local_content,
991                entity: local_entity,
992            };
993            Err(datadog::Error::ResponseError(local_error))
994        }
995    }
996
997    /// Update an AWS Account Integration Config by config ID.
998    pub async fn update_aws_account(
999        &self,
1000        aws_account_config_id: String,
1001        body: crate::datadogV2::model::AWSAccountUpdateRequest,
1002    ) -> Result<crate::datadogV2::model::AWSAccountResponse, datadog::Error<UpdateAWSAccountError>>
1003    {
1004        match self
1005            .update_aws_account_with_http_info(aws_account_config_id, body)
1006            .await
1007        {
1008            Ok(response_content) => {
1009                if let Some(e) = response_content.entity {
1010                    Ok(e)
1011                } else {
1012                    Err(datadog::Error::Serde(serde::de::Error::custom(
1013                        "response content was None",
1014                    )))
1015                }
1016            }
1017            Err(err) => Err(err),
1018        }
1019    }
1020
1021    /// Update an AWS Account Integration Config by config ID.
1022    pub async fn update_aws_account_with_http_info(
1023        &self,
1024        aws_account_config_id: String,
1025        body: crate::datadogV2::model::AWSAccountUpdateRequest,
1026    ) -> Result<
1027        datadog::ResponseContent<crate::datadogV2::model::AWSAccountResponse>,
1028        datadog::Error<UpdateAWSAccountError>,
1029    > {
1030        let local_configuration = &self.config;
1031        let operation_id = "v2.update_aws_account";
1032        if local_configuration.is_unstable_operation_enabled(operation_id) {
1033            warn!("Using unstable operation {operation_id}");
1034        } else {
1035            let local_error = datadog::UnstableOperationDisabledError {
1036                msg: "Operation 'v2.update_aws_account' is not enabled".to_string(),
1037            };
1038            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
1039        }
1040
1041        let local_client = &self.client;
1042
1043        let local_uri_str = format!(
1044            "{}/api/v2/integration/aws/accounts/{aws_account_config_id}",
1045            local_configuration.get_operation_host(operation_id),
1046            aws_account_config_id = datadog::urlencode(aws_account_config_id)
1047        );
1048        let mut local_req_builder =
1049            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
1050
1051        // build headers
1052        let mut headers = HeaderMap::new();
1053        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1054        headers.insert("Accept", HeaderValue::from_static("application/json"));
1055
1056        // build user agent
1057        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1058            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1059            Err(e) => {
1060                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1061                headers.insert(
1062                    reqwest::header::USER_AGENT,
1063                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1064                )
1065            }
1066        };
1067
1068        // build auth
1069        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1070            headers.insert(
1071                "DD-API-KEY",
1072                HeaderValue::from_str(local_key.key.as_str())
1073                    .expect("failed to parse DD-API-KEY header"),
1074            );
1075        };
1076        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1077            headers.insert(
1078                "DD-APPLICATION-KEY",
1079                HeaderValue::from_str(local_key.key.as_str())
1080                    .expect("failed to parse DD-APPLICATION-KEY header"),
1081            );
1082        };
1083
1084        // build body parameters
1085        let output = Vec::new();
1086        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1087        if body.serialize(&mut ser).is_ok() {
1088            if let Some(content_encoding) = headers.get("Content-Encoding") {
1089                match content_encoding.to_str().unwrap_or_default() {
1090                    "gzip" => {
1091                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1092                        let _ = enc.write_all(ser.into_inner().as_slice());
1093                        match enc.finish() {
1094                            Ok(buf) => {
1095                                local_req_builder = local_req_builder.body(buf);
1096                            }
1097                            Err(e) => return Err(datadog::Error::Io(e)),
1098                        }
1099                    }
1100                    "deflate" => {
1101                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1102                        let _ = enc.write_all(ser.into_inner().as_slice());
1103                        match enc.finish() {
1104                            Ok(buf) => {
1105                                local_req_builder = local_req_builder.body(buf);
1106                            }
1107                            Err(e) => return Err(datadog::Error::Io(e)),
1108                        }
1109                    }
1110                    "zstd1" => {
1111                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1112                        let _ = enc.write_all(ser.into_inner().as_slice());
1113                        match enc.finish() {
1114                            Ok(buf) => {
1115                                local_req_builder = local_req_builder.body(buf);
1116                            }
1117                            Err(e) => return Err(datadog::Error::Io(e)),
1118                        }
1119                    }
1120                    _ => {
1121                        local_req_builder = local_req_builder.body(ser.into_inner());
1122                    }
1123                }
1124            } else {
1125                local_req_builder = local_req_builder.body(ser.into_inner());
1126            }
1127        }
1128
1129        local_req_builder = local_req_builder.headers(headers);
1130        let local_req = local_req_builder.build()?;
1131        log::debug!("request content: {:?}", local_req.body());
1132        let local_resp = local_client.execute(local_req).await?;
1133
1134        let local_status = local_resp.status();
1135        let local_content = local_resp.text().await?;
1136        log::debug!("response content: {}", local_content);
1137
1138        if !local_status.is_client_error() && !local_status.is_server_error() {
1139            match serde_json::from_str::<crate::datadogV2::model::AWSAccountResponse>(
1140                &local_content,
1141            ) {
1142                Ok(e) => {
1143                    return Ok(datadog::ResponseContent {
1144                        status: local_status,
1145                        content: local_content,
1146                        entity: Some(e),
1147                    })
1148                }
1149                Err(e) => return Err(datadog::Error::Serde(e)),
1150            };
1151        } else {
1152            let local_entity: Option<UpdateAWSAccountError> =
1153                serde_json::from_str(&local_content).ok();
1154            let local_error = datadog::ResponseContent {
1155                status: local_status,
1156                content: local_content,
1157                entity: local_entity,
1158            };
1159            Err(datadog::Error::ResponseError(local_error))
1160        }
1161    }
1162}