datadog_api_client/datadogV2/api/
api_service_scorecards.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 async_stream::try_stream;
6use flate2::{
7    write::{GzEncoder, ZlibEncoder},
8    Compression,
9};
10use futures_core::stream::Stream;
11use log::warn;
12use reqwest::header::{HeaderMap, HeaderValue};
13use serde::{Deserialize, Serialize};
14use std::io::Write;
15
16/// ListScorecardOutcomesOptionalParams is a struct for passing parameters to the method [`ServiceScorecardsAPI::list_scorecard_outcomes`]
17#[non_exhaustive]
18#[derive(Clone, Default, Debug)]
19pub struct ListScorecardOutcomesOptionalParams {
20    /// Size for a given page. The maximum allowed value is 100.
21    pub page_size: Option<i64>,
22    /// Specific offset to use as the beginning of the returned page.
23    pub page_offset: Option<i64>,
24    /// Include related rule details in the response.
25    pub include: Option<String>,
26    /// Return only specified values in the outcome attributes.
27    pub fields_outcome: Option<String>,
28    /// Return only specified values in the included rule details.
29    pub fields_rule: Option<String>,
30    /// Filter the outcomes on a specific service name.
31    pub filter_outcome_service_name: Option<String>,
32    /// Filter the outcomes by a specific state.
33    pub filter_outcome_state: Option<String>,
34    /// Filter outcomes on whether a rule is enabled/disabled.
35    pub filter_rule_enabled: Option<bool>,
36    /// Filter outcomes based on rule ID.
37    pub filter_rule_id: Option<String>,
38    /// Filter outcomes based on rule name.
39    pub filter_rule_name: Option<String>,
40}
41
42impl ListScorecardOutcomesOptionalParams {
43    /// Size for a given page. The maximum allowed value is 100.
44    pub fn page_size(mut self, value: i64) -> Self {
45        self.page_size = Some(value);
46        self
47    }
48    /// Specific offset to use as the beginning of the returned page.
49    pub fn page_offset(mut self, value: i64) -> Self {
50        self.page_offset = Some(value);
51        self
52    }
53    /// Include related rule details in the response.
54    pub fn include(mut self, value: String) -> Self {
55        self.include = Some(value);
56        self
57    }
58    /// Return only specified values in the outcome attributes.
59    pub fn fields_outcome(mut self, value: String) -> Self {
60        self.fields_outcome = Some(value);
61        self
62    }
63    /// Return only specified values in the included rule details.
64    pub fn fields_rule(mut self, value: String) -> Self {
65        self.fields_rule = Some(value);
66        self
67    }
68    /// Filter the outcomes on a specific service name.
69    pub fn filter_outcome_service_name(mut self, value: String) -> Self {
70        self.filter_outcome_service_name = Some(value);
71        self
72    }
73    /// Filter the outcomes by a specific state.
74    pub fn filter_outcome_state(mut self, value: String) -> Self {
75        self.filter_outcome_state = Some(value);
76        self
77    }
78    /// Filter outcomes on whether a rule is enabled/disabled.
79    pub fn filter_rule_enabled(mut self, value: bool) -> Self {
80        self.filter_rule_enabled = Some(value);
81        self
82    }
83    /// Filter outcomes based on rule ID.
84    pub fn filter_rule_id(mut self, value: String) -> Self {
85        self.filter_rule_id = Some(value);
86        self
87    }
88    /// Filter outcomes based on rule name.
89    pub fn filter_rule_name(mut self, value: String) -> Self {
90        self.filter_rule_name = Some(value);
91        self
92    }
93}
94
95/// ListScorecardRulesOptionalParams is a struct for passing parameters to the method [`ServiceScorecardsAPI::list_scorecard_rules`]
96#[non_exhaustive]
97#[derive(Clone, Default, Debug)]
98pub struct ListScorecardRulesOptionalParams {
99    /// Size for a given page. The maximum allowed value is 100.
100    pub page_size: Option<i64>,
101    /// Specific offset to use as the beginning of the returned page.
102    pub page_offset: Option<i64>,
103    /// Include related scorecard details in the response.
104    pub include: Option<String>,
105    /// Filter the rules on a rule ID.
106    pub filter_rule_id: Option<String>,
107    /// Filter for enabled rules only.
108    pub filter_rule_enabled: Option<bool>,
109    /// Filter for custom rules only.
110    pub filter_rule_custom: Option<bool>,
111    /// Filter rules on the rule name.
112    pub filter_rule_name: Option<String>,
113    /// Filter rules on the rule description.
114    pub filter_rule_description: Option<String>,
115    /// Return only specific fields in the response for rule attributes.
116    pub fields_rule: Option<String>,
117    /// Return only specific fields in the included response for scorecard attributes.
118    pub fields_scorecard: Option<String>,
119}
120
121impl ListScorecardRulesOptionalParams {
122    /// Size for a given page. The maximum allowed value is 100.
123    pub fn page_size(mut self, value: i64) -> Self {
124        self.page_size = Some(value);
125        self
126    }
127    /// Specific offset to use as the beginning of the returned page.
128    pub fn page_offset(mut self, value: i64) -> Self {
129        self.page_offset = Some(value);
130        self
131    }
132    /// Include related scorecard details in the response.
133    pub fn include(mut self, value: String) -> Self {
134        self.include = Some(value);
135        self
136    }
137    /// Filter the rules on a rule ID.
138    pub fn filter_rule_id(mut self, value: String) -> Self {
139        self.filter_rule_id = Some(value);
140        self
141    }
142    /// Filter for enabled rules only.
143    pub fn filter_rule_enabled(mut self, value: bool) -> Self {
144        self.filter_rule_enabled = Some(value);
145        self
146    }
147    /// Filter for custom rules only.
148    pub fn filter_rule_custom(mut self, value: bool) -> Self {
149        self.filter_rule_custom = Some(value);
150        self
151    }
152    /// Filter rules on the rule name.
153    pub fn filter_rule_name(mut self, value: String) -> Self {
154        self.filter_rule_name = Some(value);
155        self
156    }
157    /// Filter rules on the rule description.
158    pub fn filter_rule_description(mut self, value: String) -> Self {
159        self.filter_rule_description = Some(value);
160        self
161    }
162    /// Return only specific fields in the response for rule attributes.
163    pub fn fields_rule(mut self, value: String) -> Self {
164        self.fields_rule = Some(value);
165        self
166    }
167    /// Return only specific fields in the included response for scorecard attributes.
168    pub fn fields_scorecard(mut self, value: String) -> Self {
169        self.fields_scorecard = Some(value);
170        self
171    }
172}
173
174/// CreateScorecardOutcomesBatchError is a struct for typed errors of method [`ServiceScorecardsAPI::create_scorecard_outcomes_batch`]
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(untagged)]
177pub enum CreateScorecardOutcomesBatchError {
178    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
179    UnknownValue(serde_json::Value),
180}
181
182/// CreateScorecardRuleError is a struct for typed errors of method [`ServiceScorecardsAPI::create_scorecard_rule`]
183#[derive(Debug, Clone, Serialize, Deserialize)]
184#[serde(untagged)]
185pub enum CreateScorecardRuleError {
186    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
187    UnknownValue(serde_json::Value),
188}
189
190/// DeleteScorecardRuleError is a struct for typed errors of method [`ServiceScorecardsAPI::delete_scorecard_rule`]
191#[derive(Debug, Clone, Serialize, Deserialize)]
192#[serde(untagged)]
193pub enum DeleteScorecardRuleError {
194    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
195    UnknownValue(serde_json::Value),
196}
197
198/// ListScorecardOutcomesError is a struct for typed errors of method [`ServiceScorecardsAPI::list_scorecard_outcomes`]
199#[derive(Debug, Clone, Serialize, Deserialize)]
200#[serde(untagged)]
201pub enum ListScorecardOutcomesError {
202    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
203    UnknownValue(serde_json::Value),
204}
205
206/// ListScorecardRulesError is a struct for typed errors of method [`ServiceScorecardsAPI::list_scorecard_rules`]
207#[derive(Debug, Clone, Serialize, Deserialize)]
208#[serde(untagged)]
209pub enum ListScorecardRulesError {
210    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
211    UnknownValue(serde_json::Value),
212}
213
214/// UpdateScorecardOutcomesAsyncError is a struct for typed errors of method [`ServiceScorecardsAPI::update_scorecard_outcomes_async`]
215#[derive(Debug, Clone, Serialize, Deserialize)]
216#[serde(untagged)]
217pub enum UpdateScorecardOutcomesAsyncError {
218    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
219    UnknownValue(serde_json::Value),
220}
221
222/// UpdateScorecardRuleError is a struct for typed errors of method [`ServiceScorecardsAPI::update_scorecard_rule`]
223#[derive(Debug, Clone, Serialize, Deserialize)]
224#[serde(untagged)]
225pub enum UpdateScorecardRuleError {
226    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
227    UnknownValue(serde_json::Value),
228}
229
230/// API to create and update scorecard rules and outcomes. See [Service Scorecards](<https://docs.datadoghq.com/service_catalog/scorecards>) for more information.
231///
232/// This feature is currently in BETA. If you have any feedback, contact [Datadog support](<https://docs.datadoghq.com/help/>).
233#[derive(Debug, Clone)]
234pub struct ServiceScorecardsAPI {
235    config: datadog::Configuration,
236    client: reqwest_middleware::ClientWithMiddleware,
237}
238
239impl Default for ServiceScorecardsAPI {
240    fn default() -> Self {
241        Self::with_config(datadog::Configuration::default())
242    }
243}
244
245impl ServiceScorecardsAPI {
246    pub fn new() -> Self {
247        Self::default()
248    }
249    pub fn with_config(config: datadog::Configuration) -> Self {
250        let mut reqwest_client_builder = reqwest::Client::builder();
251
252        if let Some(proxy_url) = &config.proxy_url {
253            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
254            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
255        }
256
257        let mut middleware_client_builder =
258            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
259
260        if config.enable_retry {
261            struct RetryableStatus;
262            impl reqwest_retry::RetryableStrategy for RetryableStatus {
263                fn handle(
264                    &self,
265                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
266                ) -> Option<reqwest_retry::Retryable> {
267                    match res {
268                        Ok(success) => reqwest_retry::default_on_request_success(success),
269                        Err(_) => None,
270                    }
271                }
272            }
273            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
274                .build_with_max_retries(config.max_retries);
275
276            let retry_middleware =
277                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
278                    backoff_policy,
279                    RetryableStatus,
280                );
281
282            middleware_client_builder = middleware_client_builder.with(retry_middleware);
283        }
284
285        let client = middleware_client_builder.build();
286
287        Self { config, client }
288    }
289
290    pub fn with_client_and_config(
291        config: datadog::Configuration,
292        client: reqwest_middleware::ClientWithMiddleware,
293    ) -> Self {
294        Self { config, client }
295    }
296
297    /// Sets multiple service-rule outcomes in a single batched request.
298    pub async fn create_scorecard_outcomes_batch(
299        &self,
300        body: crate::datadogV2::model::OutcomesBatchRequest,
301    ) -> Result<
302        crate::datadogV2::model::OutcomesBatchResponse,
303        datadog::Error<CreateScorecardOutcomesBatchError>,
304    > {
305        match self
306            .create_scorecard_outcomes_batch_with_http_info(body)
307            .await
308        {
309            Ok(response_content) => {
310                if let Some(e) = response_content.entity {
311                    Ok(e)
312                } else {
313                    Err(datadog::Error::Serde(serde::de::Error::custom(
314                        "response content was None",
315                    )))
316                }
317            }
318            Err(err) => Err(err),
319        }
320    }
321
322    /// Sets multiple service-rule outcomes in a single batched request.
323    pub async fn create_scorecard_outcomes_batch_with_http_info(
324        &self,
325        body: crate::datadogV2::model::OutcomesBatchRequest,
326    ) -> Result<
327        datadog::ResponseContent<crate::datadogV2::model::OutcomesBatchResponse>,
328        datadog::Error<CreateScorecardOutcomesBatchError>,
329    > {
330        let local_configuration = &self.config;
331        let operation_id = "v2.create_scorecard_outcomes_batch";
332        if local_configuration.is_unstable_operation_enabled(operation_id) {
333            warn!("Using unstable operation {operation_id}");
334        } else {
335            let local_error = datadog::UnstableOperationDisabledError {
336                msg: "Operation 'v2.create_scorecard_outcomes_batch' is not enabled".to_string(),
337            };
338            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
339        }
340
341        let local_client = &self.client;
342
343        let local_uri_str = format!(
344            "{}/api/v2/scorecard/outcomes/batch",
345            local_configuration.get_operation_host(operation_id)
346        );
347        let mut local_req_builder =
348            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
349
350        // build headers
351        let mut headers = HeaderMap::new();
352        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
353        headers.insert("Accept", HeaderValue::from_static("application/json"));
354
355        // build user agent
356        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
357            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
358            Err(e) => {
359                log::warn!("Failed to parse user agent header: {e}, falling back to default");
360                headers.insert(
361                    reqwest::header::USER_AGENT,
362                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
363                )
364            }
365        };
366
367        // build auth
368        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
369            headers.insert(
370                "DD-API-KEY",
371                HeaderValue::from_str(local_key.key.as_str())
372                    .expect("failed to parse DD-API-KEY header"),
373            );
374        };
375        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
376            headers.insert(
377                "DD-APPLICATION-KEY",
378                HeaderValue::from_str(local_key.key.as_str())
379                    .expect("failed to parse DD-APPLICATION-KEY header"),
380            );
381        };
382
383        // build body parameters
384        let output = Vec::new();
385        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
386        if body.serialize(&mut ser).is_ok() {
387            if let Some(content_encoding) = headers.get("Content-Encoding") {
388                match content_encoding.to_str().unwrap_or_default() {
389                    "gzip" => {
390                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
391                        let _ = enc.write_all(ser.into_inner().as_slice());
392                        match enc.finish() {
393                            Ok(buf) => {
394                                local_req_builder = local_req_builder.body(buf);
395                            }
396                            Err(e) => return Err(datadog::Error::Io(e)),
397                        }
398                    }
399                    "deflate" => {
400                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
401                        let _ = enc.write_all(ser.into_inner().as_slice());
402                        match enc.finish() {
403                            Ok(buf) => {
404                                local_req_builder = local_req_builder.body(buf);
405                            }
406                            Err(e) => return Err(datadog::Error::Io(e)),
407                        }
408                    }
409                    "zstd1" => {
410                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
411                        let _ = enc.write_all(ser.into_inner().as_slice());
412                        match enc.finish() {
413                            Ok(buf) => {
414                                local_req_builder = local_req_builder.body(buf);
415                            }
416                            Err(e) => return Err(datadog::Error::Io(e)),
417                        }
418                    }
419                    _ => {
420                        local_req_builder = local_req_builder.body(ser.into_inner());
421                    }
422                }
423            } else {
424                local_req_builder = local_req_builder.body(ser.into_inner());
425            }
426        }
427
428        local_req_builder = local_req_builder.headers(headers);
429        let local_req = local_req_builder.build()?;
430        log::debug!("request content: {:?}", local_req.body());
431        let local_resp = local_client.execute(local_req).await?;
432
433        let local_status = local_resp.status();
434        let local_content = local_resp.text().await?;
435        log::debug!("response content: {}", local_content);
436
437        if !local_status.is_client_error() && !local_status.is_server_error() {
438            match serde_json::from_str::<crate::datadogV2::model::OutcomesBatchResponse>(
439                &local_content,
440            ) {
441                Ok(e) => {
442                    return Ok(datadog::ResponseContent {
443                        status: local_status,
444                        content: local_content,
445                        entity: Some(e),
446                    })
447                }
448                Err(e) => return Err(datadog::Error::Serde(e)),
449            };
450        } else {
451            let local_entity: Option<CreateScorecardOutcomesBatchError> =
452                serde_json::from_str(&local_content).ok();
453            let local_error = datadog::ResponseContent {
454                status: local_status,
455                content: local_content,
456                entity: local_entity,
457            };
458            Err(datadog::Error::ResponseError(local_error))
459        }
460    }
461
462    /// Creates a new rule.
463    pub async fn create_scorecard_rule(
464        &self,
465        body: crate::datadogV2::model::CreateRuleRequest,
466    ) -> Result<crate::datadogV2::model::CreateRuleResponse, datadog::Error<CreateScorecardRuleError>>
467    {
468        match self.create_scorecard_rule_with_http_info(body).await {
469            Ok(response_content) => {
470                if let Some(e) = response_content.entity {
471                    Ok(e)
472                } else {
473                    Err(datadog::Error::Serde(serde::de::Error::custom(
474                        "response content was None",
475                    )))
476                }
477            }
478            Err(err) => Err(err),
479        }
480    }
481
482    /// Creates a new rule.
483    pub async fn create_scorecard_rule_with_http_info(
484        &self,
485        body: crate::datadogV2::model::CreateRuleRequest,
486    ) -> Result<
487        datadog::ResponseContent<crate::datadogV2::model::CreateRuleResponse>,
488        datadog::Error<CreateScorecardRuleError>,
489    > {
490        let local_configuration = &self.config;
491        let operation_id = "v2.create_scorecard_rule";
492        if local_configuration.is_unstable_operation_enabled(operation_id) {
493            warn!("Using unstable operation {operation_id}");
494        } else {
495            let local_error = datadog::UnstableOperationDisabledError {
496                msg: "Operation 'v2.create_scorecard_rule' is not enabled".to_string(),
497            };
498            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
499        }
500
501        let local_client = &self.client;
502
503        let local_uri_str = format!(
504            "{}/api/v2/scorecard/rules",
505            local_configuration.get_operation_host(operation_id)
506        );
507        let mut local_req_builder =
508            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
509
510        // build headers
511        let mut headers = HeaderMap::new();
512        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
513        headers.insert("Accept", HeaderValue::from_static("application/json"));
514
515        // build user agent
516        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
517            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
518            Err(e) => {
519                log::warn!("Failed to parse user agent header: {e}, falling back to default");
520                headers.insert(
521                    reqwest::header::USER_AGENT,
522                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
523                )
524            }
525        };
526
527        // build auth
528        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
529            headers.insert(
530                "DD-API-KEY",
531                HeaderValue::from_str(local_key.key.as_str())
532                    .expect("failed to parse DD-API-KEY header"),
533            );
534        };
535        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
536            headers.insert(
537                "DD-APPLICATION-KEY",
538                HeaderValue::from_str(local_key.key.as_str())
539                    .expect("failed to parse DD-APPLICATION-KEY header"),
540            );
541        };
542
543        // build body parameters
544        let output = Vec::new();
545        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
546        if body.serialize(&mut ser).is_ok() {
547            if let Some(content_encoding) = headers.get("Content-Encoding") {
548                match content_encoding.to_str().unwrap_or_default() {
549                    "gzip" => {
550                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
551                        let _ = enc.write_all(ser.into_inner().as_slice());
552                        match enc.finish() {
553                            Ok(buf) => {
554                                local_req_builder = local_req_builder.body(buf);
555                            }
556                            Err(e) => return Err(datadog::Error::Io(e)),
557                        }
558                    }
559                    "deflate" => {
560                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
561                        let _ = enc.write_all(ser.into_inner().as_slice());
562                        match enc.finish() {
563                            Ok(buf) => {
564                                local_req_builder = local_req_builder.body(buf);
565                            }
566                            Err(e) => return Err(datadog::Error::Io(e)),
567                        }
568                    }
569                    "zstd1" => {
570                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
571                        let _ = enc.write_all(ser.into_inner().as_slice());
572                        match enc.finish() {
573                            Ok(buf) => {
574                                local_req_builder = local_req_builder.body(buf);
575                            }
576                            Err(e) => return Err(datadog::Error::Io(e)),
577                        }
578                    }
579                    _ => {
580                        local_req_builder = local_req_builder.body(ser.into_inner());
581                    }
582                }
583            } else {
584                local_req_builder = local_req_builder.body(ser.into_inner());
585            }
586        }
587
588        local_req_builder = local_req_builder.headers(headers);
589        let local_req = local_req_builder.build()?;
590        log::debug!("request content: {:?}", local_req.body());
591        let local_resp = local_client.execute(local_req).await?;
592
593        let local_status = local_resp.status();
594        let local_content = local_resp.text().await?;
595        log::debug!("response content: {}", local_content);
596
597        if !local_status.is_client_error() && !local_status.is_server_error() {
598            match serde_json::from_str::<crate::datadogV2::model::CreateRuleResponse>(
599                &local_content,
600            ) {
601                Ok(e) => {
602                    return Ok(datadog::ResponseContent {
603                        status: local_status,
604                        content: local_content,
605                        entity: Some(e),
606                    })
607                }
608                Err(e) => return Err(datadog::Error::Serde(e)),
609            };
610        } else {
611            let local_entity: Option<CreateScorecardRuleError> =
612                serde_json::from_str(&local_content).ok();
613            let local_error = datadog::ResponseContent {
614                status: local_status,
615                content: local_content,
616                entity: local_entity,
617            };
618            Err(datadog::Error::ResponseError(local_error))
619        }
620    }
621
622    /// Deletes a single rule.
623    pub async fn delete_scorecard_rule(
624        &self,
625        rule_id: String,
626    ) -> Result<(), datadog::Error<DeleteScorecardRuleError>> {
627        match self.delete_scorecard_rule_with_http_info(rule_id).await {
628            Ok(_) => Ok(()),
629            Err(err) => Err(err),
630        }
631    }
632
633    /// Deletes a single rule.
634    pub async fn delete_scorecard_rule_with_http_info(
635        &self,
636        rule_id: String,
637    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteScorecardRuleError>> {
638        let local_configuration = &self.config;
639        let operation_id = "v2.delete_scorecard_rule";
640        if local_configuration.is_unstable_operation_enabled(operation_id) {
641            warn!("Using unstable operation {operation_id}");
642        } else {
643            let local_error = datadog::UnstableOperationDisabledError {
644                msg: "Operation 'v2.delete_scorecard_rule' is not enabled".to_string(),
645            };
646            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
647        }
648
649        let local_client = &self.client;
650
651        let local_uri_str = format!(
652            "{}/api/v2/scorecard/rules/{rule_id}",
653            local_configuration.get_operation_host(operation_id),
654            rule_id = datadog::urlencode(rule_id)
655        );
656        let mut local_req_builder =
657            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
658
659        // build headers
660        let mut headers = HeaderMap::new();
661        headers.insert("Accept", HeaderValue::from_static("*/*"));
662
663        // build user agent
664        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
665            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
666            Err(e) => {
667                log::warn!("Failed to parse user agent header: {e}, falling back to default");
668                headers.insert(
669                    reqwest::header::USER_AGENT,
670                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
671                )
672            }
673        };
674
675        // build auth
676        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
677            headers.insert(
678                "DD-API-KEY",
679                HeaderValue::from_str(local_key.key.as_str())
680                    .expect("failed to parse DD-API-KEY header"),
681            );
682        };
683        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
684            headers.insert(
685                "DD-APPLICATION-KEY",
686                HeaderValue::from_str(local_key.key.as_str())
687                    .expect("failed to parse DD-APPLICATION-KEY header"),
688            );
689        };
690
691        local_req_builder = local_req_builder.headers(headers);
692        let local_req = local_req_builder.build()?;
693        log::debug!("request content: {:?}", local_req.body());
694        let local_resp = local_client.execute(local_req).await?;
695
696        let local_status = local_resp.status();
697        let local_content = local_resp.text().await?;
698        log::debug!("response content: {}", local_content);
699
700        if !local_status.is_client_error() && !local_status.is_server_error() {
701            Ok(datadog::ResponseContent {
702                status: local_status,
703                content: local_content,
704                entity: None,
705            })
706        } else {
707            let local_entity: Option<DeleteScorecardRuleError> =
708                serde_json::from_str(&local_content).ok();
709            let local_error = datadog::ResponseContent {
710                status: local_status,
711                content: local_content,
712                entity: local_entity,
713            };
714            Err(datadog::Error::ResponseError(local_error))
715        }
716    }
717
718    /// Fetches all rule outcomes.
719    pub async fn list_scorecard_outcomes(
720        &self,
721        params: ListScorecardOutcomesOptionalParams,
722    ) -> Result<crate::datadogV2::model::OutcomesResponse, datadog::Error<ListScorecardOutcomesError>>
723    {
724        match self.list_scorecard_outcomes_with_http_info(params).await {
725            Ok(response_content) => {
726                if let Some(e) = response_content.entity {
727                    Ok(e)
728                } else {
729                    Err(datadog::Error::Serde(serde::de::Error::custom(
730                        "response content was None",
731                    )))
732                }
733            }
734            Err(err) => Err(err),
735        }
736    }
737
738    pub fn list_scorecard_outcomes_with_pagination(
739        &self,
740        mut params: ListScorecardOutcomesOptionalParams,
741    ) -> impl Stream<
742        Item = Result<
743            crate::datadogV2::model::OutcomesResponseDataItem,
744            datadog::Error<ListScorecardOutcomesError>,
745        >,
746    > + '_ {
747        try_stream! {
748            let mut page_size: i64 = 10;
749            if params.page_size.is_none() {
750                params.page_size = Some(page_size);
751            } else {
752                page_size = params.page_size.unwrap().clone();
753            }
754            loop {
755                let resp = self.list_scorecard_outcomes(params.clone()).await?;
756                let Some(data) = resp.data else { break };
757
758                let r = data;
759                let count = r.len();
760                for team in r {
761                    yield team;
762                }
763
764                if count < page_size as usize {
765                    break;
766                }
767                if params.page_offset.is_none() {
768                    params.page_offset = Some(page_size.clone());
769                } else {
770                    params.page_offset = Some(params.page_offset.unwrap() + page_size.clone());
771                }
772            }
773        }
774    }
775
776    /// Fetches all rule outcomes.
777    pub async fn list_scorecard_outcomes_with_http_info(
778        &self,
779        params: ListScorecardOutcomesOptionalParams,
780    ) -> Result<
781        datadog::ResponseContent<crate::datadogV2::model::OutcomesResponse>,
782        datadog::Error<ListScorecardOutcomesError>,
783    > {
784        let local_configuration = &self.config;
785        let operation_id = "v2.list_scorecard_outcomes";
786        if local_configuration.is_unstable_operation_enabled(operation_id) {
787            warn!("Using unstable operation {operation_id}");
788        } else {
789            let local_error = datadog::UnstableOperationDisabledError {
790                msg: "Operation 'v2.list_scorecard_outcomes' is not enabled".to_string(),
791            };
792            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
793        }
794
795        // unbox and build optional parameters
796        let page_size = params.page_size;
797        let page_offset = params.page_offset;
798        let include = params.include;
799        let fields_outcome = params.fields_outcome;
800        let fields_rule = params.fields_rule;
801        let filter_outcome_service_name = params.filter_outcome_service_name;
802        let filter_outcome_state = params.filter_outcome_state;
803        let filter_rule_enabled = params.filter_rule_enabled;
804        let filter_rule_id = params.filter_rule_id;
805        let filter_rule_name = params.filter_rule_name;
806
807        let local_client = &self.client;
808
809        let local_uri_str = format!(
810            "{}/api/v2/scorecard/outcomes",
811            local_configuration.get_operation_host(operation_id)
812        );
813        let mut local_req_builder =
814            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
815
816        if let Some(ref local_query_param) = page_size {
817            local_req_builder =
818                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
819        };
820        if let Some(ref local_query_param) = page_offset {
821            local_req_builder =
822                local_req_builder.query(&[("page[offset]", &local_query_param.to_string())]);
823        };
824        if let Some(ref local_query_param) = include {
825            local_req_builder =
826                local_req_builder.query(&[("include", &local_query_param.to_string())]);
827        };
828        if let Some(ref local_query_param) = fields_outcome {
829            local_req_builder =
830                local_req_builder.query(&[("fields[outcome]", &local_query_param.to_string())]);
831        };
832        if let Some(ref local_query_param) = fields_rule {
833            local_req_builder =
834                local_req_builder.query(&[("fields[rule]", &local_query_param.to_string())]);
835        };
836        if let Some(ref local_query_param) = filter_outcome_service_name {
837            local_req_builder = local_req_builder.query(&[(
838                "filter[outcome][service_name]",
839                &local_query_param.to_string(),
840            )]);
841        };
842        if let Some(ref local_query_param) = filter_outcome_state {
843            local_req_builder = local_req_builder
844                .query(&[("filter[outcome][state]", &local_query_param.to_string())]);
845        };
846        if let Some(ref local_query_param) = filter_rule_enabled {
847            local_req_builder = local_req_builder
848                .query(&[("filter[rule][enabled]", &local_query_param.to_string())]);
849        };
850        if let Some(ref local_query_param) = filter_rule_id {
851            local_req_builder =
852                local_req_builder.query(&[("filter[rule][id]", &local_query_param.to_string())]);
853        };
854        if let Some(ref local_query_param) = filter_rule_name {
855            local_req_builder =
856                local_req_builder.query(&[("filter[rule][name]", &local_query_param.to_string())]);
857        };
858
859        // build headers
860        let mut headers = HeaderMap::new();
861        headers.insert("Accept", HeaderValue::from_static("application/json"));
862
863        // build user agent
864        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
865            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
866            Err(e) => {
867                log::warn!("Failed to parse user agent header: {e}, falling back to default");
868                headers.insert(
869                    reqwest::header::USER_AGENT,
870                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
871                )
872            }
873        };
874
875        // build auth
876        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
877            headers.insert(
878                "DD-API-KEY",
879                HeaderValue::from_str(local_key.key.as_str())
880                    .expect("failed to parse DD-API-KEY header"),
881            );
882        };
883        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
884            headers.insert(
885                "DD-APPLICATION-KEY",
886                HeaderValue::from_str(local_key.key.as_str())
887                    .expect("failed to parse DD-APPLICATION-KEY header"),
888            );
889        };
890
891        local_req_builder = local_req_builder.headers(headers);
892        let local_req = local_req_builder.build()?;
893        log::debug!("request content: {:?}", local_req.body());
894        let local_resp = local_client.execute(local_req).await?;
895
896        let local_status = local_resp.status();
897        let local_content = local_resp.text().await?;
898        log::debug!("response content: {}", local_content);
899
900        if !local_status.is_client_error() && !local_status.is_server_error() {
901            match serde_json::from_str::<crate::datadogV2::model::OutcomesResponse>(&local_content)
902            {
903                Ok(e) => {
904                    return Ok(datadog::ResponseContent {
905                        status: local_status,
906                        content: local_content,
907                        entity: Some(e),
908                    })
909                }
910                Err(e) => return Err(datadog::Error::Serde(e)),
911            };
912        } else {
913            let local_entity: Option<ListScorecardOutcomesError> =
914                serde_json::from_str(&local_content).ok();
915            let local_error = datadog::ResponseContent {
916                status: local_status,
917                content: local_content,
918                entity: local_entity,
919            };
920            Err(datadog::Error::ResponseError(local_error))
921        }
922    }
923
924    /// Fetch all rules.
925    pub async fn list_scorecard_rules(
926        &self,
927        params: ListScorecardRulesOptionalParams,
928    ) -> Result<crate::datadogV2::model::ListRulesResponse, datadog::Error<ListScorecardRulesError>>
929    {
930        match self.list_scorecard_rules_with_http_info(params).await {
931            Ok(response_content) => {
932                if let Some(e) = response_content.entity {
933                    Ok(e)
934                } else {
935                    Err(datadog::Error::Serde(serde::de::Error::custom(
936                        "response content was None",
937                    )))
938                }
939            }
940            Err(err) => Err(err),
941        }
942    }
943
944    pub fn list_scorecard_rules_with_pagination(
945        &self,
946        mut params: ListScorecardRulesOptionalParams,
947    ) -> impl Stream<
948        Item = Result<
949            crate::datadogV2::model::ListRulesResponseDataItem,
950            datadog::Error<ListScorecardRulesError>,
951        >,
952    > + '_ {
953        try_stream! {
954            let mut page_size: i64 = 10;
955            if params.page_size.is_none() {
956                params.page_size = Some(page_size);
957            } else {
958                page_size = params.page_size.unwrap().clone();
959            }
960            loop {
961                let resp = self.list_scorecard_rules(params.clone()).await?;
962                let Some(data) = resp.data else { break };
963
964                let r = data;
965                let count = r.len();
966                for team in r {
967                    yield team;
968                }
969
970                if count < page_size as usize {
971                    break;
972                }
973                if params.page_offset.is_none() {
974                    params.page_offset = Some(page_size.clone());
975                } else {
976                    params.page_offset = Some(params.page_offset.unwrap() + page_size.clone());
977                }
978            }
979        }
980    }
981
982    /// Fetch all rules.
983    pub async fn list_scorecard_rules_with_http_info(
984        &self,
985        params: ListScorecardRulesOptionalParams,
986    ) -> Result<
987        datadog::ResponseContent<crate::datadogV2::model::ListRulesResponse>,
988        datadog::Error<ListScorecardRulesError>,
989    > {
990        let local_configuration = &self.config;
991        let operation_id = "v2.list_scorecard_rules";
992        if local_configuration.is_unstable_operation_enabled(operation_id) {
993            warn!("Using unstable operation {operation_id}");
994        } else {
995            let local_error = datadog::UnstableOperationDisabledError {
996                msg: "Operation 'v2.list_scorecard_rules' is not enabled".to_string(),
997            };
998            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
999        }
1000
1001        // unbox and build optional parameters
1002        let page_size = params.page_size;
1003        let page_offset = params.page_offset;
1004        let include = params.include;
1005        let filter_rule_id = params.filter_rule_id;
1006        let filter_rule_enabled = params.filter_rule_enabled;
1007        let filter_rule_custom = params.filter_rule_custom;
1008        let filter_rule_name = params.filter_rule_name;
1009        let filter_rule_description = params.filter_rule_description;
1010        let fields_rule = params.fields_rule;
1011        let fields_scorecard = params.fields_scorecard;
1012
1013        let local_client = &self.client;
1014
1015        let local_uri_str = format!(
1016            "{}/api/v2/scorecard/rules",
1017            local_configuration.get_operation_host(operation_id)
1018        );
1019        let mut local_req_builder =
1020            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1021
1022        if let Some(ref local_query_param) = page_size {
1023            local_req_builder =
1024                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
1025        };
1026        if let Some(ref local_query_param) = page_offset {
1027            local_req_builder =
1028                local_req_builder.query(&[("page[offset]", &local_query_param.to_string())]);
1029        };
1030        if let Some(ref local_query_param) = include {
1031            local_req_builder =
1032                local_req_builder.query(&[("include", &local_query_param.to_string())]);
1033        };
1034        if let Some(ref local_query_param) = filter_rule_id {
1035            local_req_builder =
1036                local_req_builder.query(&[("filter[rule][id]", &local_query_param.to_string())]);
1037        };
1038        if let Some(ref local_query_param) = filter_rule_enabled {
1039            local_req_builder = local_req_builder
1040                .query(&[("filter[rule][enabled]", &local_query_param.to_string())]);
1041        };
1042        if let Some(ref local_query_param) = filter_rule_custom {
1043            local_req_builder = local_req_builder
1044                .query(&[("filter[rule][custom]", &local_query_param.to_string())]);
1045        };
1046        if let Some(ref local_query_param) = filter_rule_name {
1047            local_req_builder =
1048                local_req_builder.query(&[("filter[rule][name]", &local_query_param.to_string())]);
1049        };
1050        if let Some(ref local_query_param) = filter_rule_description {
1051            local_req_builder = local_req_builder
1052                .query(&[("filter[rule][description]", &local_query_param.to_string())]);
1053        };
1054        if let Some(ref local_query_param) = fields_rule {
1055            local_req_builder =
1056                local_req_builder.query(&[("fields[rule]", &local_query_param.to_string())]);
1057        };
1058        if let Some(ref local_query_param) = fields_scorecard {
1059            local_req_builder =
1060                local_req_builder.query(&[("fields[scorecard]", &local_query_param.to_string())]);
1061        };
1062
1063        // build headers
1064        let mut headers = HeaderMap::new();
1065        headers.insert("Accept", HeaderValue::from_static("application/json"));
1066
1067        // build user agent
1068        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1069            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1070            Err(e) => {
1071                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1072                headers.insert(
1073                    reqwest::header::USER_AGENT,
1074                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1075                )
1076            }
1077        };
1078
1079        // build auth
1080        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1081            headers.insert(
1082                "DD-API-KEY",
1083                HeaderValue::from_str(local_key.key.as_str())
1084                    .expect("failed to parse DD-API-KEY header"),
1085            );
1086        };
1087        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1088            headers.insert(
1089                "DD-APPLICATION-KEY",
1090                HeaderValue::from_str(local_key.key.as_str())
1091                    .expect("failed to parse DD-APPLICATION-KEY header"),
1092            );
1093        };
1094
1095        local_req_builder = local_req_builder.headers(headers);
1096        let local_req = local_req_builder.build()?;
1097        log::debug!("request content: {:?}", local_req.body());
1098        let local_resp = local_client.execute(local_req).await?;
1099
1100        let local_status = local_resp.status();
1101        let local_content = local_resp.text().await?;
1102        log::debug!("response content: {}", local_content);
1103
1104        if !local_status.is_client_error() && !local_status.is_server_error() {
1105            match serde_json::from_str::<crate::datadogV2::model::ListRulesResponse>(&local_content)
1106            {
1107                Ok(e) => {
1108                    return Ok(datadog::ResponseContent {
1109                        status: local_status,
1110                        content: local_content,
1111                        entity: Some(e),
1112                    })
1113                }
1114                Err(e) => return Err(datadog::Error::Serde(e)),
1115            };
1116        } else {
1117            let local_entity: Option<ListScorecardRulesError> =
1118                serde_json::from_str(&local_content).ok();
1119            let local_error = datadog::ResponseContent {
1120                status: local_status,
1121                content: local_content,
1122                entity: local_entity,
1123            };
1124            Err(datadog::Error::ResponseError(local_error))
1125        }
1126    }
1127
1128    /// Updates multiple scorecard rule outcomes in a single batched request.
1129    pub async fn update_scorecard_outcomes_async(
1130        &self,
1131        body: crate::datadogV2::model::UpdateOutcomesAsyncRequest,
1132    ) -> Result<(), datadog::Error<UpdateScorecardOutcomesAsyncError>> {
1133        match self
1134            .update_scorecard_outcomes_async_with_http_info(body)
1135            .await
1136        {
1137            Ok(_) => Ok(()),
1138            Err(err) => Err(err),
1139        }
1140    }
1141
1142    /// Updates multiple scorecard rule outcomes in a single batched request.
1143    pub async fn update_scorecard_outcomes_async_with_http_info(
1144        &self,
1145        body: crate::datadogV2::model::UpdateOutcomesAsyncRequest,
1146    ) -> Result<datadog::ResponseContent<()>, datadog::Error<UpdateScorecardOutcomesAsyncError>>
1147    {
1148        let local_configuration = &self.config;
1149        let operation_id = "v2.update_scorecard_outcomes_async";
1150        if local_configuration.is_unstable_operation_enabled(operation_id) {
1151            warn!("Using unstable operation {operation_id}");
1152        } else {
1153            let local_error = datadog::UnstableOperationDisabledError {
1154                msg: "Operation 'v2.update_scorecard_outcomes_async' is not enabled".to_string(),
1155            };
1156            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
1157        }
1158
1159        let local_client = &self.client;
1160
1161        let local_uri_str = format!(
1162            "{}/api/v2/scorecard/outcomes",
1163            local_configuration.get_operation_host(operation_id)
1164        );
1165        let mut local_req_builder =
1166            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
1167
1168        // build headers
1169        let mut headers = HeaderMap::new();
1170        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1171        headers.insert("Accept", HeaderValue::from_static("*/*"));
1172
1173        // build user agent
1174        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1175            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1176            Err(e) => {
1177                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1178                headers.insert(
1179                    reqwest::header::USER_AGENT,
1180                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1181                )
1182            }
1183        };
1184
1185        // build auth
1186        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1187            headers.insert(
1188                "DD-API-KEY",
1189                HeaderValue::from_str(local_key.key.as_str())
1190                    .expect("failed to parse DD-API-KEY header"),
1191            );
1192        };
1193        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1194            headers.insert(
1195                "DD-APPLICATION-KEY",
1196                HeaderValue::from_str(local_key.key.as_str())
1197                    .expect("failed to parse DD-APPLICATION-KEY header"),
1198            );
1199        };
1200
1201        // build body parameters
1202        let output = Vec::new();
1203        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1204        if body.serialize(&mut ser).is_ok() {
1205            if let Some(content_encoding) = headers.get("Content-Encoding") {
1206                match content_encoding.to_str().unwrap_or_default() {
1207                    "gzip" => {
1208                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1209                        let _ = enc.write_all(ser.into_inner().as_slice());
1210                        match enc.finish() {
1211                            Ok(buf) => {
1212                                local_req_builder = local_req_builder.body(buf);
1213                            }
1214                            Err(e) => return Err(datadog::Error::Io(e)),
1215                        }
1216                    }
1217                    "deflate" => {
1218                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1219                        let _ = enc.write_all(ser.into_inner().as_slice());
1220                        match enc.finish() {
1221                            Ok(buf) => {
1222                                local_req_builder = local_req_builder.body(buf);
1223                            }
1224                            Err(e) => return Err(datadog::Error::Io(e)),
1225                        }
1226                    }
1227                    "zstd1" => {
1228                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1229                        let _ = enc.write_all(ser.into_inner().as_slice());
1230                        match enc.finish() {
1231                            Ok(buf) => {
1232                                local_req_builder = local_req_builder.body(buf);
1233                            }
1234                            Err(e) => return Err(datadog::Error::Io(e)),
1235                        }
1236                    }
1237                    _ => {
1238                        local_req_builder = local_req_builder.body(ser.into_inner());
1239                    }
1240                }
1241            } else {
1242                local_req_builder = local_req_builder.body(ser.into_inner());
1243            }
1244        }
1245
1246        local_req_builder = local_req_builder.headers(headers);
1247        let local_req = local_req_builder.build()?;
1248        log::debug!("request content: {:?}", local_req.body());
1249        let local_resp = local_client.execute(local_req).await?;
1250
1251        let local_status = local_resp.status();
1252        let local_content = local_resp.text().await?;
1253        log::debug!("response content: {}", local_content);
1254
1255        if !local_status.is_client_error() && !local_status.is_server_error() {
1256            Ok(datadog::ResponseContent {
1257                status: local_status,
1258                content: local_content,
1259                entity: None,
1260            })
1261        } else {
1262            let local_entity: Option<UpdateScorecardOutcomesAsyncError> =
1263                serde_json::from_str(&local_content).ok();
1264            let local_error = datadog::ResponseContent {
1265                status: local_status,
1266                content: local_content,
1267                entity: local_entity,
1268            };
1269            Err(datadog::Error::ResponseError(local_error))
1270        }
1271    }
1272
1273    /// Updates an existing rule.
1274    pub async fn update_scorecard_rule(
1275        &self,
1276        rule_id: String,
1277        body: crate::datadogV2::model::UpdateRuleRequest,
1278    ) -> Result<crate::datadogV2::model::UpdateRuleResponse, datadog::Error<UpdateScorecardRuleError>>
1279    {
1280        match self
1281            .update_scorecard_rule_with_http_info(rule_id, body)
1282            .await
1283        {
1284            Ok(response_content) => {
1285                if let Some(e) = response_content.entity {
1286                    Ok(e)
1287                } else {
1288                    Err(datadog::Error::Serde(serde::de::Error::custom(
1289                        "response content was None",
1290                    )))
1291                }
1292            }
1293            Err(err) => Err(err),
1294        }
1295    }
1296
1297    /// Updates an existing rule.
1298    pub async fn update_scorecard_rule_with_http_info(
1299        &self,
1300        rule_id: String,
1301        body: crate::datadogV2::model::UpdateRuleRequest,
1302    ) -> Result<
1303        datadog::ResponseContent<crate::datadogV2::model::UpdateRuleResponse>,
1304        datadog::Error<UpdateScorecardRuleError>,
1305    > {
1306        let local_configuration = &self.config;
1307        let operation_id = "v2.update_scorecard_rule";
1308        if local_configuration.is_unstable_operation_enabled(operation_id) {
1309            warn!("Using unstable operation {operation_id}");
1310        } else {
1311            let local_error = datadog::UnstableOperationDisabledError {
1312                msg: "Operation 'v2.update_scorecard_rule' is not enabled".to_string(),
1313            };
1314            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
1315        }
1316
1317        let local_client = &self.client;
1318
1319        let local_uri_str = format!(
1320            "{}/api/v2/scorecard/rules/{rule_id}",
1321            local_configuration.get_operation_host(operation_id),
1322            rule_id = datadog::urlencode(rule_id)
1323        );
1324        let mut local_req_builder =
1325            local_client.request(reqwest::Method::PUT, local_uri_str.as_str());
1326
1327        // build headers
1328        let mut headers = HeaderMap::new();
1329        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1330        headers.insert("Accept", HeaderValue::from_static("application/json"));
1331
1332        // build user agent
1333        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1334            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1335            Err(e) => {
1336                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1337                headers.insert(
1338                    reqwest::header::USER_AGENT,
1339                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1340                )
1341            }
1342        };
1343
1344        // build auth
1345        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1346            headers.insert(
1347                "DD-API-KEY",
1348                HeaderValue::from_str(local_key.key.as_str())
1349                    .expect("failed to parse DD-API-KEY header"),
1350            );
1351        };
1352        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1353            headers.insert(
1354                "DD-APPLICATION-KEY",
1355                HeaderValue::from_str(local_key.key.as_str())
1356                    .expect("failed to parse DD-APPLICATION-KEY header"),
1357            );
1358        };
1359
1360        // build body parameters
1361        let output = Vec::new();
1362        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1363        if body.serialize(&mut ser).is_ok() {
1364            if let Some(content_encoding) = headers.get("Content-Encoding") {
1365                match content_encoding.to_str().unwrap_or_default() {
1366                    "gzip" => {
1367                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1368                        let _ = enc.write_all(ser.into_inner().as_slice());
1369                        match enc.finish() {
1370                            Ok(buf) => {
1371                                local_req_builder = local_req_builder.body(buf);
1372                            }
1373                            Err(e) => return Err(datadog::Error::Io(e)),
1374                        }
1375                    }
1376                    "deflate" => {
1377                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1378                        let _ = enc.write_all(ser.into_inner().as_slice());
1379                        match enc.finish() {
1380                            Ok(buf) => {
1381                                local_req_builder = local_req_builder.body(buf);
1382                            }
1383                            Err(e) => return Err(datadog::Error::Io(e)),
1384                        }
1385                    }
1386                    "zstd1" => {
1387                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1388                        let _ = enc.write_all(ser.into_inner().as_slice());
1389                        match enc.finish() {
1390                            Ok(buf) => {
1391                                local_req_builder = local_req_builder.body(buf);
1392                            }
1393                            Err(e) => return Err(datadog::Error::Io(e)),
1394                        }
1395                    }
1396                    _ => {
1397                        local_req_builder = local_req_builder.body(ser.into_inner());
1398                    }
1399                }
1400            } else {
1401                local_req_builder = local_req_builder.body(ser.into_inner());
1402            }
1403        }
1404
1405        local_req_builder = local_req_builder.headers(headers);
1406        let local_req = local_req_builder.build()?;
1407        log::debug!("request content: {:?}", local_req.body());
1408        let local_resp = local_client.execute(local_req).await?;
1409
1410        let local_status = local_resp.status();
1411        let local_content = local_resp.text().await?;
1412        log::debug!("response content: {}", local_content);
1413
1414        if !local_status.is_client_error() && !local_status.is_server_error() {
1415            match serde_json::from_str::<crate::datadogV2::model::UpdateRuleResponse>(
1416                &local_content,
1417            ) {
1418                Ok(e) => {
1419                    return Ok(datadog::ResponseContent {
1420                        status: local_status,
1421                        content: local_content,
1422                        entity: Some(e),
1423                    })
1424                }
1425                Err(e) => return Err(datadog::Error::Serde(e)),
1426            };
1427        } else {
1428            let local_entity: Option<UpdateScorecardRuleError> =
1429                serde_json::from_str(&local_content).ok();
1430            let local_error = datadog::ResponseContent {
1431                status: local_status,
1432                content: local_content,
1433                entity: local_entity,
1434            };
1435            Err(datadog::Error::ResponseError(local_error))
1436        }
1437    }
1438}