datadog_api_client/datadogV2/api/
api_usage_metering.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 reqwest::header::{HeaderMap, HeaderValue};
6use serde::{Deserialize, Serialize};
7
8/// GetBillingDimensionMappingOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_billing_dimension_mapping`]
9#[non_exhaustive]
10#[derive(Clone, Default, Debug)]
11pub struct GetBillingDimensionMappingOptionalParams {
12    /// Datetime in ISO-8601 format, UTC, and for mappings beginning this month. Defaults to the current month.
13    pub filter_month: Option<chrono::DateTime<chrono::Utc>>,
14    /// String to specify whether to retrieve active billing dimension mappings for the contract or for all available mappings. Allowed views have the string `active` or `all`. Defaults to `active`.
15    pub filter_view: Option<String>,
16}
17
18impl GetBillingDimensionMappingOptionalParams {
19    /// Datetime in ISO-8601 format, UTC, and for mappings beginning this month. Defaults to the current month.
20    pub fn filter_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
21        self.filter_month = Some(value);
22        self
23    }
24    /// String to specify whether to retrieve active billing dimension mappings for the contract or for all available mappings. Allowed views have the string `active` or `all`. Defaults to `active`.
25    pub fn filter_view(mut self, value: String) -> Self {
26        self.filter_view = Some(value);
27        self
28    }
29}
30
31/// GetCostByOrgOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_cost_by_org`]
32#[non_exhaustive]
33#[derive(Clone, Default, Debug)]
34pub struct GetCostByOrgOptionalParams {
35    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
36    pub end_month: Option<chrono::DateTime<chrono::Utc>>,
37}
38
39impl GetCostByOrgOptionalParams {
40    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
41    pub fn end_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
42        self.end_month = Some(value);
43        self
44    }
45}
46
47/// GetEstimatedCostByOrgOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_estimated_cost_by_org`]
48#[non_exhaustive]
49#[derive(Clone, Default, Debug)]
50pub struct GetEstimatedCostByOrgOptionalParams {
51    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`. Defaults to `summary`.
52    pub view: Option<String>,
53    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost beginning this month. **Either start_month or start_date should be specified, but not both.** (start_month cannot go beyond two months in the past). Provide an `end_month` to view month-over-month cost.
54    pub start_month: Option<chrono::DateTime<chrono::Utc>>,
55    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
56    pub end_month: Option<chrono::DateTime<chrono::Utc>>,
57    /// Datetime in ISO-8601 format, UTC, precise to day: `[YYYY-MM-DD]` for cost beginning this day. **Either start_month or start_date should be specified, but not both.** (start_date cannot go beyond two months in the past). Provide an `end_date` to view day-over-day cumulative cost.
58    pub start_date: Option<chrono::DateTime<chrono::Utc>>,
59    /// Datetime in ISO-8601 format, UTC, precise to day: `[YYYY-MM-DD]` for cost ending this day.
60    pub end_date: Option<chrono::DateTime<chrono::Utc>>,
61    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
62    pub include_connected_accounts: Option<bool>,
63}
64
65impl GetEstimatedCostByOrgOptionalParams {
66    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`. Defaults to `summary`.
67    pub fn view(mut self, value: String) -> Self {
68        self.view = Some(value);
69        self
70    }
71    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost beginning this month. **Either start_month or start_date should be specified, but not both.** (start_month cannot go beyond two months in the past). Provide an `end_month` to view month-over-month cost.
72    pub fn start_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
73        self.start_month = Some(value);
74        self
75    }
76    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
77    pub fn end_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
78        self.end_month = Some(value);
79        self
80    }
81    /// Datetime in ISO-8601 format, UTC, precise to day: `[YYYY-MM-DD]` for cost beginning this day. **Either start_month or start_date should be specified, but not both.** (start_date cannot go beyond two months in the past). Provide an `end_date` to view day-over-day cumulative cost.
82    pub fn start_date(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
83        self.start_date = Some(value);
84        self
85    }
86    /// Datetime in ISO-8601 format, UTC, precise to day: `[YYYY-MM-DD]` for cost ending this day.
87    pub fn end_date(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
88        self.end_date = Some(value);
89        self
90    }
91    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
92    pub fn include_connected_accounts(mut self, value: bool) -> Self {
93        self.include_connected_accounts = Some(value);
94        self
95    }
96}
97
98/// GetHistoricalCostByOrgOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_historical_cost_by_org`]
99#[non_exhaustive]
100#[derive(Clone, Default, Debug)]
101pub struct GetHistoricalCostByOrgOptionalParams {
102    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`.  Defaults to `summary`.
103    pub view: Option<String>,
104    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
105    pub end_month: Option<chrono::DateTime<chrono::Utc>>,
106    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
107    pub include_connected_accounts: Option<bool>,
108}
109
110impl GetHistoricalCostByOrgOptionalParams {
111    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`.  Defaults to `summary`.
112    pub fn view(mut self, value: String) -> Self {
113        self.view = Some(value);
114        self
115    }
116    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
117    pub fn end_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
118        self.end_month = Some(value);
119        self
120    }
121    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
122    pub fn include_connected_accounts(mut self, value: bool) -> Self {
123        self.include_connected_accounts = Some(value);
124        self
125    }
126}
127
128/// GetHourlyUsageOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_hourly_usage`]
129#[non_exhaustive]
130#[derive(Clone, Default, Debug)]
131pub struct GetHourlyUsageOptionalParams {
132    /// Datetime in ISO-8601 format, UTC, precise to hour: [YYYY-MM-DDThh] for usage ending **before** this hour.
133    pub filter_timestamp_end: Option<chrono::DateTime<chrono::Utc>>,
134    /// Include child org usage in the response. Defaults to false.
135    pub filter_include_descendants: Option<bool>,
136    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to false.
137    pub filter_include_connected_accounts: Option<bool>,
138    /// Include breakdown of usage by subcategories where applicable (for product family logs only). Defaults to false.
139    pub filter_include_breakdown: Option<bool>,
140    /// Comma separated list of product family versions to use in the format `product_family:version`. For example,
141    /// `infra_hosts:1.0.0`. If this parameter is not used, the API will use the latest version of each requested
142    /// product family. Currently all families have one version `1.0.0`.
143    pub filter_versions: Option<String>,
144    /// Maximum number of results to return (between 1 and 500) - defaults to 500 if limit not specified.
145    pub page_limit: Option<i32>,
146    /// List following results with a next_record_id provided in the previous query.
147    pub page_next_record_id: Option<String>,
148}
149
150impl GetHourlyUsageOptionalParams {
151    /// Datetime in ISO-8601 format, UTC, precise to hour: [YYYY-MM-DDThh] for usage ending **before** this hour.
152    pub fn filter_timestamp_end(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
153        self.filter_timestamp_end = Some(value);
154        self
155    }
156    /// Include child org usage in the response. Defaults to false.
157    pub fn filter_include_descendants(mut self, value: bool) -> Self {
158        self.filter_include_descendants = Some(value);
159        self
160    }
161    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to false.
162    pub fn filter_include_connected_accounts(mut self, value: bool) -> Self {
163        self.filter_include_connected_accounts = Some(value);
164        self
165    }
166    /// Include breakdown of usage by subcategories where applicable (for product family logs only). Defaults to false.
167    pub fn filter_include_breakdown(mut self, value: bool) -> Self {
168        self.filter_include_breakdown = Some(value);
169        self
170    }
171    /// Comma separated list of product family versions to use in the format `product_family:version`. For example,
172    /// `infra_hosts:1.0.0`. If this parameter is not used, the API will use the latest version of each requested
173    /// product family. Currently all families have one version `1.0.0`.
174    pub fn filter_versions(mut self, value: String) -> Self {
175        self.filter_versions = Some(value);
176        self
177    }
178    /// Maximum number of results to return (between 1 and 500) - defaults to 500 if limit not specified.
179    pub fn page_limit(mut self, value: i32) -> Self {
180        self.page_limit = Some(value);
181        self
182    }
183    /// List following results with a next_record_id provided in the previous query.
184    pub fn page_next_record_id(mut self, value: String) -> Self {
185        self.page_next_record_id = Some(value);
186        self
187    }
188}
189
190/// GetMonthlyCostAttributionOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_monthly_cost_attribution`]
191#[non_exhaustive]
192#[derive(Clone, Default, Debug)]
193pub struct GetMonthlyCostAttributionOptionalParams {
194    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
195    pub end_month: Option<chrono::DateTime<chrono::Utc>>,
196    /// The direction to sort by: `[desc, asc]`.
197    pub sort_direction: Option<crate::datadogV2::model::SortDirection>,
198    /// The billing dimension to sort by. Always sorted by total cost. Example: `infra_host`.
199    pub sort_name: Option<String>,
200    /// Comma separated list of tag keys used to group cost. If no value is provided the cost will not be broken down by tags.
201    /// To see which tags are available, look for the value of `tag_config_source` in the API response.
202    pub tag_breakdown_keys: Option<String>,
203    /// List following results with a next_record_id provided in the previous query.
204    pub next_record_id: Option<String>,
205    /// Include child org cost in the response. Defaults to `true`.
206    pub include_descendants: Option<bool>,
207}
208
209impl GetMonthlyCostAttributionOptionalParams {
210    /// Datetime in ISO-8601 format, UTC, precise to month: `[YYYY-MM]` for cost ending this month.
211    pub fn end_month(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
212        self.end_month = Some(value);
213        self
214    }
215    /// The direction to sort by: `[desc, asc]`.
216    pub fn sort_direction(mut self, value: crate::datadogV2::model::SortDirection) -> Self {
217        self.sort_direction = Some(value);
218        self
219    }
220    /// The billing dimension to sort by. Always sorted by total cost. Example: `infra_host`.
221    pub fn sort_name(mut self, value: String) -> Self {
222        self.sort_name = Some(value);
223        self
224    }
225    /// Comma separated list of tag keys used to group cost. If no value is provided the cost will not be broken down by tags.
226    /// To see which tags are available, look for the value of `tag_config_source` in the API response.
227    pub fn tag_breakdown_keys(mut self, value: String) -> Self {
228        self.tag_breakdown_keys = Some(value);
229        self
230    }
231    /// List following results with a next_record_id provided in the previous query.
232    pub fn next_record_id(mut self, value: String) -> Self {
233        self.next_record_id = Some(value);
234        self
235    }
236    /// Include child org cost in the response. Defaults to `true`.
237    pub fn include_descendants(mut self, value: bool) -> Self {
238        self.include_descendants = Some(value);
239        self
240    }
241}
242
243/// GetProjectedCostOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_projected_cost`]
244#[non_exhaustive]
245#[derive(Clone, Default, Debug)]
246pub struct GetProjectedCostOptionalParams {
247    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`. Defaults to `summary`.
248    pub view: Option<String>,
249    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
250    pub include_connected_accounts: Option<bool>,
251}
252
253impl GetProjectedCostOptionalParams {
254    /// String to specify whether cost is broken down at a parent-org level or at the sub-org level. Available views are `summary` and `sub-org`. Defaults to `summary`.
255    pub fn view(mut self, value: String) -> Self {
256        self.view = Some(value);
257        self
258    }
259    /// Boolean to specify whether to include accounts connected to the current account as partner customers in the Datadog partner network program. Defaults to `false`.
260    pub fn include_connected_accounts(mut self, value: bool) -> Self {
261        self.include_connected_accounts = Some(value);
262        self
263    }
264}
265
266/// GetUsageApplicationSecurityMonitoringOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_usage_application_security_monitoring`]
267#[non_exhaustive]
268#[derive(Clone, Default, Debug)]
269pub struct GetUsageApplicationSecurityMonitoringOptionalParams {
270    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
271    /// **before** this hour.
272    pub end_hr: Option<chrono::DateTime<chrono::Utc>>,
273}
274
275impl GetUsageApplicationSecurityMonitoringOptionalParams {
276    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
277    /// **before** this hour.
278    pub fn end_hr(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
279        self.end_hr = Some(value);
280        self
281    }
282}
283
284/// GetUsageLambdaTracedInvocationsOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_usage_lambda_traced_invocations`]
285#[non_exhaustive]
286#[derive(Clone, Default, Debug)]
287pub struct GetUsageLambdaTracedInvocationsOptionalParams {
288    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
289    /// **before** this hour.
290    pub end_hr: Option<chrono::DateTime<chrono::Utc>>,
291}
292
293impl GetUsageLambdaTracedInvocationsOptionalParams {
294    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
295    /// **before** this hour.
296    pub fn end_hr(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
297        self.end_hr = Some(value);
298        self
299    }
300}
301
302/// GetUsageObservabilityPipelinesOptionalParams is a struct for passing parameters to the method [`UsageMeteringAPI::get_usage_observability_pipelines`]
303#[non_exhaustive]
304#[derive(Clone, Default, Debug)]
305pub struct GetUsageObservabilityPipelinesOptionalParams {
306    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
307    /// **before** this hour.
308    pub end_hr: Option<chrono::DateTime<chrono::Utc>>,
309}
310
311impl GetUsageObservabilityPipelinesOptionalParams {
312    /// Datetime in ISO-8601 format, UTC, precise to hour: `[YYYY-MM-DDThh]` for usage ending
313    /// **before** this hour.
314    pub fn end_hr(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
315        self.end_hr = Some(value);
316        self
317    }
318}
319
320/// GetActiveBillingDimensionsError is a struct for typed errors of method [`UsageMeteringAPI::get_active_billing_dimensions`]
321#[derive(Debug, Clone, Serialize, Deserialize)]
322#[serde(untagged)]
323pub enum GetActiveBillingDimensionsError {
324    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
325    UnknownValue(serde_json::Value),
326}
327
328/// GetBillingDimensionMappingError is a struct for typed errors of method [`UsageMeteringAPI::get_billing_dimension_mapping`]
329#[derive(Debug, Clone, Serialize, Deserialize)]
330#[serde(untagged)]
331pub enum GetBillingDimensionMappingError {
332    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
333    UnknownValue(serde_json::Value),
334}
335
336/// GetCostByOrgError is a struct for typed errors of method [`UsageMeteringAPI::get_cost_by_org`]
337#[derive(Debug, Clone, Serialize, Deserialize)]
338#[serde(untagged)]
339pub enum GetCostByOrgError {
340    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
341    UnknownValue(serde_json::Value),
342}
343
344/// GetEstimatedCostByOrgError is a struct for typed errors of method [`UsageMeteringAPI::get_estimated_cost_by_org`]
345#[derive(Debug, Clone, Serialize, Deserialize)]
346#[serde(untagged)]
347pub enum GetEstimatedCostByOrgError {
348    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
349    UnknownValue(serde_json::Value),
350}
351
352/// GetHistoricalCostByOrgError is a struct for typed errors of method [`UsageMeteringAPI::get_historical_cost_by_org`]
353#[derive(Debug, Clone, Serialize, Deserialize)]
354#[serde(untagged)]
355pub enum GetHistoricalCostByOrgError {
356    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
357    UnknownValue(serde_json::Value),
358}
359
360/// GetHourlyUsageError is a struct for typed errors of method [`UsageMeteringAPI::get_hourly_usage`]
361#[derive(Debug, Clone, Serialize, Deserialize)]
362#[serde(untagged)]
363pub enum GetHourlyUsageError {
364    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
365    UnknownValue(serde_json::Value),
366}
367
368/// GetMonthlyCostAttributionError is a struct for typed errors of method [`UsageMeteringAPI::get_monthly_cost_attribution`]
369#[derive(Debug, Clone, Serialize, Deserialize)]
370#[serde(untagged)]
371pub enum GetMonthlyCostAttributionError {
372    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
373    UnknownValue(serde_json::Value),
374}
375
376/// GetProjectedCostError is a struct for typed errors of method [`UsageMeteringAPI::get_projected_cost`]
377#[derive(Debug, Clone, Serialize, Deserialize)]
378#[serde(untagged)]
379pub enum GetProjectedCostError {
380    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
381    UnknownValue(serde_json::Value),
382}
383
384/// GetUsageApplicationSecurityMonitoringError is a struct for typed errors of method [`UsageMeteringAPI::get_usage_application_security_monitoring`]
385#[derive(Debug, Clone, Serialize, Deserialize)]
386#[serde(untagged)]
387pub enum GetUsageApplicationSecurityMonitoringError {
388    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
389    UnknownValue(serde_json::Value),
390}
391
392/// GetUsageLambdaTracedInvocationsError is a struct for typed errors of method [`UsageMeteringAPI::get_usage_lambda_traced_invocations`]
393#[derive(Debug, Clone, Serialize, Deserialize)]
394#[serde(untagged)]
395pub enum GetUsageLambdaTracedInvocationsError {
396    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
397    UnknownValue(serde_json::Value),
398}
399
400/// GetUsageObservabilityPipelinesError is a struct for typed errors of method [`UsageMeteringAPI::get_usage_observability_pipelines`]
401#[derive(Debug, Clone, Serialize, Deserialize)]
402#[serde(untagged)]
403pub enum GetUsageObservabilityPipelinesError {
404    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
405    UnknownValue(serde_json::Value),
406}
407
408/// The usage metering API allows you to get hourly, daily, and
409/// monthly usage across multiple facets of Datadog.
410/// This API is available to all Pro and Enterprise customers.
411///
412/// **Note**: Usage data is delayed by up to 72 hours from when it was incurred.
413/// It is retained for 15 months.
414///
415/// You can retrieve up to 24 hours of hourly usage data for multiple organizations,
416/// and up to two months of hourly usage data for a single organization in one request.
417/// Learn more on the [usage details documentation](<https://docs.datadoghq.com/account_management/billing/usage_details/>).
418#[derive(Debug, Clone)]
419pub struct UsageMeteringAPI {
420    config: datadog::Configuration,
421    client: reqwest_middleware::ClientWithMiddleware,
422}
423
424impl Default for UsageMeteringAPI {
425    fn default() -> Self {
426        Self::with_config(datadog::Configuration::default())
427    }
428}
429
430impl UsageMeteringAPI {
431    pub fn new() -> Self {
432        Self::default()
433    }
434    pub fn with_config(config: datadog::Configuration) -> Self {
435        let mut reqwest_client_builder = reqwest::Client::builder();
436
437        if let Some(proxy_url) = &config.proxy_url {
438            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
439            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
440        }
441
442        let mut middleware_client_builder =
443            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
444
445        if config.enable_retry {
446            struct RetryableStatus;
447            impl reqwest_retry::RetryableStrategy for RetryableStatus {
448                fn handle(
449                    &self,
450                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
451                ) -> Option<reqwest_retry::Retryable> {
452                    match res {
453                        Ok(success) => reqwest_retry::default_on_request_success(success),
454                        Err(_) => None,
455                    }
456                }
457            }
458            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
459                .build_with_max_retries(config.max_retries);
460
461            let retry_middleware =
462                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
463                    backoff_policy,
464                    RetryableStatus,
465                );
466
467            middleware_client_builder = middleware_client_builder.with(retry_middleware);
468        }
469
470        let client = middleware_client_builder.build();
471
472        Self { config, client }
473    }
474
475    pub fn with_client_and_config(
476        config: datadog::Configuration,
477        client: reqwest_middleware::ClientWithMiddleware,
478    ) -> Self {
479        Self { config, client }
480    }
481
482    /// Get active billing dimensions for cost attribution. Cost data for a given month becomes available no later than the 19th of the following month.
483    pub async fn get_active_billing_dimensions(
484        &self,
485    ) -> Result<
486        crate::datadogV2::model::ActiveBillingDimensionsResponse,
487        datadog::Error<GetActiveBillingDimensionsError>,
488    > {
489        match self.get_active_billing_dimensions_with_http_info().await {
490            Ok(response_content) => {
491                if let Some(e) = response_content.entity {
492                    Ok(e)
493                } else {
494                    Err(datadog::Error::Serde(serde::de::Error::custom(
495                        "response content was None",
496                    )))
497                }
498            }
499            Err(err) => Err(err),
500        }
501    }
502
503    /// Get active billing dimensions for cost attribution. Cost data for a given month becomes available no later than the 19th of the following month.
504    pub async fn get_active_billing_dimensions_with_http_info(
505        &self,
506    ) -> Result<
507        datadog::ResponseContent<crate::datadogV2::model::ActiveBillingDimensionsResponse>,
508        datadog::Error<GetActiveBillingDimensionsError>,
509    > {
510        let local_configuration = &self.config;
511        let operation_id = "v2.get_active_billing_dimensions";
512
513        let local_client = &self.client;
514
515        let local_uri_str = format!(
516            "{}/api/v2/cost_by_tag/active_billing_dimensions",
517            local_configuration.get_operation_host(operation_id)
518        );
519        let mut local_req_builder =
520            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
521
522        // build headers
523        let mut headers = HeaderMap::new();
524        headers.insert(
525            "Accept",
526            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
527        );
528
529        // build user agent
530        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
531            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
532            Err(e) => {
533                log::warn!("Failed to parse user agent header: {e}, falling back to default");
534                headers.insert(
535                    reqwest::header::USER_AGENT,
536                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
537                )
538            }
539        };
540
541        // build auth
542        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
543            headers.insert(
544                "DD-API-KEY",
545                HeaderValue::from_str(local_key.key.as_str())
546                    .expect("failed to parse DD-API-KEY header"),
547            );
548        };
549        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
550            headers.insert(
551                "DD-APPLICATION-KEY",
552                HeaderValue::from_str(local_key.key.as_str())
553                    .expect("failed to parse DD-APPLICATION-KEY header"),
554            );
555        };
556
557        local_req_builder = local_req_builder.headers(headers);
558        let local_req = local_req_builder.build()?;
559        log::debug!("request content: {:?}", local_req.body());
560        let local_resp = local_client.execute(local_req).await?;
561
562        let local_status = local_resp.status();
563        let local_content = local_resp.text().await?;
564        log::debug!("response content: {}", local_content);
565
566        if !local_status.is_client_error() && !local_status.is_server_error() {
567            match serde_json::from_str::<crate::datadogV2::model::ActiveBillingDimensionsResponse>(
568                &local_content,
569            ) {
570                Ok(e) => {
571                    return Ok(datadog::ResponseContent {
572                        status: local_status,
573                        content: local_content,
574                        entity: Some(e),
575                    })
576                }
577                Err(e) => return Err(datadog::Error::Serde(e)),
578            };
579        } else {
580            let local_entity: Option<GetActiveBillingDimensionsError> =
581                serde_json::from_str(&local_content).ok();
582            let local_error = datadog::ResponseContent {
583                status: local_status,
584                content: local_content,
585                entity: local_entity,
586            };
587            Err(datadog::Error::ResponseError(local_error))
588        }
589    }
590
591    /// Get a mapping of billing dimensions to the corresponding keys for the supported usage metering public API endpoints.
592    /// Mapping data is updated on a monthly cadence.
593    ///
594    /// This endpoint is only accessible to [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
595    pub async fn get_billing_dimension_mapping(
596        &self,
597        params: GetBillingDimensionMappingOptionalParams,
598    ) -> Result<
599        crate::datadogV2::model::BillingDimensionsMappingResponse,
600        datadog::Error<GetBillingDimensionMappingError>,
601    > {
602        match self
603            .get_billing_dimension_mapping_with_http_info(params)
604            .await
605        {
606            Ok(response_content) => {
607                if let Some(e) = response_content.entity {
608                    Ok(e)
609                } else {
610                    Err(datadog::Error::Serde(serde::de::Error::custom(
611                        "response content was None",
612                    )))
613                }
614            }
615            Err(err) => Err(err),
616        }
617    }
618
619    /// Get a mapping of billing dimensions to the corresponding keys for the supported usage metering public API endpoints.
620    /// Mapping data is updated on a monthly cadence.
621    ///
622    /// This endpoint is only accessible to [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
623    pub async fn get_billing_dimension_mapping_with_http_info(
624        &self,
625        params: GetBillingDimensionMappingOptionalParams,
626    ) -> Result<
627        datadog::ResponseContent<crate::datadogV2::model::BillingDimensionsMappingResponse>,
628        datadog::Error<GetBillingDimensionMappingError>,
629    > {
630        let local_configuration = &self.config;
631        let operation_id = "v2.get_billing_dimension_mapping";
632
633        // unbox and build optional parameters
634        let filter_month = params.filter_month;
635        let filter_view = params.filter_view;
636
637        let local_client = &self.client;
638
639        let local_uri_str = format!(
640            "{}/api/v2/usage/billing_dimension_mapping",
641            local_configuration.get_operation_host(operation_id)
642        );
643        let mut local_req_builder =
644            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
645
646        if let Some(ref local_query_param) = filter_month {
647            local_req_builder = local_req_builder.query(&[(
648                "filter[month]",
649                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
650            )]);
651        };
652        if let Some(ref local_query_param) = filter_view {
653            local_req_builder =
654                local_req_builder.query(&[("filter[view]", &local_query_param.to_string())]);
655        };
656
657        // build headers
658        let mut headers = HeaderMap::new();
659        headers.insert(
660            "Accept",
661            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
662        );
663
664        // build user agent
665        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
666            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
667            Err(e) => {
668                log::warn!("Failed to parse user agent header: {e}, falling back to default");
669                headers.insert(
670                    reqwest::header::USER_AGENT,
671                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
672                )
673            }
674        };
675
676        // build auth
677        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
678            headers.insert(
679                "DD-API-KEY",
680                HeaderValue::from_str(local_key.key.as_str())
681                    .expect("failed to parse DD-API-KEY header"),
682            );
683        };
684        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
685            headers.insert(
686                "DD-APPLICATION-KEY",
687                HeaderValue::from_str(local_key.key.as_str())
688                    .expect("failed to parse DD-APPLICATION-KEY header"),
689            );
690        };
691
692        local_req_builder = local_req_builder.headers(headers);
693        let local_req = local_req_builder.build()?;
694        log::debug!("request content: {:?}", local_req.body());
695        let local_resp = local_client.execute(local_req).await?;
696
697        let local_status = local_resp.status();
698        let local_content = local_resp.text().await?;
699        log::debug!("response content: {}", local_content);
700
701        if !local_status.is_client_error() && !local_status.is_server_error() {
702            match serde_json::from_str::<crate::datadogV2::model::BillingDimensionsMappingResponse>(
703                &local_content,
704            ) {
705                Ok(e) => {
706                    return Ok(datadog::ResponseContent {
707                        status: local_status,
708                        content: local_content,
709                        entity: Some(e),
710                    })
711                }
712                Err(e) => return Err(datadog::Error::Serde(e)),
713            };
714        } else {
715            let local_entity: Option<GetBillingDimensionMappingError> =
716                serde_json::from_str(&local_content).ok();
717            let local_error = datadog::ResponseContent {
718                status: local_status,
719                content: local_content,
720                entity: local_entity,
721            };
722            Err(datadog::Error::ResponseError(local_error))
723        }
724    }
725
726    /// Get cost across multi-org account.
727    /// Cost by org data for a given month becomes available no later than the 16th of the following month.
728    /// **Note:** This endpoint has been deprecated. Please use the new endpoint
729    /// [`/historical_cost`](<https://docs.datadoghq.com/api/latest/usage-metering/#get-historical-cost-across-your-account>)
730    /// instead.
731    ///
732    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
733    pub async fn get_cost_by_org(
734        &self,
735        start_month: chrono::DateTime<chrono::Utc>,
736        params: GetCostByOrgOptionalParams,
737    ) -> Result<crate::datadogV2::model::CostByOrgResponse, datadog::Error<GetCostByOrgError>> {
738        match self
739            .get_cost_by_org_with_http_info(start_month, params)
740            .await
741        {
742            Ok(response_content) => {
743                if let Some(e) = response_content.entity {
744                    Ok(e)
745                } else {
746                    Err(datadog::Error::Serde(serde::de::Error::custom(
747                        "response content was None",
748                    )))
749                }
750            }
751            Err(err) => Err(err),
752        }
753    }
754
755    /// Get cost across multi-org account.
756    /// Cost by org data for a given month becomes available no later than the 16th of the following month.
757    /// **Note:** This endpoint has been deprecated. Please use the new endpoint
758    /// [`/historical_cost`](<https://docs.datadoghq.com/api/latest/usage-metering/#get-historical-cost-across-your-account>)
759    /// instead.
760    ///
761    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
762    pub async fn get_cost_by_org_with_http_info(
763        &self,
764        start_month: chrono::DateTime<chrono::Utc>,
765        params: GetCostByOrgOptionalParams,
766    ) -> Result<
767        datadog::ResponseContent<crate::datadogV2::model::CostByOrgResponse>,
768        datadog::Error<GetCostByOrgError>,
769    > {
770        let local_configuration = &self.config;
771        let operation_id = "v2.get_cost_by_org";
772
773        // unbox and build optional parameters
774        let end_month = params.end_month;
775
776        let local_client = &self.client;
777
778        let local_uri_str = format!(
779            "{}/api/v2/usage/cost_by_org",
780            local_configuration.get_operation_host(operation_id)
781        );
782        let mut local_req_builder =
783            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
784
785        local_req_builder = local_req_builder.query(&[(
786            "start_month",
787            &start_month.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
788        )]);
789        if let Some(ref local_query_param) = end_month {
790            local_req_builder = local_req_builder.query(&[(
791                "end_month",
792                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
793            )]);
794        };
795
796        // build headers
797        let mut headers = HeaderMap::new();
798        headers.insert(
799            "Accept",
800            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
801        );
802
803        // build user agent
804        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
805            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
806            Err(e) => {
807                log::warn!("Failed to parse user agent header: {e}, falling back to default");
808                headers.insert(
809                    reqwest::header::USER_AGENT,
810                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
811                )
812            }
813        };
814
815        // build auth
816        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
817            headers.insert(
818                "DD-API-KEY",
819                HeaderValue::from_str(local_key.key.as_str())
820                    .expect("failed to parse DD-API-KEY header"),
821            );
822        };
823        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
824            headers.insert(
825                "DD-APPLICATION-KEY",
826                HeaderValue::from_str(local_key.key.as_str())
827                    .expect("failed to parse DD-APPLICATION-KEY header"),
828            );
829        };
830
831        local_req_builder = local_req_builder.headers(headers);
832        let local_req = local_req_builder.build()?;
833        log::debug!("request content: {:?}", local_req.body());
834        let local_resp = local_client.execute(local_req).await?;
835
836        let local_status = local_resp.status();
837        let local_content = local_resp.text().await?;
838        log::debug!("response content: {}", local_content);
839
840        if !local_status.is_client_error() && !local_status.is_server_error() {
841            match serde_json::from_str::<crate::datadogV2::model::CostByOrgResponse>(&local_content)
842            {
843                Ok(e) => {
844                    return Ok(datadog::ResponseContent {
845                        status: local_status,
846                        content: local_content,
847                        entity: Some(e),
848                    })
849                }
850                Err(e) => return Err(datadog::Error::Serde(e)),
851            };
852        } else {
853            let local_entity: Option<GetCostByOrgError> = serde_json::from_str(&local_content).ok();
854            let local_error = datadog::ResponseContent {
855                status: local_status,
856                content: local_content,
857                entity: local_entity,
858            };
859            Err(datadog::Error::ResponseError(local_error))
860        }
861    }
862
863    /// Get estimated cost across multi-org and single root-org accounts.
864    /// Estimated cost data is only available for the current month and previous month
865    /// and is delayed by up to 72 hours from when it was incurred.
866    /// To access historical costs prior to this, use the `/historical_cost` endpoint.
867    ///
868    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
869    pub async fn get_estimated_cost_by_org(
870        &self,
871        params: GetEstimatedCostByOrgOptionalParams,
872    ) -> Result<
873        crate::datadogV2::model::CostByOrgResponse,
874        datadog::Error<GetEstimatedCostByOrgError>,
875    > {
876        match self.get_estimated_cost_by_org_with_http_info(params).await {
877            Ok(response_content) => {
878                if let Some(e) = response_content.entity {
879                    Ok(e)
880                } else {
881                    Err(datadog::Error::Serde(serde::de::Error::custom(
882                        "response content was None",
883                    )))
884                }
885            }
886            Err(err) => Err(err),
887        }
888    }
889
890    /// Get estimated cost across multi-org and single root-org accounts.
891    /// Estimated cost data is only available for the current month and previous month
892    /// and is delayed by up to 72 hours from when it was incurred.
893    /// To access historical costs prior to this, use the `/historical_cost` endpoint.
894    ///
895    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
896    pub async fn get_estimated_cost_by_org_with_http_info(
897        &self,
898        params: GetEstimatedCostByOrgOptionalParams,
899    ) -> Result<
900        datadog::ResponseContent<crate::datadogV2::model::CostByOrgResponse>,
901        datadog::Error<GetEstimatedCostByOrgError>,
902    > {
903        let local_configuration = &self.config;
904        let operation_id = "v2.get_estimated_cost_by_org";
905
906        // unbox and build optional parameters
907        let view = params.view;
908        let start_month = params.start_month;
909        let end_month = params.end_month;
910        let start_date = params.start_date;
911        let end_date = params.end_date;
912        let include_connected_accounts = params.include_connected_accounts;
913
914        let local_client = &self.client;
915
916        let local_uri_str = format!(
917            "{}/api/v2/usage/estimated_cost",
918            local_configuration.get_operation_host(operation_id)
919        );
920        let mut local_req_builder =
921            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
922
923        if let Some(ref local_query_param) = view {
924            local_req_builder =
925                local_req_builder.query(&[("view", &local_query_param.to_string())]);
926        };
927        if let Some(ref local_query_param) = start_month {
928            local_req_builder = local_req_builder.query(&[(
929                "start_month",
930                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
931            )]);
932        };
933        if let Some(ref local_query_param) = end_month {
934            local_req_builder = local_req_builder.query(&[(
935                "end_month",
936                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
937            )]);
938        };
939        if let Some(ref local_query_param) = start_date {
940            local_req_builder = local_req_builder.query(&[(
941                "start_date",
942                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
943            )]);
944        };
945        if let Some(ref local_query_param) = end_date {
946            local_req_builder = local_req_builder.query(&[(
947                "end_date",
948                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
949            )]);
950        };
951        if let Some(ref local_query_param) = include_connected_accounts {
952            local_req_builder = local_req_builder
953                .query(&[("include_connected_accounts", &local_query_param.to_string())]);
954        };
955
956        // build headers
957        let mut headers = HeaderMap::new();
958        headers.insert(
959            "Accept",
960            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
961        );
962
963        // build user agent
964        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
965            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
966            Err(e) => {
967                log::warn!("Failed to parse user agent header: {e}, falling back to default");
968                headers.insert(
969                    reqwest::header::USER_AGENT,
970                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
971                )
972            }
973        };
974
975        // build auth
976        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
977            headers.insert(
978                "DD-API-KEY",
979                HeaderValue::from_str(local_key.key.as_str())
980                    .expect("failed to parse DD-API-KEY header"),
981            );
982        };
983        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
984            headers.insert(
985                "DD-APPLICATION-KEY",
986                HeaderValue::from_str(local_key.key.as_str())
987                    .expect("failed to parse DD-APPLICATION-KEY header"),
988            );
989        };
990
991        local_req_builder = local_req_builder.headers(headers);
992        let local_req = local_req_builder.build()?;
993        log::debug!("request content: {:?}", local_req.body());
994        let local_resp = local_client.execute(local_req).await?;
995
996        let local_status = local_resp.status();
997        let local_content = local_resp.text().await?;
998        log::debug!("response content: {}", local_content);
999
1000        if !local_status.is_client_error() && !local_status.is_server_error() {
1001            match serde_json::from_str::<crate::datadogV2::model::CostByOrgResponse>(&local_content)
1002            {
1003                Ok(e) => {
1004                    return Ok(datadog::ResponseContent {
1005                        status: local_status,
1006                        content: local_content,
1007                        entity: Some(e),
1008                    })
1009                }
1010                Err(e) => return Err(datadog::Error::Serde(e)),
1011            };
1012        } else {
1013            let local_entity: Option<GetEstimatedCostByOrgError> =
1014                serde_json::from_str(&local_content).ok();
1015            let local_error = datadog::ResponseContent {
1016                status: local_status,
1017                content: local_content,
1018                entity: local_entity,
1019            };
1020            Err(datadog::Error::ResponseError(local_error))
1021        }
1022    }
1023
1024    /// Get historical cost across multi-org and single root-org accounts.
1025    /// Cost data for a given month becomes available no later than the 16th of the following month.
1026    ///
1027    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
1028    pub async fn get_historical_cost_by_org(
1029        &self,
1030        start_month: chrono::DateTime<chrono::Utc>,
1031        params: GetHistoricalCostByOrgOptionalParams,
1032    ) -> Result<
1033        crate::datadogV2::model::CostByOrgResponse,
1034        datadog::Error<GetHistoricalCostByOrgError>,
1035    > {
1036        match self
1037            .get_historical_cost_by_org_with_http_info(start_month, params)
1038            .await
1039        {
1040            Ok(response_content) => {
1041                if let Some(e) = response_content.entity {
1042                    Ok(e)
1043                } else {
1044                    Err(datadog::Error::Serde(serde::de::Error::custom(
1045                        "response content was None",
1046                    )))
1047                }
1048            }
1049            Err(err) => Err(err),
1050        }
1051    }
1052
1053    /// Get historical cost across multi-org and single root-org accounts.
1054    /// Cost data for a given month becomes available no later than the 16th of the following month.
1055    ///
1056    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
1057    pub async fn get_historical_cost_by_org_with_http_info(
1058        &self,
1059        start_month: chrono::DateTime<chrono::Utc>,
1060        params: GetHistoricalCostByOrgOptionalParams,
1061    ) -> Result<
1062        datadog::ResponseContent<crate::datadogV2::model::CostByOrgResponse>,
1063        datadog::Error<GetHistoricalCostByOrgError>,
1064    > {
1065        let local_configuration = &self.config;
1066        let operation_id = "v2.get_historical_cost_by_org";
1067
1068        // unbox and build optional parameters
1069        let view = params.view;
1070        let end_month = params.end_month;
1071        let include_connected_accounts = params.include_connected_accounts;
1072
1073        let local_client = &self.client;
1074
1075        let local_uri_str = format!(
1076            "{}/api/v2/usage/historical_cost",
1077            local_configuration.get_operation_host(operation_id)
1078        );
1079        let mut local_req_builder =
1080            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1081
1082        local_req_builder = local_req_builder.query(&[(
1083            "start_month",
1084            &start_month.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1085        )]);
1086        if let Some(ref local_query_param) = view {
1087            local_req_builder =
1088                local_req_builder.query(&[("view", &local_query_param.to_string())]);
1089        };
1090        if let Some(ref local_query_param) = end_month {
1091            local_req_builder = local_req_builder.query(&[(
1092                "end_month",
1093                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1094            )]);
1095        };
1096        if let Some(ref local_query_param) = include_connected_accounts {
1097            local_req_builder = local_req_builder
1098                .query(&[("include_connected_accounts", &local_query_param.to_string())]);
1099        };
1100
1101        // build headers
1102        let mut headers = HeaderMap::new();
1103        headers.insert(
1104            "Accept",
1105            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1106        );
1107
1108        // build user agent
1109        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1110            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1111            Err(e) => {
1112                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1113                headers.insert(
1114                    reqwest::header::USER_AGENT,
1115                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1116                )
1117            }
1118        };
1119
1120        // build auth
1121        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1122            headers.insert(
1123                "DD-API-KEY",
1124                HeaderValue::from_str(local_key.key.as_str())
1125                    .expect("failed to parse DD-API-KEY header"),
1126            );
1127        };
1128        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1129            headers.insert(
1130                "DD-APPLICATION-KEY",
1131                HeaderValue::from_str(local_key.key.as_str())
1132                    .expect("failed to parse DD-APPLICATION-KEY header"),
1133            );
1134        };
1135
1136        local_req_builder = local_req_builder.headers(headers);
1137        let local_req = local_req_builder.build()?;
1138        log::debug!("request content: {:?}", local_req.body());
1139        let local_resp = local_client.execute(local_req).await?;
1140
1141        let local_status = local_resp.status();
1142        let local_content = local_resp.text().await?;
1143        log::debug!("response content: {}", local_content);
1144
1145        if !local_status.is_client_error() && !local_status.is_server_error() {
1146            match serde_json::from_str::<crate::datadogV2::model::CostByOrgResponse>(&local_content)
1147            {
1148                Ok(e) => {
1149                    return Ok(datadog::ResponseContent {
1150                        status: local_status,
1151                        content: local_content,
1152                        entity: Some(e),
1153                    })
1154                }
1155                Err(e) => return Err(datadog::Error::Serde(e)),
1156            };
1157        } else {
1158            let local_entity: Option<GetHistoricalCostByOrgError> =
1159                serde_json::from_str(&local_content).ok();
1160            let local_error = datadog::ResponseContent {
1161                status: local_status,
1162                content: local_content,
1163                entity: local_entity,
1164            };
1165            Err(datadog::Error::ResponseError(local_error))
1166        }
1167    }
1168
1169    /// Get hourly usage by product family.
1170    pub async fn get_hourly_usage(
1171        &self,
1172        filter_timestamp_start: chrono::DateTime<chrono::Utc>,
1173        filter_product_families: String,
1174        params: GetHourlyUsageOptionalParams,
1175    ) -> Result<crate::datadogV2::model::HourlyUsageResponse, datadog::Error<GetHourlyUsageError>>
1176    {
1177        match self
1178            .get_hourly_usage_with_http_info(
1179                filter_timestamp_start,
1180                filter_product_families,
1181                params,
1182            )
1183            .await
1184        {
1185            Ok(response_content) => {
1186                if let Some(e) = response_content.entity {
1187                    Ok(e)
1188                } else {
1189                    Err(datadog::Error::Serde(serde::de::Error::custom(
1190                        "response content was None",
1191                    )))
1192                }
1193            }
1194            Err(err) => Err(err),
1195        }
1196    }
1197
1198    /// Get hourly usage by product family.
1199    pub async fn get_hourly_usage_with_http_info(
1200        &self,
1201        filter_timestamp_start: chrono::DateTime<chrono::Utc>,
1202        filter_product_families: String,
1203        params: GetHourlyUsageOptionalParams,
1204    ) -> Result<
1205        datadog::ResponseContent<crate::datadogV2::model::HourlyUsageResponse>,
1206        datadog::Error<GetHourlyUsageError>,
1207    > {
1208        let local_configuration = &self.config;
1209        let operation_id = "v2.get_hourly_usage";
1210
1211        // unbox and build optional parameters
1212        let filter_timestamp_end = params.filter_timestamp_end;
1213        let filter_include_descendants = params.filter_include_descendants;
1214        let filter_include_connected_accounts = params.filter_include_connected_accounts;
1215        let filter_include_breakdown = params.filter_include_breakdown;
1216        let filter_versions = params.filter_versions;
1217        let page_limit = params.page_limit;
1218        let page_next_record_id = params.page_next_record_id;
1219
1220        let local_client = &self.client;
1221
1222        let local_uri_str = format!(
1223            "{}/api/v2/usage/hourly_usage",
1224            local_configuration.get_operation_host(operation_id)
1225        );
1226        let mut local_req_builder =
1227            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1228
1229        local_req_builder = local_req_builder.query(&[(
1230            "filter[timestamp][start]",
1231            &filter_timestamp_start.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1232        )]);
1233        local_req_builder = local_req_builder.query(&[(
1234            "filter[product_families]",
1235            &filter_product_families.to_string(),
1236        )]);
1237        if let Some(ref local_query_param) = filter_timestamp_end {
1238            local_req_builder = local_req_builder.query(&[(
1239                "filter[timestamp][end]",
1240                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1241            )]);
1242        };
1243        if let Some(ref local_query_param) = filter_include_descendants {
1244            local_req_builder = local_req_builder.query(&[(
1245                "filter[include_descendants]",
1246                &local_query_param.to_string(),
1247            )]);
1248        };
1249        if let Some(ref local_query_param) = filter_include_connected_accounts {
1250            local_req_builder = local_req_builder.query(&[(
1251                "filter[include_connected_accounts]",
1252                &local_query_param.to_string(),
1253            )]);
1254        };
1255        if let Some(ref local_query_param) = filter_include_breakdown {
1256            local_req_builder = local_req_builder
1257                .query(&[("filter[include_breakdown]", &local_query_param.to_string())]);
1258        };
1259        if let Some(ref local_query_param) = filter_versions {
1260            local_req_builder =
1261                local_req_builder.query(&[("filter[versions]", &local_query_param.to_string())]);
1262        };
1263        if let Some(ref local_query_param) = page_limit {
1264            local_req_builder =
1265                local_req_builder.query(&[("page[limit]", &local_query_param.to_string())]);
1266        };
1267        if let Some(ref local_query_param) = page_next_record_id {
1268            local_req_builder = local_req_builder
1269                .query(&[("page[next_record_id]", &local_query_param.to_string())]);
1270        };
1271
1272        // build headers
1273        let mut headers = HeaderMap::new();
1274        headers.insert(
1275            "Accept",
1276            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1277        );
1278
1279        // build user agent
1280        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1281            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1282            Err(e) => {
1283                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1284                headers.insert(
1285                    reqwest::header::USER_AGENT,
1286                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1287                )
1288            }
1289        };
1290
1291        // build auth
1292        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1293            headers.insert(
1294                "DD-API-KEY",
1295                HeaderValue::from_str(local_key.key.as_str())
1296                    .expect("failed to parse DD-API-KEY header"),
1297            );
1298        };
1299        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1300            headers.insert(
1301                "DD-APPLICATION-KEY",
1302                HeaderValue::from_str(local_key.key.as_str())
1303                    .expect("failed to parse DD-APPLICATION-KEY header"),
1304            );
1305        };
1306
1307        local_req_builder = local_req_builder.headers(headers);
1308        let local_req = local_req_builder.build()?;
1309        log::debug!("request content: {:?}", local_req.body());
1310        let local_resp = local_client.execute(local_req).await?;
1311
1312        let local_status = local_resp.status();
1313        let local_content = local_resp.text().await?;
1314        log::debug!("response content: {}", local_content);
1315
1316        if !local_status.is_client_error() && !local_status.is_server_error() {
1317            match serde_json::from_str::<crate::datadogV2::model::HourlyUsageResponse>(
1318                &local_content,
1319            ) {
1320                Ok(e) => {
1321                    return Ok(datadog::ResponseContent {
1322                        status: local_status,
1323                        content: local_content,
1324                        entity: Some(e),
1325                    })
1326                }
1327                Err(e) => return Err(datadog::Error::Serde(e)),
1328            };
1329        } else {
1330            let local_entity: Option<GetHourlyUsageError> =
1331                serde_json::from_str(&local_content).ok();
1332            let local_error = datadog::ResponseContent {
1333                status: local_status,
1334                content: local_content,
1335                entity: local_entity,
1336            };
1337            Err(datadog::Error::ResponseError(local_error))
1338        }
1339    }
1340
1341    /// Get monthly cost attribution by tag across multi-org and single root-org accounts.
1342    /// Cost Attribution data for a given month becomes available no later than the 19th of the following month.
1343    /// This API endpoint is paginated. To make sure you receive all records, check if the value of `next_record_id` is
1344    /// set in the response. If it is, make another request and pass `next_record_id` as a parameter.
1345    /// Pseudo code example:
1346    /// ```
1347    /// response := GetMonthlyCostAttribution(start_month, end_month)
1348    /// cursor := response.metadata.pagination.next_record_id
1349    /// WHILE cursor != null BEGIN
1350    ///   sleep(5 seconds)  # Avoid running into rate limit
1351    ///   response := GetMonthlyCostAttribution(start_month, end_month, next_record_id=cursor)
1352    ///   cursor := response.metadata.pagination.next_record_id
1353    /// END
1354    /// ```
1355    ///
1356    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>). This endpoint is not available in the Government (US1-FED) site.
1357    pub async fn get_monthly_cost_attribution(
1358        &self,
1359        start_month: chrono::DateTime<chrono::Utc>,
1360        fields: String,
1361        params: GetMonthlyCostAttributionOptionalParams,
1362    ) -> Result<
1363        crate::datadogV2::model::MonthlyCostAttributionResponse,
1364        datadog::Error<GetMonthlyCostAttributionError>,
1365    > {
1366        match self
1367            .get_monthly_cost_attribution_with_http_info(start_month, fields, params)
1368            .await
1369        {
1370            Ok(response_content) => {
1371                if let Some(e) = response_content.entity {
1372                    Ok(e)
1373                } else {
1374                    Err(datadog::Error::Serde(serde::de::Error::custom(
1375                        "response content was None",
1376                    )))
1377                }
1378            }
1379            Err(err) => Err(err),
1380        }
1381    }
1382
1383    /// Get monthly cost attribution by tag across multi-org and single root-org accounts.
1384    /// Cost Attribution data for a given month becomes available no later than the 19th of the following month.
1385    /// This API endpoint is paginated. To make sure you receive all records, check if the value of `next_record_id` is
1386    /// set in the response. If it is, make another request and pass `next_record_id` as a parameter.
1387    /// Pseudo code example:
1388    /// ```
1389    /// response := GetMonthlyCostAttribution(start_month, end_month)
1390    /// cursor := response.metadata.pagination.next_record_id
1391    /// WHILE cursor != null BEGIN
1392    ///   sleep(5 seconds)  # Avoid running into rate limit
1393    ///   response := GetMonthlyCostAttribution(start_month, end_month, next_record_id=cursor)
1394    ///   cursor := response.metadata.pagination.next_record_id
1395    /// END
1396    /// ```
1397    ///
1398    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>). This endpoint is not available in the Government (US1-FED) site.
1399    pub async fn get_monthly_cost_attribution_with_http_info(
1400        &self,
1401        start_month: chrono::DateTime<chrono::Utc>,
1402        fields: String,
1403        params: GetMonthlyCostAttributionOptionalParams,
1404    ) -> Result<
1405        datadog::ResponseContent<crate::datadogV2::model::MonthlyCostAttributionResponse>,
1406        datadog::Error<GetMonthlyCostAttributionError>,
1407    > {
1408        let local_configuration = &self.config;
1409        let operation_id = "v2.get_monthly_cost_attribution";
1410
1411        // unbox and build optional parameters
1412        let end_month = params.end_month;
1413        let sort_direction = params.sort_direction;
1414        let sort_name = params.sort_name;
1415        let tag_breakdown_keys = params.tag_breakdown_keys;
1416        let next_record_id = params.next_record_id;
1417        let include_descendants = params.include_descendants;
1418
1419        let local_client = &self.client;
1420
1421        let local_uri_str = format!(
1422            "{}/api/v2/cost_by_tag/monthly_cost_attribution",
1423            local_configuration.get_operation_host(operation_id)
1424        );
1425        let mut local_req_builder =
1426            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1427
1428        local_req_builder = local_req_builder.query(&[(
1429            "start_month",
1430            &start_month.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1431        )]);
1432        local_req_builder = local_req_builder.query(&[("fields", &fields.to_string())]);
1433        if let Some(ref local_query_param) = end_month {
1434            local_req_builder = local_req_builder.query(&[(
1435                "end_month",
1436                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1437            )]);
1438        };
1439        if let Some(ref local_query_param) = sort_direction {
1440            local_req_builder =
1441                local_req_builder.query(&[("sort_direction", &local_query_param.to_string())]);
1442        };
1443        if let Some(ref local_query_param) = sort_name {
1444            local_req_builder =
1445                local_req_builder.query(&[("sort_name", &local_query_param.to_string())]);
1446        };
1447        if let Some(ref local_query_param) = tag_breakdown_keys {
1448            local_req_builder =
1449                local_req_builder.query(&[("tag_breakdown_keys", &local_query_param.to_string())]);
1450        };
1451        if let Some(ref local_query_param) = next_record_id {
1452            local_req_builder =
1453                local_req_builder.query(&[("next_record_id", &local_query_param.to_string())]);
1454        };
1455        if let Some(ref local_query_param) = include_descendants {
1456            local_req_builder =
1457                local_req_builder.query(&[("include_descendants", &local_query_param.to_string())]);
1458        };
1459
1460        // build headers
1461        let mut headers = HeaderMap::new();
1462        headers.insert(
1463            "Accept",
1464            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1465        );
1466
1467        // build user agent
1468        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1469            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1470            Err(e) => {
1471                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1472                headers.insert(
1473                    reqwest::header::USER_AGENT,
1474                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1475                )
1476            }
1477        };
1478
1479        // build auth
1480        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1481            headers.insert(
1482                "DD-API-KEY",
1483                HeaderValue::from_str(local_key.key.as_str())
1484                    .expect("failed to parse DD-API-KEY header"),
1485            );
1486        };
1487        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1488            headers.insert(
1489                "DD-APPLICATION-KEY",
1490                HeaderValue::from_str(local_key.key.as_str())
1491                    .expect("failed to parse DD-APPLICATION-KEY header"),
1492            );
1493        };
1494
1495        local_req_builder = local_req_builder.headers(headers);
1496        let local_req = local_req_builder.build()?;
1497        log::debug!("request content: {:?}", local_req.body());
1498        let local_resp = local_client.execute(local_req).await?;
1499
1500        let local_status = local_resp.status();
1501        let local_content = local_resp.text().await?;
1502        log::debug!("response content: {}", local_content);
1503
1504        if !local_status.is_client_error() && !local_status.is_server_error() {
1505            match serde_json::from_str::<crate::datadogV2::model::MonthlyCostAttributionResponse>(
1506                &local_content,
1507            ) {
1508                Ok(e) => {
1509                    return Ok(datadog::ResponseContent {
1510                        status: local_status,
1511                        content: local_content,
1512                        entity: Some(e),
1513                    })
1514                }
1515                Err(e) => return Err(datadog::Error::Serde(e)),
1516            };
1517        } else {
1518            let local_entity: Option<GetMonthlyCostAttributionError> =
1519                serde_json::from_str(&local_content).ok();
1520            let local_error = datadog::ResponseContent {
1521                status: local_status,
1522                content: local_content,
1523                entity: local_entity,
1524            };
1525            Err(datadog::Error::ResponseError(local_error))
1526        }
1527    }
1528
1529    /// Get projected cost across multi-org and single root-org accounts.
1530    /// Projected cost data is only available for the current month and becomes available around the 12th of the month.
1531    ///
1532    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
1533    pub async fn get_projected_cost(
1534        &self,
1535        params: GetProjectedCostOptionalParams,
1536    ) -> Result<crate::datadogV2::model::ProjectedCostResponse, datadog::Error<GetProjectedCostError>>
1537    {
1538        match self.get_projected_cost_with_http_info(params).await {
1539            Ok(response_content) => {
1540                if let Some(e) = response_content.entity {
1541                    Ok(e)
1542                } else {
1543                    Err(datadog::Error::Serde(serde::de::Error::custom(
1544                        "response content was None",
1545                    )))
1546                }
1547            }
1548            Err(err) => Err(err),
1549        }
1550    }
1551
1552    /// Get projected cost across multi-org and single root-org accounts.
1553    /// Projected cost data is only available for the current month and becomes available around the 12th of the month.
1554    ///
1555    /// This endpoint is only accessible for [parent-level organizations](<https://docs.datadoghq.com/account_management/multi_organization/>).
1556    pub async fn get_projected_cost_with_http_info(
1557        &self,
1558        params: GetProjectedCostOptionalParams,
1559    ) -> Result<
1560        datadog::ResponseContent<crate::datadogV2::model::ProjectedCostResponse>,
1561        datadog::Error<GetProjectedCostError>,
1562    > {
1563        let local_configuration = &self.config;
1564        let operation_id = "v2.get_projected_cost";
1565
1566        // unbox and build optional parameters
1567        let view = params.view;
1568        let include_connected_accounts = params.include_connected_accounts;
1569
1570        let local_client = &self.client;
1571
1572        let local_uri_str = format!(
1573            "{}/api/v2/usage/projected_cost",
1574            local_configuration.get_operation_host(operation_id)
1575        );
1576        let mut local_req_builder =
1577            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1578
1579        if let Some(ref local_query_param) = view {
1580            local_req_builder =
1581                local_req_builder.query(&[("view", &local_query_param.to_string())]);
1582        };
1583        if let Some(ref local_query_param) = include_connected_accounts {
1584            local_req_builder = local_req_builder
1585                .query(&[("include_connected_accounts", &local_query_param.to_string())]);
1586        };
1587
1588        // build headers
1589        let mut headers = HeaderMap::new();
1590        headers.insert(
1591            "Accept",
1592            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1593        );
1594
1595        // build user agent
1596        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1597            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1598            Err(e) => {
1599                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1600                headers.insert(
1601                    reqwest::header::USER_AGENT,
1602                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1603                )
1604            }
1605        };
1606
1607        // build auth
1608        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1609            headers.insert(
1610                "DD-API-KEY",
1611                HeaderValue::from_str(local_key.key.as_str())
1612                    .expect("failed to parse DD-API-KEY header"),
1613            );
1614        };
1615        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1616            headers.insert(
1617                "DD-APPLICATION-KEY",
1618                HeaderValue::from_str(local_key.key.as_str())
1619                    .expect("failed to parse DD-APPLICATION-KEY header"),
1620            );
1621        };
1622
1623        local_req_builder = local_req_builder.headers(headers);
1624        let local_req = local_req_builder.build()?;
1625        log::debug!("request content: {:?}", local_req.body());
1626        let local_resp = local_client.execute(local_req).await?;
1627
1628        let local_status = local_resp.status();
1629        let local_content = local_resp.text().await?;
1630        log::debug!("response content: {}", local_content);
1631
1632        if !local_status.is_client_error() && !local_status.is_server_error() {
1633            match serde_json::from_str::<crate::datadogV2::model::ProjectedCostResponse>(
1634                &local_content,
1635            ) {
1636                Ok(e) => {
1637                    return Ok(datadog::ResponseContent {
1638                        status: local_status,
1639                        content: local_content,
1640                        entity: Some(e),
1641                    })
1642                }
1643                Err(e) => return Err(datadog::Error::Serde(e)),
1644            };
1645        } else {
1646            let local_entity: Option<GetProjectedCostError> =
1647                serde_json::from_str(&local_content).ok();
1648            let local_error = datadog::ResponseContent {
1649                status: local_status,
1650                content: local_content,
1651                entity: local_entity,
1652            };
1653            Err(datadog::Error::ResponseError(local_error))
1654        }
1655    }
1656
1657    /// Get hourly usage for application security .
1658    /// **Note:** This endpoint has been deprecated. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1659    pub async fn get_usage_application_security_monitoring(
1660        &self,
1661        start_hr: chrono::DateTime<chrono::Utc>,
1662        params: GetUsageApplicationSecurityMonitoringOptionalParams,
1663    ) -> Result<
1664        crate::datadogV2::model::UsageApplicationSecurityMonitoringResponse,
1665        datadog::Error<GetUsageApplicationSecurityMonitoringError>,
1666    > {
1667        match self
1668            .get_usage_application_security_monitoring_with_http_info(start_hr, params)
1669            .await
1670        {
1671            Ok(response_content) => {
1672                if let Some(e) = response_content.entity {
1673                    Ok(e)
1674                } else {
1675                    Err(datadog::Error::Serde(serde::de::Error::custom(
1676                        "response content was None",
1677                    )))
1678                }
1679            }
1680            Err(err) => Err(err),
1681        }
1682    }
1683
1684    /// Get hourly usage for application security .
1685    /// **Note:** This endpoint has been deprecated. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1686    pub async fn get_usage_application_security_monitoring_with_http_info(
1687        &self,
1688        start_hr: chrono::DateTime<chrono::Utc>,
1689        params: GetUsageApplicationSecurityMonitoringOptionalParams,
1690    ) -> Result<
1691        datadog::ResponseContent<
1692            crate::datadogV2::model::UsageApplicationSecurityMonitoringResponse,
1693        >,
1694        datadog::Error<GetUsageApplicationSecurityMonitoringError>,
1695    > {
1696        let local_configuration = &self.config;
1697        let operation_id = "v2.get_usage_application_security_monitoring";
1698
1699        // unbox and build optional parameters
1700        let end_hr = params.end_hr;
1701
1702        let local_client = &self.client;
1703
1704        let local_uri_str = format!(
1705            "{}/api/v2/usage/application_security",
1706            local_configuration.get_operation_host(operation_id)
1707        );
1708        let mut local_req_builder =
1709            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1710
1711        local_req_builder = local_req_builder.query(&[(
1712            "start_hr",
1713            &start_hr.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1714        )]);
1715        if let Some(ref local_query_param) = end_hr {
1716            local_req_builder = local_req_builder.query(&[(
1717                "end_hr",
1718                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1719            )]);
1720        };
1721
1722        // build headers
1723        let mut headers = HeaderMap::new();
1724        headers.insert(
1725            "Accept",
1726            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1727        );
1728
1729        // build user agent
1730        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1731            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1732            Err(e) => {
1733                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1734                headers.insert(
1735                    reqwest::header::USER_AGENT,
1736                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1737                )
1738            }
1739        };
1740
1741        // build auth
1742        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1743            headers.insert(
1744                "DD-API-KEY",
1745                HeaderValue::from_str(local_key.key.as_str())
1746                    .expect("failed to parse DD-API-KEY header"),
1747            );
1748        };
1749        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1750            headers.insert(
1751                "DD-APPLICATION-KEY",
1752                HeaderValue::from_str(local_key.key.as_str())
1753                    .expect("failed to parse DD-APPLICATION-KEY header"),
1754            );
1755        };
1756
1757        local_req_builder = local_req_builder.headers(headers);
1758        let local_req = local_req_builder.build()?;
1759        log::debug!("request content: {:?}", local_req.body());
1760        let local_resp = local_client.execute(local_req).await?;
1761
1762        let local_status = local_resp.status();
1763        let local_content = local_resp.text().await?;
1764        log::debug!("response content: {}", local_content);
1765
1766        if !local_status.is_client_error() && !local_status.is_server_error() {
1767            match serde_json::from_str::<
1768                crate::datadogV2::model::UsageApplicationSecurityMonitoringResponse,
1769            >(&local_content)
1770            {
1771                Ok(e) => {
1772                    return Ok(datadog::ResponseContent {
1773                        status: local_status,
1774                        content: local_content,
1775                        entity: Some(e),
1776                    })
1777                }
1778                Err(e) => return Err(datadog::Error::Serde(e)),
1779            };
1780        } else {
1781            let local_entity: Option<GetUsageApplicationSecurityMonitoringError> =
1782                serde_json::from_str(&local_content).ok();
1783            let local_error = datadog::ResponseContent {
1784                status: local_status,
1785                content: local_content,
1786                entity: local_entity,
1787            };
1788            Err(datadog::Error::ResponseError(local_error))
1789        }
1790    }
1791
1792    /// Get hourly usage for Lambda traced invocations.
1793    /// **Note:** This endpoint has been deprecated.. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1794    pub async fn get_usage_lambda_traced_invocations(
1795        &self,
1796        start_hr: chrono::DateTime<chrono::Utc>,
1797        params: GetUsageLambdaTracedInvocationsOptionalParams,
1798    ) -> Result<
1799        crate::datadogV2::model::UsageLambdaTracedInvocationsResponse,
1800        datadog::Error<GetUsageLambdaTracedInvocationsError>,
1801    > {
1802        match self
1803            .get_usage_lambda_traced_invocations_with_http_info(start_hr, params)
1804            .await
1805        {
1806            Ok(response_content) => {
1807                if let Some(e) = response_content.entity {
1808                    Ok(e)
1809                } else {
1810                    Err(datadog::Error::Serde(serde::de::Error::custom(
1811                        "response content was None",
1812                    )))
1813                }
1814            }
1815            Err(err) => Err(err),
1816        }
1817    }
1818
1819    /// Get hourly usage for Lambda traced invocations.
1820    /// **Note:** This endpoint has been deprecated.. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1821    pub async fn get_usage_lambda_traced_invocations_with_http_info(
1822        &self,
1823        start_hr: chrono::DateTime<chrono::Utc>,
1824        params: GetUsageLambdaTracedInvocationsOptionalParams,
1825    ) -> Result<
1826        datadog::ResponseContent<crate::datadogV2::model::UsageLambdaTracedInvocationsResponse>,
1827        datadog::Error<GetUsageLambdaTracedInvocationsError>,
1828    > {
1829        let local_configuration = &self.config;
1830        let operation_id = "v2.get_usage_lambda_traced_invocations";
1831
1832        // unbox and build optional parameters
1833        let end_hr = params.end_hr;
1834
1835        let local_client = &self.client;
1836
1837        let local_uri_str = format!(
1838            "{}/api/v2/usage/lambda_traced_invocations",
1839            local_configuration.get_operation_host(operation_id)
1840        );
1841        let mut local_req_builder =
1842            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1843
1844        local_req_builder = local_req_builder.query(&[(
1845            "start_hr",
1846            &start_hr.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1847        )]);
1848        if let Some(ref local_query_param) = end_hr {
1849            local_req_builder = local_req_builder.query(&[(
1850                "end_hr",
1851                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1852            )]);
1853        };
1854
1855        // build headers
1856        let mut headers = HeaderMap::new();
1857        headers.insert(
1858            "Accept",
1859            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1860        );
1861
1862        // build user agent
1863        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1864            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1865            Err(e) => {
1866                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1867                headers.insert(
1868                    reqwest::header::USER_AGENT,
1869                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1870                )
1871            }
1872        };
1873
1874        // build auth
1875        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1876            headers.insert(
1877                "DD-API-KEY",
1878                HeaderValue::from_str(local_key.key.as_str())
1879                    .expect("failed to parse DD-API-KEY header"),
1880            );
1881        };
1882        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1883            headers.insert(
1884                "DD-APPLICATION-KEY",
1885                HeaderValue::from_str(local_key.key.as_str())
1886                    .expect("failed to parse DD-APPLICATION-KEY header"),
1887            );
1888        };
1889
1890        local_req_builder = local_req_builder.headers(headers);
1891        let local_req = local_req_builder.build()?;
1892        log::debug!("request content: {:?}", local_req.body());
1893        let local_resp = local_client.execute(local_req).await?;
1894
1895        let local_status = local_resp.status();
1896        let local_content = local_resp.text().await?;
1897        log::debug!("response content: {}", local_content);
1898
1899        if !local_status.is_client_error() && !local_status.is_server_error() {
1900            match serde_json::from_str::<
1901                crate::datadogV2::model::UsageLambdaTracedInvocationsResponse,
1902            >(&local_content)
1903            {
1904                Ok(e) => {
1905                    return Ok(datadog::ResponseContent {
1906                        status: local_status,
1907                        content: local_content,
1908                        entity: Some(e),
1909                    })
1910                }
1911                Err(e) => return Err(datadog::Error::Serde(e)),
1912            };
1913        } else {
1914            let local_entity: Option<GetUsageLambdaTracedInvocationsError> =
1915                serde_json::from_str(&local_content).ok();
1916            let local_error = datadog::ResponseContent {
1917                status: local_status,
1918                content: local_content,
1919                entity: local_entity,
1920            };
1921            Err(datadog::Error::ResponseError(local_error))
1922        }
1923    }
1924
1925    /// Get hourly usage for observability pipelines.
1926    /// **Note:** This endpoint has been deprecated. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1927    pub async fn get_usage_observability_pipelines(
1928        &self,
1929        start_hr: chrono::DateTime<chrono::Utc>,
1930        params: GetUsageObservabilityPipelinesOptionalParams,
1931    ) -> Result<
1932        crate::datadogV2::model::UsageObservabilityPipelinesResponse,
1933        datadog::Error<GetUsageObservabilityPipelinesError>,
1934    > {
1935        match self
1936            .get_usage_observability_pipelines_with_http_info(start_hr, params)
1937            .await
1938        {
1939            Ok(response_content) => {
1940                if let Some(e) = response_content.entity {
1941                    Ok(e)
1942                } else {
1943                    Err(datadog::Error::Serde(serde::de::Error::custom(
1944                        "response content was None",
1945                    )))
1946                }
1947            }
1948            Err(err) => Err(err),
1949        }
1950    }
1951
1952    /// Get hourly usage for observability pipelines.
1953    /// **Note:** This endpoint has been deprecated. Hourly usage data for all products is now available in the [Get hourly usage by product family API](<https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family>)
1954    pub async fn get_usage_observability_pipelines_with_http_info(
1955        &self,
1956        start_hr: chrono::DateTime<chrono::Utc>,
1957        params: GetUsageObservabilityPipelinesOptionalParams,
1958    ) -> Result<
1959        datadog::ResponseContent<crate::datadogV2::model::UsageObservabilityPipelinesResponse>,
1960        datadog::Error<GetUsageObservabilityPipelinesError>,
1961    > {
1962        let local_configuration = &self.config;
1963        let operation_id = "v2.get_usage_observability_pipelines";
1964
1965        // unbox and build optional parameters
1966        let end_hr = params.end_hr;
1967
1968        let local_client = &self.client;
1969
1970        let local_uri_str = format!(
1971            "{}/api/v2/usage/observability_pipelines",
1972            local_configuration.get_operation_host(operation_id)
1973        );
1974        let mut local_req_builder =
1975            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
1976
1977        local_req_builder = local_req_builder.query(&[(
1978            "start_hr",
1979            &start_hr.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1980        )]);
1981        if let Some(ref local_query_param) = end_hr {
1982            local_req_builder = local_req_builder.query(&[(
1983                "end_hr",
1984                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
1985            )]);
1986        };
1987
1988        // build headers
1989        let mut headers = HeaderMap::new();
1990        headers.insert(
1991            "Accept",
1992            HeaderValue::from_static("application/json;datetime-format=rfc3339"),
1993        );
1994
1995        // build user agent
1996        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1997            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1998            Err(e) => {
1999                log::warn!("Failed to parse user agent header: {e}, falling back to default");
2000                headers.insert(
2001                    reqwest::header::USER_AGENT,
2002                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
2003                )
2004            }
2005        };
2006
2007        // build auth
2008        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
2009            headers.insert(
2010                "DD-API-KEY",
2011                HeaderValue::from_str(local_key.key.as_str())
2012                    .expect("failed to parse DD-API-KEY header"),
2013            );
2014        };
2015        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
2016            headers.insert(
2017                "DD-APPLICATION-KEY",
2018                HeaderValue::from_str(local_key.key.as_str())
2019                    .expect("failed to parse DD-APPLICATION-KEY header"),
2020            );
2021        };
2022
2023        local_req_builder = local_req_builder.headers(headers);
2024        let local_req = local_req_builder.build()?;
2025        log::debug!("request content: {:?}", local_req.body());
2026        let local_resp = local_client.execute(local_req).await?;
2027
2028        let local_status = local_resp.status();
2029        let local_content = local_resp.text().await?;
2030        log::debug!("response content: {}", local_content);
2031
2032        if !local_status.is_client_error() && !local_status.is_server_error() {
2033            match serde_json::from_str::<crate::datadogV2::model::UsageObservabilityPipelinesResponse>(
2034                &local_content,
2035            ) {
2036                Ok(e) => {
2037                    return Ok(datadog::ResponseContent {
2038                        status: local_status,
2039                        content: local_content,
2040                        entity: Some(e),
2041                    })
2042                }
2043                Err(e) => return Err(datadog::Error::Serde(e)),
2044            };
2045        } else {
2046            let local_entity: Option<GetUsageObservabilityPipelinesError> =
2047                serde_json::from_str(&local_content).ok();
2048            let local_error = datadog::ResponseContent {
2049                status: local_status,
2050                content: local_content,
2051                entity: local_entity,
2052            };
2053            Err(datadog::Error::ResponseError(local_error))
2054        }
2055    }
2056}