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