datadog_api_client/datadogV2/api/
api_metrics.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 reqwest::header::{HeaderMap, HeaderValue};
12use serde::{Deserialize, Serialize};
13use std::io::Write;
14
15/// EstimateMetricsOutputSeriesOptionalParams is a struct for passing parameters to the method [`MetricsAPI::estimate_metrics_output_series`]
16#[non_exhaustive]
17#[derive(Clone, Default, Debug)]
18pub struct EstimateMetricsOutputSeriesOptionalParams {
19    /// Filtered tag keys that the metric is configured to query with.
20    pub filter_groups: Option<String>,
21    /// The number of hours of look back (from now) to estimate cardinality with. If unspecified, it defaults to 0 hours.
22    pub filter_hours_ago: Option<i32>,
23    /// Deprecated. Number of aggregations has no impact on volume.
24    pub filter_num_aggregations: Option<i32>,
25    /// A boolean, for distribution metrics only, to estimate cardinality if the metric includes additional percentile aggregators.
26    pub filter_pct: Option<bool>,
27    /// A window, in hours, from the look back to estimate cardinality with. The minimum and default is 1 hour.
28    pub filter_timespan_h: Option<i32>,
29}
30
31impl EstimateMetricsOutputSeriesOptionalParams {
32    /// Filtered tag keys that the metric is configured to query with.
33    pub fn filter_groups(mut self, value: String) -> Self {
34        self.filter_groups = Some(value);
35        self
36    }
37    /// The number of hours of look back (from now) to estimate cardinality with. If unspecified, it defaults to 0 hours.
38    pub fn filter_hours_ago(mut self, value: i32) -> Self {
39        self.filter_hours_ago = Some(value);
40        self
41    }
42    /// Deprecated. Number of aggregations has no impact on volume.
43    pub fn filter_num_aggregations(mut self, value: i32) -> Self {
44        self.filter_num_aggregations = Some(value);
45        self
46    }
47    /// A boolean, for distribution metrics only, to estimate cardinality if the metric includes additional percentile aggregators.
48    pub fn filter_pct(mut self, value: bool) -> Self {
49        self.filter_pct = Some(value);
50        self
51    }
52    /// A window, in hours, from the look back to estimate cardinality with. The minimum and default is 1 hour.
53    pub fn filter_timespan_h(mut self, value: i32) -> Self {
54        self.filter_timespan_h = Some(value);
55        self
56    }
57}
58
59/// ListActiveMetricConfigurationsOptionalParams is a struct for passing parameters to the method [`MetricsAPI::list_active_metric_configurations`]
60#[non_exhaustive]
61#[derive(Clone, Default, Debug)]
62pub struct ListActiveMetricConfigurationsOptionalParams {
63    /// The number of seconds of look back (from now).
64    /// Default value is 604,800 (1 week), minimum value is 7200 (2 hours), maximum value is 2,630,000 (1 month).
65    pub window_seconds: Option<i64>,
66}
67
68impl ListActiveMetricConfigurationsOptionalParams {
69    /// The number of seconds of look back (from now).
70    /// Default value is 604,800 (1 week), minimum value is 7200 (2 hours), maximum value is 2,630,000 (1 month).
71    pub fn window_seconds(mut self, value: i64) -> Self {
72        self.window_seconds = Some(value);
73        self
74    }
75}
76
77/// ListTagConfigurationsOptionalParams is a struct for passing parameters to the method [`MetricsAPI::list_tag_configurations`]
78#[non_exhaustive]
79#[derive(Clone, Default, Debug)]
80pub struct ListTagConfigurationsOptionalParams {
81    /// Filter custom metrics that have configured tags.
82    pub filter_configured: Option<bool>,
83    /// Filter tag configurations by configured tags.
84    pub filter_tags_configured: Option<String>,
85    /// Filter metrics by metric type.
86    pub filter_metric_type:
87        Option<crate::datadogV2::model::MetricTagConfigurationMetricTypeCategory>,
88    /// Filter distributions with additional percentile
89    /// aggregations enabled or disabled.
90    pub filter_include_percentiles: Option<bool>,
91    /// (Preview) Filter custom metrics that have or have not been queried in the specified window[seconds].
92    /// If no window is provided or the window is less than 2 hours, a default of 2 hours will be applied.
93    pub filter_queried: Option<bool>,
94    /// Filter metrics that have been submitted with the given tags. Supports boolean and wildcard expressions.
95    /// Can only be combined with the filter[queried] filter.
96    pub filter_tags: Option<String>,
97    /// (Preview) Filter metrics that are used in dashboards, monitors, notebooks, SLOs.
98    pub filter_related_assets: Option<bool>,
99    /// The number of seconds of look back (from now) to apply to a filter[tag] or filter[queried] query.
100    /// Default value is 3600 (1 hour), maximum value is 2,592,000 (30 days).
101    pub window_seconds: Option<i64>,
102    /// Maximum number of results returned.
103    pub page_size: Option<i32>,
104    /// String to query the next page of results.
105    /// This key is provided with each valid response from the API in `meta.pagination.next_cursor`.
106    /// Once the `meta.pagination.next_cursor` key is null, all pages have been retrieved.
107    pub page_cursor: Option<String>,
108}
109
110impl ListTagConfigurationsOptionalParams {
111    /// Filter custom metrics that have configured tags.
112    pub fn filter_configured(mut self, value: bool) -> Self {
113        self.filter_configured = Some(value);
114        self
115    }
116    /// Filter tag configurations by configured tags.
117    pub fn filter_tags_configured(mut self, value: String) -> Self {
118        self.filter_tags_configured = Some(value);
119        self
120    }
121    /// Filter metrics by metric type.
122    pub fn filter_metric_type(
123        mut self,
124        value: crate::datadogV2::model::MetricTagConfigurationMetricTypeCategory,
125    ) -> Self {
126        self.filter_metric_type = Some(value);
127        self
128    }
129    /// Filter distributions with additional percentile
130    /// aggregations enabled or disabled.
131    pub fn filter_include_percentiles(mut self, value: bool) -> Self {
132        self.filter_include_percentiles = Some(value);
133        self
134    }
135    /// (Preview) Filter custom metrics that have or have not been queried in the specified window[seconds].
136    /// If no window is provided or the window is less than 2 hours, a default of 2 hours will be applied.
137    pub fn filter_queried(mut self, value: bool) -> Self {
138        self.filter_queried = Some(value);
139        self
140    }
141    /// Filter metrics that have been submitted with the given tags. Supports boolean and wildcard expressions.
142    /// Can only be combined with the filter[queried] filter.
143    pub fn filter_tags(mut self, value: String) -> Self {
144        self.filter_tags = Some(value);
145        self
146    }
147    /// (Preview) Filter metrics that are used in dashboards, monitors, notebooks, SLOs.
148    pub fn filter_related_assets(mut self, value: bool) -> Self {
149        self.filter_related_assets = Some(value);
150        self
151    }
152    /// The number of seconds of look back (from now) to apply to a filter[tag] or filter[queried] query.
153    /// Default value is 3600 (1 hour), maximum value is 2,592,000 (30 days).
154    pub fn window_seconds(mut self, value: i64) -> Self {
155        self.window_seconds = Some(value);
156        self
157    }
158    /// Maximum number of results returned.
159    pub fn page_size(mut self, value: i32) -> Self {
160        self.page_size = Some(value);
161        self
162    }
163    /// String to query the next page of results.
164    /// This key is provided with each valid response from the API in `meta.pagination.next_cursor`.
165    /// Once the `meta.pagination.next_cursor` key is null, all pages have been retrieved.
166    pub fn page_cursor(mut self, value: String) -> Self {
167        self.page_cursor = Some(value);
168        self
169    }
170}
171
172/// SubmitMetricsOptionalParams is a struct for passing parameters to the method [`MetricsAPI::submit_metrics`]
173#[non_exhaustive]
174#[derive(Clone, Default, Debug)]
175pub struct SubmitMetricsOptionalParams {
176    /// HTTP header used to compress the media-type.
177    pub content_encoding: Option<crate::datadogV2::model::MetricContentEncoding>,
178}
179
180impl SubmitMetricsOptionalParams {
181    /// HTTP header used to compress the media-type.
182    pub fn content_encoding(
183        mut self,
184        value: crate::datadogV2::model::MetricContentEncoding,
185    ) -> Self {
186        self.content_encoding = Some(value);
187        self
188    }
189}
190
191/// CreateBulkTagsMetricsConfigurationError is a struct for typed errors of method [`MetricsAPI::create_bulk_tags_metrics_configuration`]
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(untagged)]
194pub enum CreateBulkTagsMetricsConfigurationError {
195    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
196    UnknownValue(serde_json::Value),
197}
198
199/// CreateTagConfigurationError is a struct for typed errors of method [`MetricsAPI::create_tag_configuration`]
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[serde(untagged)]
202pub enum CreateTagConfigurationError {
203    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
204    UnknownValue(serde_json::Value),
205}
206
207/// DeleteBulkTagsMetricsConfigurationError is a struct for typed errors of method [`MetricsAPI::delete_bulk_tags_metrics_configuration`]
208#[derive(Debug, Clone, Serialize, Deserialize)]
209#[serde(untagged)]
210pub enum DeleteBulkTagsMetricsConfigurationError {
211    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
212    UnknownValue(serde_json::Value),
213}
214
215/// DeleteTagConfigurationError is a struct for typed errors of method [`MetricsAPI::delete_tag_configuration`]
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(untagged)]
218pub enum DeleteTagConfigurationError {
219    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
220    UnknownValue(serde_json::Value),
221}
222
223/// EstimateMetricsOutputSeriesError is a struct for typed errors of method [`MetricsAPI::estimate_metrics_output_series`]
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(untagged)]
226pub enum EstimateMetricsOutputSeriesError {
227    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
228    UnknownValue(serde_json::Value),
229}
230
231/// GetMetricTagCardinalityDetailsError is a struct for typed errors of method [`MetricsAPI::get_metric_tag_cardinality_details`]
232#[derive(Debug, Clone, Serialize, Deserialize)]
233#[serde(untagged)]
234pub enum GetMetricTagCardinalityDetailsError {
235    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
236    UnknownValue(serde_json::Value),
237}
238
239/// ListActiveMetricConfigurationsError is a struct for typed errors of method [`MetricsAPI::list_active_metric_configurations`]
240#[derive(Debug, Clone, Serialize, Deserialize)]
241#[serde(untagged)]
242pub enum ListActiveMetricConfigurationsError {
243    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
244    UnknownValue(serde_json::Value),
245}
246
247/// ListMetricAssetsError is a struct for typed errors of method [`MetricsAPI::list_metric_assets`]
248#[derive(Debug, Clone, Serialize, Deserialize)]
249#[serde(untagged)]
250pub enum ListMetricAssetsError {
251    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
252    UnknownValue(serde_json::Value),
253}
254
255/// ListTagConfigurationByNameError is a struct for typed errors of method [`MetricsAPI::list_tag_configuration_by_name`]
256#[derive(Debug, Clone, Serialize, Deserialize)]
257#[serde(untagged)]
258pub enum ListTagConfigurationByNameError {
259    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
260    UnknownValue(serde_json::Value),
261}
262
263/// ListTagConfigurationsError is a struct for typed errors of method [`MetricsAPI::list_tag_configurations`]
264#[derive(Debug, Clone, Serialize, Deserialize)]
265#[serde(untagged)]
266pub enum ListTagConfigurationsError {
267    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
268    UnknownValue(serde_json::Value),
269}
270
271/// ListTagsByMetricNameError is a struct for typed errors of method [`MetricsAPI::list_tags_by_metric_name`]
272#[derive(Debug, Clone, Serialize, Deserialize)]
273#[serde(untagged)]
274pub enum ListTagsByMetricNameError {
275    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
276    UnknownValue(serde_json::Value),
277}
278
279/// ListVolumesByMetricNameError is a struct for typed errors of method [`MetricsAPI::list_volumes_by_metric_name`]
280#[derive(Debug, Clone, Serialize, Deserialize)]
281#[serde(untagged)]
282pub enum ListVolumesByMetricNameError {
283    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
284    UnknownValue(serde_json::Value),
285}
286
287/// QueryScalarDataError is a struct for typed errors of method [`MetricsAPI::query_scalar_data`]
288#[derive(Debug, Clone, Serialize, Deserialize)]
289#[serde(untagged)]
290pub enum QueryScalarDataError {
291    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
292    UnknownValue(serde_json::Value),
293}
294
295/// QueryTimeseriesDataError is a struct for typed errors of method [`MetricsAPI::query_timeseries_data`]
296#[derive(Debug, Clone, Serialize, Deserialize)]
297#[serde(untagged)]
298pub enum QueryTimeseriesDataError {
299    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
300    UnknownValue(serde_json::Value),
301}
302
303/// SubmitMetricsError is a struct for typed errors of method [`MetricsAPI::submit_metrics`]
304#[derive(Debug, Clone, Serialize, Deserialize)]
305#[serde(untagged)]
306pub enum SubmitMetricsError {
307    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
308    UnknownValue(serde_json::Value),
309}
310
311/// UpdateTagConfigurationError is a struct for typed errors of method [`MetricsAPI::update_tag_configuration`]
312#[derive(Debug, Clone, Serialize, Deserialize)]
313#[serde(untagged)]
314pub enum UpdateTagConfigurationError {
315    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
316    UnknownValue(serde_json::Value),
317}
318
319/// The metrics endpoint allows you to:
320///
321/// - Post metrics data so it can be graphed on Datadog’s dashboards
322/// - Query metrics from any time period (timeseries and scalar)
323/// - Modify tag configurations for metrics
324/// - View tags and volumes for metrics
325///
326/// **Note**: A graph can only contain a set number of points
327/// and as the timeframe over which a metric is viewed increases,
328/// aggregation between points occurs to stay below that set number.
329///
330/// The Post, Patch, and Delete `manage_tags` API methods can only be performed by
331/// a user who has the `Manage Tags for Metrics` permission.
332///
333/// See the [Metrics page](<https://docs.datadoghq.com/metrics/>) for more information.
334#[derive(Debug, Clone)]
335pub struct MetricsAPI {
336    config: datadog::Configuration,
337    client: reqwest_middleware::ClientWithMiddleware,
338}
339
340impl Default for MetricsAPI {
341    fn default() -> Self {
342        Self::with_config(datadog::Configuration::default())
343    }
344}
345
346impl MetricsAPI {
347    pub fn new() -> Self {
348        Self::default()
349    }
350    pub fn with_config(config: datadog::Configuration) -> Self {
351        let mut reqwest_client_builder = reqwest::Client::builder();
352
353        if let Some(proxy_url) = &config.proxy_url {
354            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
355            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
356        }
357
358        let mut middleware_client_builder =
359            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
360
361        if config.enable_retry {
362            struct RetryableStatus;
363            impl reqwest_retry::RetryableStrategy for RetryableStatus {
364                fn handle(
365                    &self,
366                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
367                ) -> Option<reqwest_retry::Retryable> {
368                    match res {
369                        Ok(success) => reqwest_retry::default_on_request_success(success),
370                        Err(_) => None,
371                    }
372                }
373            }
374            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
375                .build_with_max_retries(config.max_retries);
376
377            let retry_middleware =
378                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
379                    backoff_policy,
380                    RetryableStatus,
381                );
382
383            middleware_client_builder = middleware_client_builder.with(retry_middleware);
384        }
385
386        let client = middleware_client_builder.build();
387
388        Self { config, client }
389    }
390
391    pub fn with_client_and_config(
392        config: datadog::Configuration,
393        client: reqwest_middleware::ClientWithMiddleware,
394    ) -> Self {
395        Self { config, client }
396    }
397
398    /// Create and define a list of queryable tag keys for a set of existing count, gauge, rate, and distribution metrics.
399    /// Metrics are selected by passing a metric name prefix. Use the Delete method of this API path to remove tag configurations.
400    /// Results can be sent to a set of account email addresses, just like the same operation in the Datadog web app.
401    /// If multiple calls include the same metric, the last configuration applied (not by submit order) is used, do not
402    /// expect deterministic ordering of concurrent calls. The `exclude_tags_mode` value will set all metrics that match the prefix to
403    /// the same exclusion state, metric tag configurations do not support mixed inclusion and exclusion for tags on the same metric.
404    /// Can only be used with application keys of users with the `Manage Tags for Metrics` permission.
405    pub async fn create_bulk_tags_metrics_configuration(
406        &self,
407        body: crate::datadogV2::model::MetricBulkTagConfigCreateRequest,
408    ) -> Result<
409        crate::datadogV2::model::MetricBulkTagConfigResponse,
410        datadog::Error<CreateBulkTagsMetricsConfigurationError>,
411    > {
412        match self
413            .create_bulk_tags_metrics_configuration_with_http_info(body)
414            .await
415        {
416            Ok(response_content) => {
417                if let Some(e) = response_content.entity {
418                    Ok(e)
419                } else {
420                    Err(datadog::Error::Serde(serde::de::Error::custom(
421                        "response content was None",
422                    )))
423                }
424            }
425            Err(err) => Err(err),
426        }
427    }
428
429    /// Create and define a list of queryable tag keys for a set of existing count, gauge, rate, and distribution metrics.
430    /// Metrics are selected by passing a metric name prefix. Use the Delete method of this API path to remove tag configurations.
431    /// Results can be sent to a set of account email addresses, just like the same operation in the Datadog web app.
432    /// If multiple calls include the same metric, the last configuration applied (not by submit order) is used, do not
433    /// expect deterministic ordering of concurrent calls. The `exclude_tags_mode` value will set all metrics that match the prefix to
434    /// the same exclusion state, metric tag configurations do not support mixed inclusion and exclusion for tags on the same metric.
435    /// Can only be used with application keys of users with the `Manage Tags for Metrics` permission.
436    pub async fn create_bulk_tags_metrics_configuration_with_http_info(
437        &self,
438        body: crate::datadogV2::model::MetricBulkTagConfigCreateRequest,
439    ) -> Result<
440        datadog::ResponseContent<crate::datadogV2::model::MetricBulkTagConfigResponse>,
441        datadog::Error<CreateBulkTagsMetricsConfigurationError>,
442    > {
443        let local_configuration = &self.config;
444        let operation_id = "v2.create_bulk_tags_metrics_configuration";
445
446        let local_client = &self.client;
447
448        let local_uri_str = format!(
449            "{}/api/v2/metrics/config/bulk-tags",
450            local_configuration.get_operation_host(operation_id)
451        );
452        let mut local_req_builder =
453            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
454
455        // build headers
456        let mut headers = HeaderMap::new();
457        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
458        headers.insert("Accept", HeaderValue::from_static("application/json"));
459
460        // build user agent
461        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
462            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
463            Err(e) => {
464                log::warn!("Failed to parse user agent header: {e}, falling back to default");
465                headers.insert(
466                    reqwest::header::USER_AGENT,
467                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
468                )
469            }
470        };
471
472        // build auth
473        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
474            headers.insert(
475                "DD-API-KEY",
476                HeaderValue::from_str(local_key.key.as_str())
477                    .expect("failed to parse DD-API-KEY header"),
478            );
479        };
480        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
481            headers.insert(
482                "DD-APPLICATION-KEY",
483                HeaderValue::from_str(local_key.key.as_str())
484                    .expect("failed to parse DD-APPLICATION-KEY header"),
485            );
486        };
487
488        // build body parameters
489        let output = Vec::new();
490        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
491        if body.serialize(&mut ser).is_ok() {
492            if let Some(content_encoding) = headers.get("Content-Encoding") {
493                match content_encoding.to_str().unwrap_or_default() {
494                    "gzip" => {
495                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
496                        let _ = enc.write_all(ser.into_inner().as_slice());
497                        match enc.finish() {
498                            Ok(buf) => {
499                                local_req_builder = local_req_builder.body(buf);
500                            }
501                            Err(e) => return Err(datadog::Error::Io(e)),
502                        }
503                    }
504                    "deflate" => {
505                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
506                        let _ = enc.write_all(ser.into_inner().as_slice());
507                        match enc.finish() {
508                            Ok(buf) => {
509                                local_req_builder = local_req_builder.body(buf);
510                            }
511                            Err(e) => return Err(datadog::Error::Io(e)),
512                        }
513                    }
514                    "zstd1" => {
515                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
516                        let _ = enc.write_all(ser.into_inner().as_slice());
517                        match enc.finish() {
518                            Ok(buf) => {
519                                local_req_builder = local_req_builder.body(buf);
520                            }
521                            Err(e) => return Err(datadog::Error::Io(e)),
522                        }
523                    }
524                    _ => {
525                        local_req_builder = local_req_builder.body(ser.into_inner());
526                    }
527                }
528            } else {
529                local_req_builder = local_req_builder.body(ser.into_inner());
530            }
531        }
532
533        local_req_builder = local_req_builder.headers(headers);
534        let local_req = local_req_builder.build()?;
535        log::debug!("request content: {:?}", local_req.body());
536        let local_resp = local_client.execute(local_req).await?;
537
538        let local_status = local_resp.status();
539        let local_content = local_resp.text().await?;
540        log::debug!("response content: {}", local_content);
541
542        if !local_status.is_client_error() && !local_status.is_server_error() {
543            match serde_json::from_str::<crate::datadogV2::model::MetricBulkTagConfigResponse>(
544                &local_content,
545            ) {
546                Ok(e) => {
547                    return Ok(datadog::ResponseContent {
548                        status: local_status,
549                        content: local_content,
550                        entity: Some(e),
551                    })
552                }
553                Err(e) => return Err(datadog::Error::Serde(e)),
554            };
555        } else {
556            let local_entity: Option<CreateBulkTagsMetricsConfigurationError> =
557                serde_json::from_str(&local_content).ok();
558            let local_error = datadog::ResponseContent {
559                status: local_status,
560                content: local_content,
561                entity: local_entity,
562            };
563            Err(datadog::Error::ResponseError(local_error))
564        }
565    }
566
567    /// Create and define a list of queryable tag keys for an existing count/gauge/rate/distribution metric.
568    /// Optionally, include percentile aggregations on any distribution metric. By setting `exclude_tags_mode`
569    /// to true, the behavior is changed from an allow-list to a deny-list, and tags in the defined list are
570    /// not queryable. Can only be used with application keys of users with the `Manage Tags for Metrics`
571    /// permission.
572    pub async fn create_tag_configuration(
573        &self,
574        metric_name: String,
575        body: crate::datadogV2::model::MetricTagConfigurationCreateRequest,
576    ) -> Result<
577        crate::datadogV2::model::MetricTagConfigurationResponse,
578        datadog::Error<CreateTagConfigurationError>,
579    > {
580        match self
581            .create_tag_configuration_with_http_info(metric_name, body)
582            .await
583        {
584            Ok(response_content) => {
585                if let Some(e) = response_content.entity {
586                    Ok(e)
587                } else {
588                    Err(datadog::Error::Serde(serde::de::Error::custom(
589                        "response content was None",
590                    )))
591                }
592            }
593            Err(err) => Err(err),
594        }
595    }
596
597    /// Create and define a list of queryable tag keys for an existing count/gauge/rate/distribution metric.
598    /// Optionally, include percentile aggregations on any distribution metric. By setting `exclude_tags_mode`
599    /// to true, the behavior is changed from an allow-list to a deny-list, and tags in the defined list are
600    /// not queryable. Can only be used with application keys of users with the `Manage Tags for Metrics`
601    /// permission.
602    pub async fn create_tag_configuration_with_http_info(
603        &self,
604        metric_name: String,
605        body: crate::datadogV2::model::MetricTagConfigurationCreateRequest,
606    ) -> Result<
607        datadog::ResponseContent<crate::datadogV2::model::MetricTagConfigurationResponse>,
608        datadog::Error<CreateTagConfigurationError>,
609    > {
610        let local_configuration = &self.config;
611        let operation_id = "v2.create_tag_configuration";
612
613        let local_client = &self.client;
614
615        let local_uri_str = format!(
616            "{}/api/v2/metrics/{metric_name}/tags",
617            local_configuration.get_operation_host(operation_id),
618            metric_name = datadog::urlencode(metric_name)
619        );
620        let mut local_req_builder =
621            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
622
623        // build headers
624        let mut headers = HeaderMap::new();
625        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
626        headers.insert("Accept", HeaderValue::from_static("application/json"));
627
628        // build user agent
629        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
630            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
631            Err(e) => {
632                log::warn!("Failed to parse user agent header: {e}, falling back to default");
633                headers.insert(
634                    reqwest::header::USER_AGENT,
635                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
636                )
637            }
638        };
639
640        // build auth
641        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
642            headers.insert(
643                "DD-API-KEY",
644                HeaderValue::from_str(local_key.key.as_str())
645                    .expect("failed to parse DD-API-KEY header"),
646            );
647        };
648        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
649            headers.insert(
650                "DD-APPLICATION-KEY",
651                HeaderValue::from_str(local_key.key.as_str())
652                    .expect("failed to parse DD-APPLICATION-KEY header"),
653            );
654        };
655
656        // build body parameters
657        let output = Vec::new();
658        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
659        if body.serialize(&mut ser).is_ok() {
660            if let Some(content_encoding) = headers.get("Content-Encoding") {
661                match content_encoding.to_str().unwrap_or_default() {
662                    "gzip" => {
663                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
664                        let _ = enc.write_all(ser.into_inner().as_slice());
665                        match enc.finish() {
666                            Ok(buf) => {
667                                local_req_builder = local_req_builder.body(buf);
668                            }
669                            Err(e) => return Err(datadog::Error::Io(e)),
670                        }
671                    }
672                    "deflate" => {
673                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
674                        let _ = enc.write_all(ser.into_inner().as_slice());
675                        match enc.finish() {
676                            Ok(buf) => {
677                                local_req_builder = local_req_builder.body(buf);
678                            }
679                            Err(e) => return Err(datadog::Error::Io(e)),
680                        }
681                    }
682                    "zstd1" => {
683                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
684                        let _ = enc.write_all(ser.into_inner().as_slice());
685                        match enc.finish() {
686                            Ok(buf) => {
687                                local_req_builder = local_req_builder.body(buf);
688                            }
689                            Err(e) => return Err(datadog::Error::Io(e)),
690                        }
691                    }
692                    _ => {
693                        local_req_builder = local_req_builder.body(ser.into_inner());
694                    }
695                }
696            } else {
697                local_req_builder = local_req_builder.body(ser.into_inner());
698            }
699        }
700
701        local_req_builder = local_req_builder.headers(headers);
702        let local_req = local_req_builder.build()?;
703        log::debug!("request content: {:?}", local_req.body());
704        let local_resp = local_client.execute(local_req).await?;
705
706        let local_status = local_resp.status();
707        let local_content = local_resp.text().await?;
708        log::debug!("response content: {}", local_content);
709
710        if !local_status.is_client_error() && !local_status.is_server_error() {
711            match serde_json::from_str::<crate::datadogV2::model::MetricTagConfigurationResponse>(
712                &local_content,
713            ) {
714                Ok(e) => {
715                    return Ok(datadog::ResponseContent {
716                        status: local_status,
717                        content: local_content,
718                        entity: Some(e),
719                    })
720                }
721                Err(e) => return Err(datadog::Error::Serde(e)),
722            };
723        } else {
724            let local_entity: Option<CreateTagConfigurationError> =
725                serde_json::from_str(&local_content).ok();
726            let local_error = datadog::ResponseContent {
727                status: local_status,
728                content: local_content,
729                entity: local_entity,
730            };
731            Err(datadog::Error::ResponseError(local_error))
732        }
733    }
734
735    /// Delete all custom lists of queryable tag keys for a set of existing count, gauge, rate, and distribution metrics.
736    /// Metrics are selected by passing a metric name prefix.
737    /// Results can be sent to a set of account email addresses, just like the same operation in the Datadog web app.
738    /// Can only be used with application keys of users with the `Manage Tags for Metrics` permission.
739    pub async fn delete_bulk_tags_metrics_configuration(
740        &self,
741        body: crate::datadogV2::model::MetricBulkTagConfigDeleteRequest,
742    ) -> Result<
743        crate::datadogV2::model::MetricBulkTagConfigResponse,
744        datadog::Error<DeleteBulkTagsMetricsConfigurationError>,
745    > {
746        match self
747            .delete_bulk_tags_metrics_configuration_with_http_info(body)
748            .await
749        {
750            Ok(response_content) => {
751                if let Some(e) = response_content.entity {
752                    Ok(e)
753                } else {
754                    Err(datadog::Error::Serde(serde::de::Error::custom(
755                        "response content was None",
756                    )))
757                }
758            }
759            Err(err) => Err(err),
760        }
761    }
762
763    /// Delete all custom lists of queryable tag keys for a set of existing count, gauge, rate, and distribution metrics.
764    /// Metrics are selected by passing a metric name prefix.
765    /// Results can be sent to a set of account email addresses, just like the same operation in the Datadog web app.
766    /// Can only be used with application keys of users with the `Manage Tags for Metrics` permission.
767    pub async fn delete_bulk_tags_metrics_configuration_with_http_info(
768        &self,
769        body: crate::datadogV2::model::MetricBulkTagConfigDeleteRequest,
770    ) -> Result<
771        datadog::ResponseContent<crate::datadogV2::model::MetricBulkTagConfigResponse>,
772        datadog::Error<DeleteBulkTagsMetricsConfigurationError>,
773    > {
774        let local_configuration = &self.config;
775        let operation_id = "v2.delete_bulk_tags_metrics_configuration";
776
777        let local_client = &self.client;
778
779        let local_uri_str = format!(
780            "{}/api/v2/metrics/config/bulk-tags",
781            local_configuration.get_operation_host(operation_id)
782        );
783        let mut local_req_builder =
784            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
785
786        // build headers
787        let mut headers = HeaderMap::new();
788        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
789        headers.insert("Accept", HeaderValue::from_static("application/json"));
790
791        // build user agent
792        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
793            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
794            Err(e) => {
795                log::warn!("Failed to parse user agent header: {e}, falling back to default");
796                headers.insert(
797                    reqwest::header::USER_AGENT,
798                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
799                )
800            }
801        };
802
803        // build auth
804        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
805            headers.insert(
806                "DD-API-KEY",
807                HeaderValue::from_str(local_key.key.as_str())
808                    .expect("failed to parse DD-API-KEY header"),
809            );
810        };
811        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
812            headers.insert(
813                "DD-APPLICATION-KEY",
814                HeaderValue::from_str(local_key.key.as_str())
815                    .expect("failed to parse DD-APPLICATION-KEY header"),
816            );
817        };
818
819        // build body parameters
820        let output = Vec::new();
821        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
822        if body.serialize(&mut ser).is_ok() {
823            if let Some(content_encoding) = headers.get("Content-Encoding") {
824                match content_encoding.to_str().unwrap_or_default() {
825                    "gzip" => {
826                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
827                        let _ = enc.write_all(ser.into_inner().as_slice());
828                        match enc.finish() {
829                            Ok(buf) => {
830                                local_req_builder = local_req_builder.body(buf);
831                            }
832                            Err(e) => return Err(datadog::Error::Io(e)),
833                        }
834                    }
835                    "deflate" => {
836                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
837                        let _ = enc.write_all(ser.into_inner().as_slice());
838                        match enc.finish() {
839                            Ok(buf) => {
840                                local_req_builder = local_req_builder.body(buf);
841                            }
842                            Err(e) => return Err(datadog::Error::Io(e)),
843                        }
844                    }
845                    "zstd1" => {
846                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
847                        let _ = enc.write_all(ser.into_inner().as_slice());
848                        match enc.finish() {
849                            Ok(buf) => {
850                                local_req_builder = local_req_builder.body(buf);
851                            }
852                            Err(e) => return Err(datadog::Error::Io(e)),
853                        }
854                    }
855                    _ => {
856                        local_req_builder = local_req_builder.body(ser.into_inner());
857                    }
858                }
859            } else {
860                local_req_builder = local_req_builder.body(ser.into_inner());
861            }
862        }
863
864        local_req_builder = local_req_builder.headers(headers);
865        let local_req = local_req_builder.build()?;
866        log::debug!("request content: {:?}", local_req.body());
867        let local_resp = local_client.execute(local_req).await?;
868
869        let local_status = local_resp.status();
870        let local_content = local_resp.text().await?;
871        log::debug!("response content: {}", local_content);
872
873        if !local_status.is_client_error() && !local_status.is_server_error() {
874            match serde_json::from_str::<crate::datadogV2::model::MetricBulkTagConfigResponse>(
875                &local_content,
876            ) {
877                Ok(e) => {
878                    return Ok(datadog::ResponseContent {
879                        status: local_status,
880                        content: local_content,
881                        entity: Some(e),
882                    })
883                }
884                Err(e) => return Err(datadog::Error::Serde(e)),
885            };
886        } else {
887            let local_entity: Option<DeleteBulkTagsMetricsConfigurationError> =
888                serde_json::from_str(&local_content).ok();
889            let local_error = datadog::ResponseContent {
890                status: local_status,
891                content: local_content,
892                entity: local_entity,
893            };
894            Err(datadog::Error::ResponseError(local_error))
895        }
896    }
897
898    /// Deletes a metric's tag configuration. Can only be used with application
899    /// keys from users with the `Manage Tags for Metrics` permission.
900    pub async fn delete_tag_configuration(
901        &self,
902        metric_name: String,
903    ) -> Result<(), datadog::Error<DeleteTagConfigurationError>> {
904        match self
905            .delete_tag_configuration_with_http_info(metric_name)
906            .await
907        {
908            Ok(_) => Ok(()),
909            Err(err) => Err(err),
910        }
911    }
912
913    /// Deletes a metric's tag configuration. Can only be used with application
914    /// keys from users with the `Manage Tags for Metrics` permission.
915    pub async fn delete_tag_configuration_with_http_info(
916        &self,
917        metric_name: String,
918    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteTagConfigurationError>> {
919        let local_configuration = &self.config;
920        let operation_id = "v2.delete_tag_configuration";
921
922        let local_client = &self.client;
923
924        let local_uri_str = format!(
925            "{}/api/v2/metrics/{metric_name}/tags",
926            local_configuration.get_operation_host(operation_id),
927            metric_name = datadog::urlencode(metric_name)
928        );
929        let mut local_req_builder =
930            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
931
932        // build headers
933        let mut headers = HeaderMap::new();
934        headers.insert("Accept", HeaderValue::from_static("*/*"));
935
936        // build user agent
937        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
938            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
939            Err(e) => {
940                log::warn!("Failed to parse user agent header: {e}, falling back to default");
941                headers.insert(
942                    reqwest::header::USER_AGENT,
943                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
944                )
945            }
946        };
947
948        // build auth
949        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
950            headers.insert(
951                "DD-API-KEY",
952                HeaderValue::from_str(local_key.key.as_str())
953                    .expect("failed to parse DD-API-KEY header"),
954            );
955        };
956        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
957            headers.insert(
958                "DD-APPLICATION-KEY",
959                HeaderValue::from_str(local_key.key.as_str())
960                    .expect("failed to parse DD-APPLICATION-KEY header"),
961            );
962        };
963
964        local_req_builder = local_req_builder.headers(headers);
965        let local_req = local_req_builder.build()?;
966        log::debug!("request content: {:?}", local_req.body());
967        let local_resp = local_client.execute(local_req).await?;
968
969        let local_status = local_resp.status();
970        let local_content = local_resp.text().await?;
971        log::debug!("response content: {}", local_content);
972
973        if !local_status.is_client_error() && !local_status.is_server_error() {
974            Ok(datadog::ResponseContent {
975                status: local_status,
976                content: local_content,
977                entity: None,
978            })
979        } else {
980            let local_entity: Option<DeleteTagConfigurationError> =
981                serde_json::from_str(&local_content).ok();
982            let local_error = datadog::ResponseContent {
983                status: local_status,
984                content: local_content,
985                entity: local_entity,
986            };
987            Err(datadog::Error::ResponseError(local_error))
988        }
989    }
990
991    /// Returns the estimated cardinality for a metric with a given tag, percentile and number of aggregations configuration using Metrics without Limits&trade;.
992    pub async fn estimate_metrics_output_series(
993        &self,
994        metric_name: String,
995        params: EstimateMetricsOutputSeriesOptionalParams,
996    ) -> Result<
997        crate::datadogV2::model::MetricEstimateResponse,
998        datadog::Error<EstimateMetricsOutputSeriesError>,
999    > {
1000        match self
1001            .estimate_metrics_output_series_with_http_info(metric_name, params)
1002            .await
1003        {
1004            Ok(response_content) => {
1005                if let Some(e) = response_content.entity {
1006                    Ok(e)
1007                } else {
1008                    Err(datadog::Error::Serde(serde::de::Error::custom(
1009                        "response content was None",
1010                    )))
1011                }
1012            }
1013            Err(err) => Err(err),
1014        }
1015    }
1016
1017    /// Returns the estimated cardinality for a metric with a given tag, percentile and number of aggregations configuration using Metrics without Limits&trade;.
1018    pub async fn estimate_metrics_output_series_with_http_info(
1019        &self,
1020        metric_name: String,
1021        params: EstimateMetricsOutputSeriesOptionalParams,
1022    ) -> Result<
1023        datadog::ResponseContent<crate::datadogV2::model::MetricEstimateResponse>,
1024        datadog::Error<EstimateMetricsOutputSeriesError>,
1025    > {
1026        let local_configuration = &self.config;
1027        let operation_id = "v2.estimate_metrics_output_series";
1028
1029        // unbox and build optional parameters
1030        let filter_groups = params.filter_groups;
1031        let filter_hours_ago = params.filter_hours_ago;
1032        let filter_num_aggregations = params.filter_num_aggregations;
1033        let filter_pct = params.filter_pct;
1034        let filter_timespan_h = params.filter_timespan_h;
1035
1036        let local_client = &self.client;
1037
1038        let local_uri_str = format!(
1039            "{}/api/v2/metrics/{metric_name}/estimate",
1040            local_configuration.get_operation_host(operation_id),
1041            metric_name = datadog::urlencode(metric_name)
1042        );
1043        let mut local_req_builder =
1044            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1045
1046        if let Some(ref local_query_param) = filter_groups {
1047            local_req_builder =
1048                local_req_builder.query(&[("filter[groups]", &local_query_param.to_string())]);
1049        };
1050        if let Some(ref local_query_param) = filter_hours_ago {
1051            local_req_builder =
1052                local_req_builder.query(&[("filter[hours_ago]", &local_query_param.to_string())]);
1053        };
1054        if let Some(ref local_query_param) = filter_num_aggregations {
1055            local_req_builder = local_req_builder
1056                .query(&[("filter[num_aggregations]", &local_query_param.to_string())]);
1057        };
1058        if let Some(ref local_query_param) = filter_pct {
1059            local_req_builder =
1060                local_req_builder.query(&[("filter[pct]", &local_query_param.to_string())]);
1061        };
1062        if let Some(ref local_query_param) = filter_timespan_h {
1063            local_req_builder =
1064                local_req_builder.query(&[("filter[timespan_h]", &local_query_param.to_string())]);
1065        };
1066
1067        // build headers
1068        let mut headers = HeaderMap::new();
1069        headers.insert("Accept", HeaderValue::from_static("application/json"));
1070
1071        // build user agent
1072        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1073            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1074            Err(e) => {
1075                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1076                headers.insert(
1077                    reqwest::header::USER_AGENT,
1078                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1079                )
1080            }
1081        };
1082
1083        // build auth
1084        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1085            headers.insert(
1086                "DD-API-KEY",
1087                HeaderValue::from_str(local_key.key.as_str())
1088                    .expect("failed to parse DD-API-KEY header"),
1089            );
1090        };
1091        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1092            headers.insert(
1093                "DD-APPLICATION-KEY",
1094                HeaderValue::from_str(local_key.key.as_str())
1095                    .expect("failed to parse DD-APPLICATION-KEY header"),
1096            );
1097        };
1098
1099        local_req_builder = local_req_builder.headers(headers);
1100        let local_req = local_req_builder.build()?;
1101        log::debug!("request content: {:?}", local_req.body());
1102        let local_resp = local_client.execute(local_req).await?;
1103
1104        let local_status = local_resp.status();
1105        let local_content = local_resp.text().await?;
1106        log::debug!("response content: {}", local_content);
1107
1108        if !local_status.is_client_error() && !local_status.is_server_error() {
1109            match serde_json::from_str::<crate::datadogV2::model::MetricEstimateResponse>(
1110                &local_content,
1111            ) {
1112                Ok(e) => {
1113                    return Ok(datadog::ResponseContent {
1114                        status: local_status,
1115                        content: local_content,
1116                        entity: Some(e),
1117                    })
1118                }
1119                Err(e) => return Err(datadog::Error::Serde(e)),
1120            };
1121        } else {
1122            let local_entity: Option<EstimateMetricsOutputSeriesError> =
1123                serde_json::from_str(&local_content).ok();
1124            let local_error = datadog::ResponseContent {
1125                status: local_status,
1126                content: local_content,
1127                entity: local_entity,
1128            };
1129            Err(datadog::Error::ResponseError(local_error))
1130        }
1131    }
1132
1133    /// Returns the cardinality details of tags for a specific metric.
1134    pub async fn get_metric_tag_cardinality_details(
1135        &self,
1136        metric_name: String,
1137    ) -> Result<
1138        crate::datadogV2::model::MetricTagCardinalitiesResponse,
1139        datadog::Error<GetMetricTagCardinalityDetailsError>,
1140    > {
1141        match self
1142            .get_metric_tag_cardinality_details_with_http_info(metric_name)
1143            .await
1144        {
1145            Ok(response_content) => {
1146                if let Some(e) = response_content.entity {
1147                    Ok(e)
1148                } else {
1149                    Err(datadog::Error::Serde(serde::de::Error::custom(
1150                        "response content was None",
1151                    )))
1152                }
1153            }
1154            Err(err) => Err(err),
1155        }
1156    }
1157
1158    /// Returns the cardinality details of tags for a specific metric.
1159    pub async fn get_metric_tag_cardinality_details_with_http_info(
1160        &self,
1161        metric_name: String,
1162    ) -> Result<
1163        datadog::ResponseContent<crate::datadogV2::model::MetricTagCardinalitiesResponse>,
1164        datadog::Error<GetMetricTagCardinalityDetailsError>,
1165    > {
1166        let local_configuration = &self.config;
1167        let operation_id = "v2.get_metric_tag_cardinality_details";
1168
1169        let local_client = &self.client;
1170
1171        let local_uri_str = format!(
1172            "{}/api/v2/metrics/{metric_name}/tag-cardinalities",
1173            local_configuration.get_operation_host(operation_id),
1174            metric_name = datadog::urlencode(metric_name)
1175        );
1176        let mut local_req_builder =
1177            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1178
1179        // build headers
1180        let mut headers = HeaderMap::new();
1181        headers.insert("Accept", HeaderValue::from_static("application/json"));
1182
1183        // build user agent
1184        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1185            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1186            Err(e) => {
1187                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1188                headers.insert(
1189                    reqwest::header::USER_AGENT,
1190                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1191                )
1192            }
1193        };
1194
1195        // build auth
1196        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1197            headers.insert(
1198                "DD-API-KEY",
1199                HeaderValue::from_str(local_key.key.as_str())
1200                    .expect("failed to parse DD-API-KEY header"),
1201            );
1202        };
1203        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1204            headers.insert(
1205                "DD-APPLICATION-KEY",
1206                HeaderValue::from_str(local_key.key.as_str())
1207                    .expect("failed to parse DD-APPLICATION-KEY header"),
1208            );
1209        };
1210
1211        local_req_builder = local_req_builder.headers(headers);
1212        let local_req = local_req_builder.build()?;
1213        log::debug!("request content: {:?}", local_req.body());
1214        let local_resp = local_client.execute(local_req).await?;
1215
1216        let local_status = local_resp.status();
1217        let local_content = local_resp.text().await?;
1218        log::debug!("response content: {}", local_content);
1219
1220        if !local_status.is_client_error() && !local_status.is_server_error() {
1221            match serde_json::from_str::<crate::datadogV2::model::MetricTagCardinalitiesResponse>(
1222                &local_content,
1223            ) {
1224                Ok(e) => {
1225                    return Ok(datadog::ResponseContent {
1226                        status: local_status,
1227                        content: local_content,
1228                        entity: Some(e),
1229                    })
1230                }
1231                Err(e) => return Err(datadog::Error::Serde(e)),
1232            };
1233        } else {
1234            let local_entity: Option<GetMetricTagCardinalityDetailsError> =
1235                serde_json::from_str(&local_content).ok();
1236            let local_error = datadog::ResponseContent {
1237                status: local_status,
1238                content: local_content,
1239                entity: local_entity,
1240            };
1241            Err(datadog::Error::ResponseError(local_error))
1242        }
1243    }
1244
1245    /// List tags and aggregations that are actively queried on dashboards, notebooks, monitors, the Metrics Explorer, and using the API for a given metric name.
1246    pub async fn list_active_metric_configurations(
1247        &self,
1248        metric_name: String,
1249        params: ListActiveMetricConfigurationsOptionalParams,
1250    ) -> Result<
1251        crate::datadogV2::model::MetricSuggestedTagsAndAggregationsResponse,
1252        datadog::Error<ListActiveMetricConfigurationsError>,
1253    > {
1254        match self
1255            .list_active_metric_configurations_with_http_info(metric_name, params)
1256            .await
1257        {
1258            Ok(response_content) => {
1259                if let Some(e) = response_content.entity {
1260                    Ok(e)
1261                } else {
1262                    Err(datadog::Error::Serde(serde::de::Error::custom(
1263                        "response content was None",
1264                    )))
1265                }
1266            }
1267            Err(err) => Err(err),
1268        }
1269    }
1270
1271    /// List tags and aggregations that are actively queried on dashboards, notebooks, monitors, the Metrics Explorer, and using the API for a given metric name.
1272    pub async fn list_active_metric_configurations_with_http_info(
1273        &self,
1274        metric_name: String,
1275        params: ListActiveMetricConfigurationsOptionalParams,
1276    ) -> Result<
1277        datadog::ResponseContent<
1278            crate::datadogV2::model::MetricSuggestedTagsAndAggregationsResponse,
1279        >,
1280        datadog::Error<ListActiveMetricConfigurationsError>,
1281    > {
1282        let local_configuration = &self.config;
1283        let operation_id = "v2.list_active_metric_configurations";
1284
1285        // unbox and build optional parameters
1286        let window_seconds = params.window_seconds;
1287
1288        let local_client = &self.client;
1289
1290        let local_uri_str = format!(
1291            "{}/api/v2/metrics/{metric_name}/active-configurations",
1292            local_configuration.get_operation_host(operation_id),
1293            metric_name = datadog::urlencode(metric_name)
1294        );
1295        let mut local_req_builder =
1296            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1297
1298        if let Some(ref local_query_param) = window_seconds {
1299            local_req_builder =
1300                local_req_builder.query(&[("window[seconds]", &local_query_param.to_string())]);
1301        };
1302
1303        // build headers
1304        let mut headers = HeaderMap::new();
1305        headers.insert("Accept", HeaderValue::from_static("application/json"));
1306
1307        // build user agent
1308        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1309            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1310            Err(e) => {
1311                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1312                headers.insert(
1313                    reqwest::header::USER_AGENT,
1314                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1315                )
1316            }
1317        };
1318
1319        // build auth
1320        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1321            headers.insert(
1322                "DD-API-KEY",
1323                HeaderValue::from_str(local_key.key.as_str())
1324                    .expect("failed to parse DD-API-KEY header"),
1325            );
1326        };
1327        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1328            headers.insert(
1329                "DD-APPLICATION-KEY",
1330                HeaderValue::from_str(local_key.key.as_str())
1331                    .expect("failed to parse DD-APPLICATION-KEY header"),
1332            );
1333        };
1334
1335        local_req_builder = local_req_builder.headers(headers);
1336        let local_req = local_req_builder.build()?;
1337        log::debug!("request content: {:?}", local_req.body());
1338        let local_resp = local_client.execute(local_req).await?;
1339
1340        let local_status = local_resp.status();
1341        let local_content = local_resp.text().await?;
1342        log::debug!("response content: {}", local_content);
1343
1344        if !local_status.is_client_error() && !local_status.is_server_error() {
1345            match serde_json::from_str::<
1346                crate::datadogV2::model::MetricSuggestedTagsAndAggregationsResponse,
1347            >(&local_content)
1348            {
1349                Ok(e) => {
1350                    return Ok(datadog::ResponseContent {
1351                        status: local_status,
1352                        content: local_content,
1353                        entity: Some(e),
1354                    })
1355                }
1356                Err(e) => return Err(datadog::Error::Serde(e)),
1357            };
1358        } else {
1359            let local_entity: Option<ListActiveMetricConfigurationsError> =
1360                serde_json::from_str(&local_content).ok();
1361            let local_error = datadog::ResponseContent {
1362                status: local_status,
1363                content: local_content,
1364                entity: local_entity,
1365            };
1366            Err(datadog::Error::ResponseError(local_error))
1367        }
1368    }
1369
1370    /// Returns dashboards, monitors, notebooks, and SLOs that a metric is stored in, if any.  Updated every 24 hours.
1371    pub async fn list_metric_assets(
1372        &self,
1373        metric_name: String,
1374    ) -> Result<crate::datadogV2::model::MetricAssetsResponse, datadog::Error<ListMetricAssetsError>>
1375    {
1376        match self.list_metric_assets_with_http_info(metric_name).await {
1377            Ok(response_content) => {
1378                if let Some(e) = response_content.entity {
1379                    Ok(e)
1380                } else {
1381                    Err(datadog::Error::Serde(serde::de::Error::custom(
1382                        "response content was None",
1383                    )))
1384                }
1385            }
1386            Err(err) => Err(err),
1387        }
1388    }
1389
1390    /// Returns dashboards, monitors, notebooks, and SLOs that a metric is stored in, if any.  Updated every 24 hours.
1391    pub async fn list_metric_assets_with_http_info(
1392        &self,
1393        metric_name: String,
1394    ) -> Result<
1395        datadog::ResponseContent<crate::datadogV2::model::MetricAssetsResponse>,
1396        datadog::Error<ListMetricAssetsError>,
1397    > {
1398        let local_configuration = &self.config;
1399        let operation_id = "v2.list_metric_assets";
1400
1401        let local_client = &self.client;
1402
1403        let local_uri_str = format!(
1404            "{}/api/v2/metrics/{metric_name}/assets",
1405            local_configuration.get_operation_host(operation_id),
1406            metric_name = datadog::urlencode(metric_name)
1407        );
1408        let mut local_req_builder =
1409            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1410
1411        // build headers
1412        let mut headers = HeaderMap::new();
1413        headers.insert("Accept", HeaderValue::from_static("application/json"));
1414
1415        // build user agent
1416        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1417            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1418            Err(e) => {
1419                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1420                headers.insert(
1421                    reqwest::header::USER_AGENT,
1422                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1423                )
1424            }
1425        };
1426
1427        // build auth
1428        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1429            headers.insert(
1430                "DD-API-KEY",
1431                HeaderValue::from_str(local_key.key.as_str())
1432                    .expect("failed to parse DD-API-KEY header"),
1433            );
1434        };
1435        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1436            headers.insert(
1437                "DD-APPLICATION-KEY",
1438                HeaderValue::from_str(local_key.key.as_str())
1439                    .expect("failed to parse DD-APPLICATION-KEY header"),
1440            );
1441        };
1442
1443        local_req_builder = local_req_builder.headers(headers);
1444        let local_req = local_req_builder.build()?;
1445        log::debug!("request content: {:?}", local_req.body());
1446        let local_resp = local_client.execute(local_req).await?;
1447
1448        let local_status = local_resp.status();
1449        let local_content = local_resp.text().await?;
1450        log::debug!("response content: {}", local_content);
1451
1452        if !local_status.is_client_error() && !local_status.is_server_error() {
1453            match serde_json::from_str::<crate::datadogV2::model::MetricAssetsResponse>(
1454                &local_content,
1455            ) {
1456                Ok(e) => {
1457                    return Ok(datadog::ResponseContent {
1458                        status: local_status,
1459                        content: local_content,
1460                        entity: Some(e),
1461                    })
1462                }
1463                Err(e) => return Err(datadog::Error::Serde(e)),
1464            };
1465        } else {
1466            let local_entity: Option<ListMetricAssetsError> =
1467                serde_json::from_str(&local_content).ok();
1468            let local_error = datadog::ResponseContent {
1469                status: local_status,
1470                content: local_content,
1471                entity: local_entity,
1472            };
1473            Err(datadog::Error::ResponseError(local_error))
1474        }
1475    }
1476
1477    /// Returns the tag configuration for the given metric name.
1478    pub async fn list_tag_configuration_by_name(
1479        &self,
1480        metric_name: String,
1481    ) -> Result<
1482        crate::datadogV2::model::MetricTagConfigurationResponse,
1483        datadog::Error<ListTagConfigurationByNameError>,
1484    > {
1485        match self
1486            .list_tag_configuration_by_name_with_http_info(metric_name)
1487            .await
1488        {
1489            Ok(response_content) => {
1490                if let Some(e) = response_content.entity {
1491                    Ok(e)
1492                } else {
1493                    Err(datadog::Error::Serde(serde::de::Error::custom(
1494                        "response content was None",
1495                    )))
1496                }
1497            }
1498            Err(err) => Err(err),
1499        }
1500    }
1501
1502    /// Returns the tag configuration for the given metric name.
1503    pub async fn list_tag_configuration_by_name_with_http_info(
1504        &self,
1505        metric_name: String,
1506    ) -> Result<
1507        datadog::ResponseContent<crate::datadogV2::model::MetricTagConfigurationResponse>,
1508        datadog::Error<ListTagConfigurationByNameError>,
1509    > {
1510        let local_configuration = &self.config;
1511        let operation_id = "v2.list_tag_configuration_by_name";
1512
1513        let local_client = &self.client;
1514
1515        let local_uri_str = format!(
1516            "{}/api/v2/metrics/{metric_name}/tags",
1517            local_configuration.get_operation_host(operation_id),
1518            metric_name = datadog::urlencode(metric_name)
1519        );
1520        let mut local_req_builder =
1521            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1522
1523        // build headers
1524        let mut headers = HeaderMap::new();
1525        headers.insert("Accept", HeaderValue::from_static("application/json"));
1526
1527        // build user agent
1528        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1529            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1530            Err(e) => {
1531                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1532                headers.insert(
1533                    reqwest::header::USER_AGENT,
1534                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1535                )
1536            }
1537        };
1538
1539        // build auth
1540        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1541            headers.insert(
1542                "DD-API-KEY",
1543                HeaderValue::from_str(local_key.key.as_str())
1544                    .expect("failed to parse DD-API-KEY header"),
1545            );
1546        };
1547        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1548            headers.insert(
1549                "DD-APPLICATION-KEY",
1550                HeaderValue::from_str(local_key.key.as_str())
1551                    .expect("failed to parse DD-APPLICATION-KEY header"),
1552            );
1553        };
1554
1555        local_req_builder = local_req_builder.headers(headers);
1556        let local_req = local_req_builder.build()?;
1557        log::debug!("request content: {:?}", local_req.body());
1558        let local_resp = local_client.execute(local_req).await?;
1559
1560        let local_status = local_resp.status();
1561        let local_content = local_resp.text().await?;
1562        log::debug!("response content: {}", local_content);
1563
1564        if !local_status.is_client_error() && !local_status.is_server_error() {
1565            match serde_json::from_str::<crate::datadogV2::model::MetricTagConfigurationResponse>(
1566                &local_content,
1567            ) {
1568                Ok(e) => {
1569                    return Ok(datadog::ResponseContent {
1570                        status: local_status,
1571                        content: local_content,
1572                        entity: Some(e),
1573                    })
1574                }
1575                Err(e) => return Err(datadog::Error::Serde(e)),
1576            };
1577        } else {
1578            let local_entity: Option<ListTagConfigurationByNameError> =
1579                serde_json::from_str(&local_content).ok();
1580            let local_error = datadog::ResponseContent {
1581                status: local_status,
1582                content: local_content,
1583                entity: local_entity,
1584            };
1585            Err(datadog::Error::ResponseError(local_error))
1586        }
1587    }
1588
1589    /// Returns all metrics that can be configured in the Metrics Summary page or with Metrics without Limits™ (matching additional filters if specified).
1590    /// Optionally, paginate by using the `page[cursor]` and/or `page[size]` query parameters.
1591    /// To fetch the first page, pass in a query parameter with either a valid `page[size]` or an empty cursor like `page[cursor]=`. To fetch the next page, pass in the `next_cursor` value from the response as the new `page[cursor]` value.
1592    /// Once the `meta.pagination.next_cursor` value is null, all pages have been retrieved.
1593    pub async fn list_tag_configurations(
1594        &self,
1595        params: ListTagConfigurationsOptionalParams,
1596    ) -> Result<
1597        crate::datadogV2::model::MetricsAndMetricTagConfigurationsResponse,
1598        datadog::Error<ListTagConfigurationsError>,
1599    > {
1600        match self.list_tag_configurations_with_http_info(params).await {
1601            Ok(response_content) => {
1602                if let Some(e) = response_content.entity {
1603                    Ok(e)
1604                } else {
1605                    Err(datadog::Error::Serde(serde::de::Error::custom(
1606                        "response content was None",
1607                    )))
1608                }
1609            }
1610            Err(err) => Err(err),
1611        }
1612    }
1613
1614    pub fn list_tag_configurations_with_pagination(
1615        &self,
1616        mut params: ListTagConfigurationsOptionalParams,
1617    ) -> impl Stream<
1618        Item = Result<
1619            crate::datadogV2::model::MetricsAndMetricTagConfigurations,
1620            datadog::Error<ListTagConfigurationsError>,
1621        >,
1622    > + '_ {
1623        try_stream! {
1624            let mut page_size: i32 = 10000;
1625            if params.page_size.is_none() {
1626                params.page_size = Some(page_size);
1627            } else {
1628                page_size = params.page_size.unwrap().clone();
1629            }
1630            loop {
1631                let resp = self.list_tag_configurations(params.clone()).await?;
1632                let Some(data) = resp.data else { break };
1633
1634                let r = data;
1635                let count = r.len();
1636                for team in r {
1637                    yield team;
1638                }
1639
1640                if count < page_size as usize {
1641                    break;
1642                }
1643                let Some(meta) = resp.meta else { break };
1644                let Some(pagination) = meta.pagination else { break };
1645                let Some(next_cursor) = pagination.next_cursor.unwrap() else { break };
1646
1647                params.page_cursor = Some(next_cursor);
1648            }
1649        }
1650    }
1651
1652    /// Returns all metrics that can be configured in the Metrics Summary page or with Metrics without Limits™ (matching additional filters if specified).
1653    /// Optionally, paginate by using the `page[cursor]` and/or `page[size]` query parameters.
1654    /// To fetch the first page, pass in a query parameter with either a valid `page[size]` or an empty cursor like `page[cursor]=`. To fetch the next page, pass in the `next_cursor` value from the response as the new `page[cursor]` value.
1655    /// Once the `meta.pagination.next_cursor` value is null, all pages have been retrieved.
1656    pub async fn list_tag_configurations_with_http_info(
1657        &self,
1658        params: ListTagConfigurationsOptionalParams,
1659    ) -> Result<
1660        datadog::ResponseContent<
1661            crate::datadogV2::model::MetricsAndMetricTagConfigurationsResponse,
1662        >,
1663        datadog::Error<ListTagConfigurationsError>,
1664    > {
1665        let local_configuration = &self.config;
1666        let operation_id = "v2.list_tag_configurations";
1667
1668        // unbox and build optional parameters
1669        let filter_configured = params.filter_configured;
1670        let filter_tags_configured = params.filter_tags_configured;
1671        let filter_metric_type = params.filter_metric_type;
1672        let filter_include_percentiles = params.filter_include_percentiles;
1673        let filter_queried = params.filter_queried;
1674        let filter_tags = params.filter_tags;
1675        let filter_related_assets = params.filter_related_assets;
1676        let window_seconds = params.window_seconds;
1677        let page_size = params.page_size;
1678        let page_cursor = params.page_cursor;
1679
1680        let local_client = &self.client;
1681
1682        let local_uri_str = format!(
1683            "{}/api/v2/metrics",
1684            local_configuration.get_operation_host(operation_id)
1685        );
1686        let mut local_req_builder =
1687            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1688
1689        if let Some(ref local_query_param) = filter_configured {
1690            local_req_builder =
1691                local_req_builder.query(&[("filter[configured]", &local_query_param.to_string())]);
1692        };
1693        if let Some(ref local_query_param) = filter_tags_configured {
1694            local_req_builder = local_req_builder
1695                .query(&[("filter[tags_configured]", &local_query_param.to_string())]);
1696        };
1697        if let Some(ref local_query_param) = filter_metric_type {
1698            local_req_builder =
1699                local_req_builder.query(&[("filter[metric_type]", &local_query_param.to_string())]);
1700        };
1701        if let Some(ref local_query_param) = filter_include_percentiles {
1702            local_req_builder = local_req_builder.query(&[(
1703                "filter[include_percentiles]",
1704                &local_query_param.to_string(),
1705            )]);
1706        };
1707        if let Some(ref local_query_param) = filter_queried {
1708            local_req_builder =
1709                local_req_builder.query(&[("filter[queried]", &local_query_param.to_string())]);
1710        };
1711        if let Some(ref local_query_param) = filter_tags {
1712            local_req_builder =
1713                local_req_builder.query(&[("filter[tags]", &local_query_param.to_string())]);
1714        };
1715        if let Some(ref local_query_param) = filter_related_assets {
1716            local_req_builder = local_req_builder
1717                .query(&[("filter[related_assets]", &local_query_param.to_string())]);
1718        };
1719        if let Some(ref local_query_param) = window_seconds {
1720            local_req_builder =
1721                local_req_builder.query(&[("window[seconds]", &local_query_param.to_string())]);
1722        };
1723        if let Some(ref local_query_param) = page_size {
1724            local_req_builder =
1725                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
1726        };
1727        if let Some(ref local_query_param) = page_cursor {
1728            local_req_builder =
1729                local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
1730        };
1731
1732        // build headers
1733        let mut headers = HeaderMap::new();
1734        headers.insert("Accept", HeaderValue::from_static("application/json"));
1735
1736        // build user agent
1737        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1738            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1739            Err(e) => {
1740                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1741                headers.insert(
1742                    reqwest::header::USER_AGENT,
1743                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1744                )
1745            }
1746        };
1747
1748        // build auth
1749        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1750            headers.insert(
1751                "DD-API-KEY",
1752                HeaderValue::from_str(local_key.key.as_str())
1753                    .expect("failed to parse DD-API-KEY header"),
1754            );
1755        };
1756        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1757            headers.insert(
1758                "DD-APPLICATION-KEY",
1759                HeaderValue::from_str(local_key.key.as_str())
1760                    .expect("failed to parse DD-APPLICATION-KEY header"),
1761            );
1762        };
1763
1764        local_req_builder = local_req_builder.headers(headers);
1765        let local_req = local_req_builder.build()?;
1766        log::debug!("request content: {:?}", local_req.body());
1767        let local_resp = local_client.execute(local_req).await?;
1768
1769        let local_status = local_resp.status();
1770        let local_content = local_resp.text().await?;
1771        log::debug!("response content: {}", local_content);
1772
1773        if !local_status.is_client_error() && !local_status.is_server_error() {
1774            match serde_json::from_str::<
1775                crate::datadogV2::model::MetricsAndMetricTagConfigurationsResponse,
1776            >(&local_content)
1777            {
1778                Ok(e) => {
1779                    return Ok(datadog::ResponseContent {
1780                        status: local_status,
1781                        content: local_content,
1782                        entity: Some(e),
1783                    })
1784                }
1785                Err(e) => return Err(datadog::Error::Serde(e)),
1786            };
1787        } else {
1788            let local_entity: Option<ListTagConfigurationsError> =
1789                serde_json::from_str(&local_content).ok();
1790            let local_error = datadog::ResponseContent {
1791                status: local_status,
1792                content: local_content,
1793                entity: local_entity,
1794            };
1795            Err(datadog::Error::ResponseError(local_error))
1796        }
1797    }
1798
1799    /// View indexed tag key-value pairs for a given metric name over the previous hour.
1800    pub async fn list_tags_by_metric_name(
1801        &self,
1802        metric_name: String,
1803    ) -> Result<
1804        crate::datadogV2::model::MetricAllTagsResponse,
1805        datadog::Error<ListTagsByMetricNameError>,
1806    > {
1807        match self
1808            .list_tags_by_metric_name_with_http_info(metric_name)
1809            .await
1810        {
1811            Ok(response_content) => {
1812                if let Some(e) = response_content.entity {
1813                    Ok(e)
1814                } else {
1815                    Err(datadog::Error::Serde(serde::de::Error::custom(
1816                        "response content was None",
1817                    )))
1818                }
1819            }
1820            Err(err) => Err(err),
1821        }
1822    }
1823
1824    /// View indexed tag key-value pairs for a given metric name over the previous hour.
1825    pub async fn list_tags_by_metric_name_with_http_info(
1826        &self,
1827        metric_name: String,
1828    ) -> Result<
1829        datadog::ResponseContent<crate::datadogV2::model::MetricAllTagsResponse>,
1830        datadog::Error<ListTagsByMetricNameError>,
1831    > {
1832        let local_configuration = &self.config;
1833        let operation_id = "v2.list_tags_by_metric_name";
1834
1835        let local_client = &self.client;
1836
1837        let local_uri_str = format!(
1838            "{}/api/v2/metrics/{metric_name}/all-tags",
1839            local_configuration.get_operation_host(operation_id),
1840            metric_name = datadog::urlencode(metric_name)
1841        );
1842        let mut local_req_builder =
1843            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1844
1845        // build headers
1846        let mut headers = HeaderMap::new();
1847        headers.insert("Accept", HeaderValue::from_static("application/json"));
1848
1849        // build user agent
1850        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1851            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1852            Err(e) => {
1853                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1854                headers.insert(
1855                    reqwest::header::USER_AGENT,
1856                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1857                )
1858            }
1859        };
1860
1861        // build auth
1862        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1863            headers.insert(
1864                "DD-API-KEY",
1865                HeaderValue::from_str(local_key.key.as_str())
1866                    .expect("failed to parse DD-API-KEY header"),
1867            );
1868        };
1869        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1870            headers.insert(
1871                "DD-APPLICATION-KEY",
1872                HeaderValue::from_str(local_key.key.as_str())
1873                    .expect("failed to parse DD-APPLICATION-KEY header"),
1874            );
1875        };
1876
1877        local_req_builder = local_req_builder.headers(headers);
1878        let local_req = local_req_builder.build()?;
1879        log::debug!("request content: {:?}", local_req.body());
1880        let local_resp = local_client.execute(local_req).await?;
1881
1882        let local_status = local_resp.status();
1883        let local_content = local_resp.text().await?;
1884        log::debug!("response content: {}", local_content);
1885
1886        if !local_status.is_client_error() && !local_status.is_server_error() {
1887            match serde_json::from_str::<crate::datadogV2::model::MetricAllTagsResponse>(
1888                &local_content,
1889            ) {
1890                Ok(e) => {
1891                    return Ok(datadog::ResponseContent {
1892                        status: local_status,
1893                        content: local_content,
1894                        entity: Some(e),
1895                    })
1896                }
1897                Err(e) => return Err(datadog::Error::Serde(e)),
1898            };
1899        } else {
1900            let local_entity: Option<ListTagsByMetricNameError> =
1901                serde_json::from_str(&local_content).ok();
1902            let local_error = datadog::ResponseContent {
1903                status: local_status,
1904                content: local_content,
1905                entity: local_entity,
1906            };
1907            Err(datadog::Error::ResponseError(local_error))
1908        }
1909    }
1910
1911    /// View distinct metrics volumes for the given metric name.
1912    ///
1913    /// Custom metrics generated in-app from other products will return `null` for ingested volumes.
1914    pub async fn list_volumes_by_metric_name(
1915        &self,
1916        metric_name: String,
1917    ) -> Result<
1918        crate::datadogV2::model::MetricVolumesResponse,
1919        datadog::Error<ListVolumesByMetricNameError>,
1920    > {
1921        match self
1922            .list_volumes_by_metric_name_with_http_info(metric_name)
1923            .await
1924        {
1925            Ok(response_content) => {
1926                if let Some(e) = response_content.entity {
1927                    Ok(e)
1928                } else {
1929                    Err(datadog::Error::Serde(serde::de::Error::custom(
1930                        "response content was None",
1931                    )))
1932                }
1933            }
1934            Err(err) => Err(err),
1935        }
1936    }
1937
1938    /// View distinct metrics volumes for the given metric name.
1939    ///
1940    /// Custom metrics generated in-app from other products will return `null` for ingested volumes.
1941    pub async fn list_volumes_by_metric_name_with_http_info(
1942        &self,
1943        metric_name: String,
1944    ) -> Result<
1945        datadog::ResponseContent<crate::datadogV2::model::MetricVolumesResponse>,
1946        datadog::Error<ListVolumesByMetricNameError>,
1947    > {
1948        let local_configuration = &self.config;
1949        let operation_id = "v2.list_volumes_by_metric_name";
1950
1951        let local_client = &self.client;
1952
1953        let local_uri_str = format!(
1954            "{}/api/v2/metrics/{metric_name}/volumes",
1955            local_configuration.get_operation_host(operation_id),
1956            metric_name = datadog::urlencode(metric_name)
1957        );
1958        let mut local_req_builder =
1959            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1960
1961        // build headers
1962        let mut headers = HeaderMap::new();
1963        headers.insert("Accept", HeaderValue::from_static("application/json"));
1964
1965        // build user agent
1966        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1967            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1968            Err(e) => {
1969                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1970                headers.insert(
1971                    reqwest::header::USER_AGENT,
1972                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1973                )
1974            }
1975        };
1976
1977        // build auth
1978        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1979            headers.insert(
1980                "DD-API-KEY",
1981                HeaderValue::from_str(local_key.key.as_str())
1982                    .expect("failed to parse DD-API-KEY header"),
1983            );
1984        };
1985        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1986            headers.insert(
1987                "DD-APPLICATION-KEY",
1988                HeaderValue::from_str(local_key.key.as_str())
1989                    .expect("failed to parse DD-APPLICATION-KEY header"),
1990            );
1991        };
1992
1993        local_req_builder = local_req_builder.headers(headers);
1994        let local_req = local_req_builder.build()?;
1995        log::debug!("request content: {:?}", local_req.body());
1996        let local_resp = local_client.execute(local_req).await?;
1997
1998        let local_status = local_resp.status();
1999        let local_content = local_resp.text().await?;
2000        log::debug!("response content: {}", local_content);
2001
2002        if !local_status.is_client_error() && !local_status.is_server_error() {
2003            match serde_json::from_str::<crate::datadogV2::model::MetricVolumesResponse>(
2004                &local_content,
2005            ) {
2006                Ok(e) => {
2007                    return Ok(datadog::ResponseContent {
2008                        status: local_status,
2009                        content: local_content,
2010                        entity: Some(e),
2011                    })
2012                }
2013                Err(e) => return Err(datadog::Error::Serde(e)),
2014            };
2015        } else {
2016            let local_entity: Option<ListVolumesByMetricNameError> =
2017                serde_json::from_str(&local_content).ok();
2018            let local_error = datadog::ResponseContent {
2019                status: local_status,
2020                content: local_content,
2021                entity: local_entity,
2022            };
2023            Err(datadog::Error::ResponseError(local_error))
2024        }
2025    }
2026
2027    /// Query scalar values (as seen on Query Value, Table, and Toplist widgets).
2028    /// Multiple data sources are supported with the ability to
2029    /// process the data using formulas and functions.
2030    pub async fn query_scalar_data(
2031        &self,
2032        body: crate::datadogV2::model::ScalarFormulaQueryRequest,
2033    ) -> Result<
2034        crate::datadogV2::model::ScalarFormulaQueryResponse,
2035        datadog::Error<QueryScalarDataError>,
2036    > {
2037        match self.query_scalar_data_with_http_info(body).await {
2038            Ok(response_content) => {
2039                if let Some(e) = response_content.entity {
2040                    Ok(e)
2041                } else {
2042                    Err(datadog::Error::Serde(serde::de::Error::custom(
2043                        "response content was None",
2044                    )))
2045                }
2046            }
2047            Err(err) => Err(err),
2048        }
2049    }
2050
2051    /// Query scalar values (as seen on Query Value, Table, and Toplist widgets).
2052    /// Multiple data sources are supported with the ability to
2053    /// process the data using formulas and functions.
2054    pub async fn query_scalar_data_with_http_info(
2055        &self,
2056        body: crate::datadogV2::model::ScalarFormulaQueryRequest,
2057    ) -> Result<
2058        datadog::ResponseContent<crate::datadogV2::model::ScalarFormulaQueryResponse>,
2059        datadog::Error<QueryScalarDataError>,
2060    > {
2061        let local_configuration = &self.config;
2062        let operation_id = "v2.query_scalar_data";
2063
2064        let local_client = &self.client;
2065
2066        let local_uri_str = format!(
2067            "{}/api/v2/query/scalar",
2068            local_configuration.get_operation_host(operation_id)
2069        );
2070        let mut local_req_builder =
2071            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
2072
2073        // build headers
2074        let mut headers = HeaderMap::new();
2075        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
2076        headers.insert("Accept", HeaderValue::from_static("application/json"));
2077
2078        // build user agent
2079        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
2080            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
2081            Err(e) => {
2082                log::warn!("Failed to parse user agent header: {e}, falling back to default");
2083                headers.insert(
2084                    reqwest::header::USER_AGENT,
2085                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2086                )
2087            }
2088        };
2089
2090        // build auth
2091        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2092            headers.insert(
2093                "DD-API-KEY",
2094                HeaderValue::from_str(local_key.key.as_str())
2095                    .expect("failed to parse DD-API-KEY header"),
2096            );
2097        };
2098        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
2099            headers.insert(
2100                "DD-APPLICATION-KEY",
2101                HeaderValue::from_str(local_key.key.as_str())
2102                    .expect("failed to parse DD-APPLICATION-KEY header"),
2103            );
2104        };
2105
2106        // build body parameters
2107        let output = Vec::new();
2108        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2109        if body.serialize(&mut ser).is_ok() {
2110            if let Some(content_encoding) = headers.get("Content-Encoding") {
2111                match content_encoding.to_str().unwrap_or_default() {
2112                    "gzip" => {
2113                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2114                        let _ = enc.write_all(ser.into_inner().as_slice());
2115                        match enc.finish() {
2116                            Ok(buf) => {
2117                                local_req_builder = local_req_builder.body(buf);
2118                            }
2119                            Err(e) => return Err(datadog::Error::Io(e)),
2120                        }
2121                    }
2122                    "deflate" => {
2123                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2124                        let _ = enc.write_all(ser.into_inner().as_slice());
2125                        match enc.finish() {
2126                            Ok(buf) => {
2127                                local_req_builder = local_req_builder.body(buf);
2128                            }
2129                            Err(e) => return Err(datadog::Error::Io(e)),
2130                        }
2131                    }
2132                    "zstd1" => {
2133                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2134                        let _ = enc.write_all(ser.into_inner().as_slice());
2135                        match enc.finish() {
2136                            Ok(buf) => {
2137                                local_req_builder = local_req_builder.body(buf);
2138                            }
2139                            Err(e) => return Err(datadog::Error::Io(e)),
2140                        }
2141                    }
2142                    _ => {
2143                        local_req_builder = local_req_builder.body(ser.into_inner());
2144                    }
2145                }
2146            } else {
2147                local_req_builder = local_req_builder.body(ser.into_inner());
2148            }
2149        }
2150
2151        local_req_builder = local_req_builder.headers(headers);
2152        let local_req = local_req_builder.build()?;
2153        log::debug!("request content: {:?}", local_req.body());
2154        let local_resp = local_client.execute(local_req).await?;
2155
2156        let local_status = local_resp.status();
2157        let local_content = local_resp.text().await?;
2158        log::debug!("response content: {}", local_content);
2159
2160        if !local_status.is_client_error() && !local_status.is_server_error() {
2161            match serde_json::from_str::<crate::datadogV2::model::ScalarFormulaQueryResponse>(
2162                &local_content,
2163            ) {
2164                Ok(e) => {
2165                    return Ok(datadog::ResponseContent {
2166                        status: local_status,
2167                        content: local_content,
2168                        entity: Some(e),
2169                    })
2170                }
2171                Err(e) => return Err(datadog::Error::Serde(e)),
2172            };
2173        } else {
2174            let local_entity: Option<QueryScalarDataError> =
2175                serde_json::from_str(&local_content).ok();
2176            let local_error = datadog::ResponseContent {
2177                status: local_status,
2178                content: local_content,
2179                entity: local_entity,
2180            };
2181            Err(datadog::Error::ResponseError(local_error))
2182        }
2183    }
2184
2185    /// Query timeseries data across various data sources and
2186    /// process the data by applying formulas and functions.
2187    pub async fn query_timeseries_data(
2188        &self,
2189        body: crate::datadogV2::model::TimeseriesFormulaQueryRequest,
2190    ) -> Result<
2191        crate::datadogV2::model::TimeseriesFormulaQueryResponse,
2192        datadog::Error<QueryTimeseriesDataError>,
2193    > {
2194        match self.query_timeseries_data_with_http_info(body).await {
2195            Ok(response_content) => {
2196                if let Some(e) = response_content.entity {
2197                    Ok(e)
2198                } else {
2199                    Err(datadog::Error::Serde(serde::de::Error::custom(
2200                        "response content was None",
2201                    )))
2202                }
2203            }
2204            Err(err) => Err(err),
2205        }
2206    }
2207
2208    /// Query timeseries data across various data sources and
2209    /// process the data by applying formulas and functions.
2210    pub async fn query_timeseries_data_with_http_info(
2211        &self,
2212        body: crate::datadogV2::model::TimeseriesFormulaQueryRequest,
2213    ) -> Result<
2214        datadog::ResponseContent<crate::datadogV2::model::TimeseriesFormulaQueryResponse>,
2215        datadog::Error<QueryTimeseriesDataError>,
2216    > {
2217        let local_configuration = &self.config;
2218        let operation_id = "v2.query_timeseries_data";
2219
2220        let local_client = &self.client;
2221
2222        let local_uri_str = format!(
2223            "{}/api/v2/query/timeseries",
2224            local_configuration.get_operation_host(operation_id)
2225        );
2226        let mut local_req_builder =
2227            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
2228
2229        // build headers
2230        let mut headers = HeaderMap::new();
2231        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
2232        headers.insert("Accept", HeaderValue::from_static("application/json"));
2233
2234        // build user agent
2235        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
2236            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
2237            Err(e) => {
2238                log::warn!("Failed to parse user agent header: {e}, falling back to default");
2239                headers.insert(
2240                    reqwest::header::USER_AGENT,
2241                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2242                )
2243            }
2244        };
2245
2246        // build auth
2247        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2248            headers.insert(
2249                "DD-API-KEY",
2250                HeaderValue::from_str(local_key.key.as_str())
2251                    .expect("failed to parse DD-API-KEY header"),
2252            );
2253        };
2254        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
2255            headers.insert(
2256                "DD-APPLICATION-KEY",
2257                HeaderValue::from_str(local_key.key.as_str())
2258                    .expect("failed to parse DD-APPLICATION-KEY header"),
2259            );
2260        };
2261
2262        // build body parameters
2263        let output = Vec::new();
2264        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2265        if body.serialize(&mut ser).is_ok() {
2266            if let Some(content_encoding) = headers.get("Content-Encoding") {
2267                match content_encoding.to_str().unwrap_or_default() {
2268                    "gzip" => {
2269                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2270                        let _ = enc.write_all(ser.into_inner().as_slice());
2271                        match enc.finish() {
2272                            Ok(buf) => {
2273                                local_req_builder = local_req_builder.body(buf);
2274                            }
2275                            Err(e) => return Err(datadog::Error::Io(e)),
2276                        }
2277                    }
2278                    "deflate" => {
2279                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2280                        let _ = enc.write_all(ser.into_inner().as_slice());
2281                        match enc.finish() {
2282                            Ok(buf) => {
2283                                local_req_builder = local_req_builder.body(buf);
2284                            }
2285                            Err(e) => return Err(datadog::Error::Io(e)),
2286                        }
2287                    }
2288                    "zstd1" => {
2289                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2290                        let _ = enc.write_all(ser.into_inner().as_slice());
2291                        match enc.finish() {
2292                            Ok(buf) => {
2293                                local_req_builder = local_req_builder.body(buf);
2294                            }
2295                            Err(e) => return Err(datadog::Error::Io(e)),
2296                        }
2297                    }
2298                    _ => {
2299                        local_req_builder = local_req_builder.body(ser.into_inner());
2300                    }
2301                }
2302            } else {
2303                local_req_builder = local_req_builder.body(ser.into_inner());
2304            }
2305        }
2306
2307        local_req_builder = local_req_builder.headers(headers);
2308        let local_req = local_req_builder.build()?;
2309        log::debug!("request content: {:?}", local_req.body());
2310        let local_resp = local_client.execute(local_req).await?;
2311
2312        let local_status = local_resp.status();
2313        let local_content = local_resp.text().await?;
2314        log::debug!("response content: {}", local_content);
2315
2316        if !local_status.is_client_error() && !local_status.is_server_error() {
2317            match serde_json::from_str::<crate::datadogV2::model::TimeseriesFormulaQueryResponse>(
2318                &local_content,
2319            ) {
2320                Ok(e) => {
2321                    return Ok(datadog::ResponseContent {
2322                        status: local_status,
2323                        content: local_content,
2324                        entity: Some(e),
2325                    })
2326                }
2327                Err(e) => return Err(datadog::Error::Serde(e)),
2328            };
2329        } else {
2330            let local_entity: Option<QueryTimeseriesDataError> =
2331                serde_json::from_str(&local_content).ok();
2332            let local_error = datadog::ResponseContent {
2333                status: local_status,
2334                content: local_content,
2335                entity: local_entity,
2336            };
2337            Err(datadog::Error::ResponseError(local_error))
2338        }
2339    }
2340
2341    /// The metrics end-point allows you to post time-series data that can be graphed on Datadog’s dashboards.
2342    /// The maximum payload size is 500 kilobytes (512000 bytes). Compressed payloads must have a decompressed size of less than 5 megabytes (5242880 bytes).
2343    ///
2344    /// If you’re submitting metrics directly to the Datadog API without using DogStatsD, expect:
2345    ///
2346    /// - 64 bits for the timestamp
2347    /// - 64 bits for the value
2348    /// - 20 bytes for the metric names
2349    /// - 50 bytes for the timeseries
2350    /// - The full payload is approximately 100 bytes.
2351    ///
2352    /// Host name is one of the resources in the Resources field.
2353    pub async fn submit_metrics(
2354        &self,
2355        body: crate::datadogV2::model::MetricPayload,
2356        params: SubmitMetricsOptionalParams,
2357    ) -> Result<crate::datadogV2::model::IntakePayloadAccepted, datadog::Error<SubmitMetricsError>>
2358    {
2359        match self.submit_metrics_with_http_info(body, params).await {
2360            Ok(response_content) => {
2361                if let Some(e) = response_content.entity {
2362                    Ok(e)
2363                } else {
2364                    Err(datadog::Error::Serde(serde::de::Error::custom(
2365                        "response content was None",
2366                    )))
2367                }
2368            }
2369            Err(err) => Err(err),
2370        }
2371    }
2372
2373    /// The metrics end-point allows you to post time-series data that can be graphed on Datadog’s dashboards.
2374    /// The maximum payload size is 500 kilobytes (512000 bytes). Compressed payloads must have a decompressed size of less than 5 megabytes (5242880 bytes).
2375    ///
2376    /// If you’re submitting metrics directly to the Datadog API without using DogStatsD, expect:
2377    ///
2378    /// - 64 bits for the timestamp
2379    /// - 64 bits for the value
2380    /// - 20 bytes for the metric names
2381    /// - 50 bytes for the timeseries
2382    /// - The full payload is approximately 100 bytes.
2383    ///
2384    /// Host name is one of the resources in the Resources field.
2385    pub async fn submit_metrics_with_http_info(
2386        &self,
2387        body: crate::datadogV2::model::MetricPayload,
2388        params: SubmitMetricsOptionalParams,
2389    ) -> Result<
2390        datadog::ResponseContent<crate::datadogV2::model::IntakePayloadAccepted>,
2391        datadog::Error<SubmitMetricsError>,
2392    > {
2393        let local_configuration = &self.config;
2394        let operation_id = "v2.submit_metrics";
2395
2396        // unbox and build optional parameters
2397        let content_encoding = params.content_encoding;
2398
2399        let local_client = &self.client;
2400
2401        let local_uri_str = format!(
2402            "{}/api/v2/series",
2403            local_configuration.get_operation_host(operation_id)
2404        );
2405        let mut local_req_builder =
2406            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
2407
2408        // build headers
2409        let mut headers = HeaderMap::new();
2410        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
2411        headers.insert("Accept", HeaderValue::from_static("application/json"));
2412
2413        if let Some(ref local) = content_encoding {
2414            headers.insert(
2415                "Content-Encoding",
2416                local
2417                    .to_string()
2418                    .parse()
2419                    .expect("failed to parse Content-Encoding header"),
2420            );
2421        }
2422
2423        // build user agent
2424        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
2425            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
2426            Err(e) => {
2427                log::warn!("Failed to parse user agent header: {e}, falling back to default");
2428                headers.insert(
2429                    reqwest::header::USER_AGENT,
2430                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2431                )
2432            }
2433        };
2434
2435        // build auth
2436        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2437            headers.insert(
2438                "DD-API-KEY",
2439                HeaderValue::from_str(local_key.key.as_str())
2440                    .expect("failed to parse DD-API-KEY header"),
2441            );
2442        };
2443
2444        // build body parameters
2445        let output = Vec::new();
2446        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2447        if body.serialize(&mut ser).is_ok() {
2448            if let Some(content_encoding) = headers.get("Content-Encoding") {
2449                match content_encoding.to_str().unwrap_or_default() {
2450                    "gzip" => {
2451                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2452                        let _ = enc.write_all(ser.into_inner().as_slice());
2453                        match enc.finish() {
2454                            Ok(buf) => {
2455                                local_req_builder = local_req_builder.body(buf);
2456                            }
2457                            Err(e) => return Err(datadog::Error::Io(e)),
2458                        }
2459                    }
2460                    "deflate" => {
2461                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2462                        let _ = enc.write_all(ser.into_inner().as_slice());
2463                        match enc.finish() {
2464                            Ok(buf) => {
2465                                local_req_builder = local_req_builder.body(buf);
2466                            }
2467                            Err(e) => return Err(datadog::Error::Io(e)),
2468                        }
2469                    }
2470                    "zstd1" => {
2471                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2472                        let _ = enc.write_all(ser.into_inner().as_slice());
2473                        match enc.finish() {
2474                            Ok(buf) => {
2475                                local_req_builder = local_req_builder.body(buf);
2476                            }
2477                            Err(e) => return Err(datadog::Error::Io(e)),
2478                        }
2479                    }
2480                    _ => {
2481                        local_req_builder = local_req_builder.body(ser.into_inner());
2482                    }
2483                }
2484            } else {
2485                local_req_builder = local_req_builder.body(ser.into_inner());
2486            }
2487        }
2488
2489        local_req_builder = local_req_builder.headers(headers);
2490        let local_req = local_req_builder.build()?;
2491        log::debug!("request content: {:?}", local_req.body());
2492        let local_resp = local_client.execute(local_req).await?;
2493
2494        let local_status = local_resp.status();
2495        let local_content = local_resp.text().await?;
2496        log::debug!("response content: {}", local_content);
2497
2498        if !local_status.is_client_error() && !local_status.is_server_error() {
2499            match serde_json::from_str::<crate::datadogV2::model::IntakePayloadAccepted>(
2500                &local_content,
2501            ) {
2502                Ok(e) => {
2503                    return Ok(datadog::ResponseContent {
2504                        status: local_status,
2505                        content: local_content,
2506                        entity: Some(e),
2507                    })
2508                }
2509                Err(e) => return Err(datadog::Error::Serde(e)),
2510            };
2511        } else {
2512            let local_entity: Option<SubmitMetricsError> =
2513                serde_json::from_str(&local_content).ok();
2514            let local_error = datadog::ResponseContent {
2515                status: local_status,
2516                content: local_content,
2517                entity: local_entity,
2518            };
2519            Err(datadog::Error::ResponseError(local_error))
2520        }
2521    }
2522
2523    /// Update the tag configuration of a metric or percentile aggregations of a distribution metric or custom aggregations
2524    /// of a count, rate, or gauge metric. By setting `exclude_tags_mode` to true the behavior is changed
2525    /// from an allow-list to a deny-list, and tags in the defined list will not be queryable.
2526    /// Can only be used with application keys from users with the `Manage Tags for Metrics` permission. This endpoint requires
2527    /// a tag configuration to be created first.
2528    pub async fn update_tag_configuration(
2529        &self,
2530        metric_name: String,
2531        body: crate::datadogV2::model::MetricTagConfigurationUpdateRequest,
2532    ) -> Result<
2533        crate::datadogV2::model::MetricTagConfigurationResponse,
2534        datadog::Error<UpdateTagConfigurationError>,
2535    > {
2536        match self
2537            .update_tag_configuration_with_http_info(metric_name, body)
2538            .await
2539        {
2540            Ok(response_content) => {
2541                if let Some(e) = response_content.entity {
2542                    Ok(e)
2543                } else {
2544                    Err(datadog::Error::Serde(serde::de::Error::custom(
2545                        "response content was None",
2546                    )))
2547                }
2548            }
2549            Err(err) => Err(err),
2550        }
2551    }
2552
2553    /// Update the tag configuration of a metric or percentile aggregations of a distribution metric or custom aggregations
2554    /// of a count, rate, or gauge metric. By setting `exclude_tags_mode` to true the behavior is changed
2555    /// from an allow-list to a deny-list, and tags in the defined list will not be queryable.
2556    /// Can only be used with application keys from users with the `Manage Tags for Metrics` permission. This endpoint requires
2557    /// a tag configuration to be created first.
2558    pub async fn update_tag_configuration_with_http_info(
2559        &self,
2560        metric_name: String,
2561        body: crate::datadogV2::model::MetricTagConfigurationUpdateRequest,
2562    ) -> Result<
2563        datadog::ResponseContent<crate::datadogV2::model::MetricTagConfigurationResponse>,
2564        datadog::Error<UpdateTagConfigurationError>,
2565    > {
2566        let local_configuration = &self.config;
2567        let operation_id = "v2.update_tag_configuration";
2568
2569        let local_client = &self.client;
2570
2571        let local_uri_str = format!(
2572            "{}/api/v2/metrics/{metric_name}/tags",
2573            local_configuration.get_operation_host(operation_id),
2574            metric_name = datadog::urlencode(metric_name)
2575        );
2576        let mut local_req_builder =
2577            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
2578
2579        // build headers
2580        let mut headers = HeaderMap::new();
2581        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
2582        headers.insert("Accept", HeaderValue::from_static("application/json"));
2583
2584        // build user agent
2585        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
2586            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
2587            Err(e) => {
2588                log::warn!("Failed to parse user agent header: {e}, falling back to default");
2589                headers.insert(
2590                    reqwest::header::USER_AGENT,
2591                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2592                )
2593            }
2594        };
2595
2596        // build auth
2597        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2598            headers.insert(
2599                "DD-API-KEY",
2600                HeaderValue::from_str(local_key.key.as_str())
2601                    .expect("failed to parse DD-API-KEY header"),
2602            );
2603        };
2604        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
2605            headers.insert(
2606                "DD-APPLICATION-KEY",
2607                HeaderValue::from_str(local_key.key.as_str())
2608                    .expect("failed to parse DD-APPLICATION-KEY header"),
2609            );
2610        };
2611
2612        // build body parameters
2613        let output = Vec::new();
2614        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
2615        if body.serialize(&mut ser).is_ok() {
2616            if let Some(content_encoding) = headers.get("Content-Encoding") {
2617                match content_encoding.to_str().unwrap_or_default() {
2618                    "gzip" => {
2619                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
2620                        let _ = enc.write_all(ser.into_inner().as_slice());
2621                        match enc.finish() {
2622                            Ok(buf) => {
2623                                local_req_builder = local_req_builder.body(buf);
2624                            }
2625                            Err(e) => return Err(datadog::Error::Io(e)),
2626                        }
2627                    }
2628                    "deflate" => {
2629                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
2630                        let _ = enc.write_all(ser.into_inner().as_slice());
2631                        match enc.finish() {
2632                            Ok(buf) => {
2633                                local_req_builder = local_req_builder.body(buf);
2634                            }
2635                            Err(e) => return Err(datadog::Error::Io(e)),
2636                        }
2637                    }
2638                    "zstd1" => {
2639                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
2640                        let _ = enc.write_all(ser.into_inner().as_slice());
2641                        match enc.finish() {
2642                            Ok(buf) => {
2643                                local_req_builder = local_req_builder.body(buf);
2644                            }
2645                            Err(e) => return Err(datadog::Error::Io(e)),
2646                        }
2647                    }
2648                    _ => {
2649                        local_req_builder = local_req_builder.body(ser.into_inner());
2650                    }
2651                }
2652            } else {
2653                local_req_builder = local_req_builder.body(ser.into_inner());
2654            }
2655        }
2656
2657        local_req_builder = local_req_builder.headers(headers);
2658        let local_req = local_req_builder.build()?;
2659        log::debug!("request content: {:?}", local_req.body());
2660        let local_resp = local_client.execute(local_req).await?;
2661
2662        let local_status = local_resp.status();
2663        let local_content = local_resp.text().await?;
2664        log::debug!("response content: {}", local_content);
2665
2666        if !local_status.is_client_error() && !local_status.is_server_error() {
2667            match serde_json::from_str::<crate::datadogV2::model::MetricTagConfigurationResponse>(
2668                &local_content,
2669            ) {
2670                Ok(e) => {
2671                    return Ok(datadog::ResponseContent {
2672                        status: local_status,
2673                        content: local_content,
2674                        entity: Some(e),
2675                    })
2676                }
2677                Err(e) => return Err(datadog::Error::Serde(e)),
2678            };
2679        } else {
2680            let local_entity: Option<UpdateTagConfigurationError> =
2681                serde_json::from_str(&local_content).ok();
2682            let local_error = datadog::ResponseContent {
2683                status: local_status,
2684                content: local_content,
2685                entity: local_entity,
2686            };
2687            Err(datadog::Error::ResponseError(local_error))
2688        }
2689    }
2690}