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