datadog_api_client/datadogV2/api/
api_downtimes.rs

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