datadog_api_client/datadogV2/api/
api_on_call_paging.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use flate2::{
6    write::{GzEncoder, ZlibEncoder},
7    Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13/// AcknowledgeOnCallPageError is a struct for typed errors of method [`OnCallPagingAPI::acknowledge_on_call_page`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum AcknowledgeOnCallPageError {
17    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// CreateOnCallPageError is a struct for typed errors of method [`OnCallPagingAPI::create_on_call_page`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum CreateOnCallPageError {
25    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// EscalateOnCallPageError is a struct for typed errors of method [`OnCallPagingAPI::escalate_on_call_page`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum EscalateOnCallPageError {
33    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// ResolveOnCallPageError is a struct for typed errors of method [`OnCallPagingAPI::resolve_on_call_page`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum ResolveOnCallPageError {
41    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// Trigger and manage [Datadog On-Call](<https://docs.datadoghq.com/service_management/on-call/>)
46/// pages directly through the Datadog API.
47#[derive(Debug, Clone)]
48pub struct OnCallPagingAPI {
49    config: datadog::Configuration,
50    client: reqwest_middleware::ClientWithMiddleware,
51}
52
53impl Default for OnCallPagingAPI {
54    fn default() -> Self {
55        Self::with_config(datadog::Configuration::default())
56    }
57}
58
59impl OnCallPagingAPI {
60    pub fn new() -> Self {
61        Self::default()
62    }
63    pub fn with_config(config: datadog::Configuration) -> Self {
64        let mut reqwest_client_builder = reqwest::Client::builder();
65
66        if let Some(proxy_url) = &config.proxy_url {
67            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
68            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
69        }
70
71        let mut middleware_client_builder =
72            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
73
74        if config.enable_retry {
75            struct RetryableStatus;
76            impl reqwest_retry::RetryableStrategy for RetryableStatus {
77                fn handle(
78                    &self,
79                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
80                ) -> Option<reqwest_retry::Retryable> {
81                    match res {
82                        Ok(success) => reqwest_retry::default_on_request_success(success),
83                        Err(_) => None,
84                    }
85                }
86            }
87            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
88                .build_with_max_retries(config.max_retries);
89
90            let retry_middleware =
91                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
92                    backoff_policy,
93                    RetryableStatus,
94                );
95
96            middleware_client_builder = middleware_client_builder.with(retry_middleware);
97        }
98
99        let client = middleware_client_builder.build();
100
101        Self { config, client }
102    }
103
104    pub fn with_client_and_config(
105        config: datadog::Configuration,
106        client: reqwest_middleware::ClientWithMiddleware,
107    ) -> Self {
108        Self { config, client }
109    }
110
111    /// Acknowledges an On-Call Page.
112    ///
113    pub async fn acknowledge_on_call_page(
114        &self,
115        page_id: uuid::Uuid,
116    ) -> Result<(), datadog::Error<AcknowledgeOnCallPageError>> {
117        match self.acknowledge_on_call_page_with_http_info(page_id).await {
118            Ok(_) => Ok(()),
119            Err(err) => Err(err),
120        }
121    }
122
123    /// Acknowledges an On-Call Page.
124    ///
125    pub async fn acknowledge_on_call_page_with_http_info(
126        &self,
127        page_id: uuid::Uuid,
128    ) -> Result<datadog::ResponseContent<()>, datadog::Error<AcknowledgeOnCallPageError>> {
129        let local_configuration = &self.config;
130        let operation_id = "v2.acknowledge_on_call_page";
131
132        let local_client = &self.client;
133
134        let local_uri_str = format!(
135            "{}/api/v2/on-call/pages/{page_id}/acknowledge",
136            local_configuration.get_operation_host(operation_id),
137            page_id = datadog::urlencode(page_id.to_string())
138        );
139        let mut local_req_builder =
140            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
141
142        // build headers
143        let mut headers = HeaderMap::new();
144        headers.insert("Accept", HeaderValue::from_static("*/*"));
145
146        // build user agent
147        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
148            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
149            Err(e) => {
150                log::warn!("Failed to parse user agent header: {e}, falling back to default");
151                headers.insert(
152                    reqwest::header::USER_AGENT,
153                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
154                )
155            }
156        };
157
158        // build auth
159        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
160            headers.insert(
161                "DD-API-KEY",
162                HeaderValue::from_str(local_key.key.as_str())
163                    .expect("failed to parse DD-API-KEY header"),
164            );
165        };
166        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
167            headers.insert(
168                "DD-APPLICATION-KEY",
169                HeaderValue::from_str(local_key.key.as_str())
170                    .expect("failed to parse DD-APPLICATION-KEY header"),
171            );
172        };
173
174        local_req_builder = local_req_builder.headers(headers);
175        let local_req = local_req_builder.build()?;
176        log::debug!("request content: {:?}", local_req.body());
177        let local_resp = local_client.execute(local_req).await?;
178
179        let local_status = local_resp.status();
180        let local_content = local_resp.text().await?;
181        log::debug!("response content: {}", local_content);
182
183        if !local_status.is_client_error() && !local_status.is_server_error() {
184            Ok(datadog::ResponseContent {
185                status: local_status,
186                content: local_content,
187                entity: None,
188            })
189        } else {
190            let local_entity: Option<AcknowledgeOnCallPageError> =
191                serde_json::from_str(&local_content).ok();
192            let local_error = datadog::ResponseContent {
193                status: local_status,
194                content: local_content,
195                entity: local_entity,
196            };
197            Err(datadog::Error::ResponseError(local_error))
198        }
199    }
200
201    /// Trigger a new On-Call Page.
202    ///
203    pub async fn create_on_call_page(
204        &self,
205        body: crate::datadogV2::model::CreatePageRequest,
206    ) -> Result<crate::datadogV2::model::CreatePageResponse, datadog::Error<CreateOnCallPageError>>
207    {
208        match self.create_on_call_page_with_http_info(body).await {
209            Ok(response_content) => {
210                if let Some(e) = response_content.entity {
211                    Ok(e)
212                } else {
213                    Err(datadog::Error::Serde(serde::de::Error::custom(
214                        "response content was None",
215                    )))
216                }
217            }
218            Err(err) => Err(err),
219        }
220    }
221
222    /// Trigger a new On-Call Page.
223    ///
224    pub async fn create_on_call_page_with_http_info(
225        &self,
226        body: crate::datadogV2::model::CreatePageRequest,
227    ) -> Result<
228        datadog::ResponseContent<crate::datadogV2::model::CreatePageResponse>,
229        datadog::Error<CreateOnCallPageError>,
230    > {
231        let local_configuration = &self.config;
232        let operation_id = "v2.create_on_call_page";
233
234        let local_client = &self.client;
235
236        let local_uri_str = format!(
237            "{}/api/v2/on-call/pages",
238            local_configuration.get_operation_host(operation_id)
239        );
240        let mut local_req_builder =
241            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
242
243        // build headers
244        let mut headers = HeaderMap::new();
245        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
246        headers.insert("Accept", HeaderValue::from_static("application/json"));
247
248        // build user agent
249        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
250            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
251            Err(e) => {
252                log::warn!("Failed to parse user agent header: {e}, falling back to default");
253                headers.insert(
254                    reqwest::header::USER_AGENT,
255                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
256                )
257            }
258        };
259
260        // build auth
261        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
262            headers.insert(
263                "DD-API-KEY",
264                HeaderValue::from_str(local_key.key.as_str())
265                    .expect("failed to parse DD-API-KEY header"),
266            );
267        };
268        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
269            headers.insert(
270                "DD-APPLICATION-KEY",
271                HeaderValue::from_str(local_key.key.as_str())
272                    .expect("failed to parse DD-APPLICATION-KEY header"),
273            );
274        };
275
276        // build body parameters
277        let output = Vec::new();
278        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
279        if body.serialize(&mut ser).is_ok() {
280            if let Some(content_encoding) = headers.get("Content-Encoding") {
281                match content_encoding.to_str().unwrap_or_default() {
282                    "gzip" => {
283                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
284                        let _ = enc.write_all(ser.into_inner().as_slice());
285                        match enc.finish() {
286                            Ok(buf) => {
287                                local_req_builder = local_req_builder.body(buf);
288                            }
289                            Err(e) => return Err(datadog::Error::Io(e)),
290                        }
291                    }
292                    "deflate" => {
293                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
294                        let _ = enc.write_all(ser.into_inner().as_slice());
295                        match enc.finish() {
296                            Ok(buf) => {
297                                local_req_builder = local_req_builder.body(buf);
298                            }
299                            Err(e) => return Err(datadog::Error::Io(e)),
300                        }
301                    }
302                    "zstd1" => {
303                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
304                        let _ = enc.write_all(ser.into_inner().as_slice());
305                        match enc.finish() {
306                            Ok(buf) => {
307                                local_req_builder = local_req_builder.body(buf);
308                            }
309                            Err(e) => return Err(datadog::Error::Io(e)),
310                        }
311                    }
312                    _ => {
313                        local_req_builder = local_req_builder.body(ser.into_inner());
314                    }
315                }
316            } else {
317                local_req_builder = local_req_builder.body(ser.into_inner());
318            }
319        }
320
321        local_req_builder = local_req_builder.headers(headers);
322        let local_req = local_req_builder.build()?;
323        log::debug!("request content: {:?}", local_req.body());
324        let local_resp = local_client.execute(local_req).await?;
325
326        let local_status = local_resp.status();
327        let local_content = local_resp.text().await?;
328        log::debug!("response content: {}", local_content);
329
330        if !local_status.is_client_error() && !local_status.is_server_error() {
331            match serde_json::from_str::<crate::datadogV2::model::CreatePageResponse>(
332                &local_content,
333            ) {
334                Ok(e) => {
335                    return Ok(datadog::ResponseContent {
336                        status: local_status,
337                        content: local_content,
338                        entity: Some(e),
339                    })
340                }
341                Err(e) => return Err(datadog::Error::Serde(e)),
342            };
343        } else {
344            let local_entity: Option<CreateOnCallPageError> =
345                serde_json::from_str(&local_content).ok();
346            let local_error = datadog::ResponseContent {
347                status: local_status,
348                content: local_content,
349                entity: local_entity,
350            };
351            Err(datadog::Error::ResponseError(local_error))
352        }
353    }
354
355    /// Escalates an On-Call Page.
356    ///
357    pub async fn escalate_on_call_page(
358        &self,
359        page_id: uuid::Uuid,
360    ) -> Result<(), datadog::Error<EscalateOnCallPageError>> {
361        match self.escalate_on_call_page_with_http_info(page_id).await {
362            Ok(_) => Ok(()),
363            Err(err) => Err(err),
364        }
365    }
366
367    /// Escalates an On-Call Page.
368    ///
369    pub async fn escalate_on_call_page_with_http_info(
370        &self,
371        page_id: uuid::Uuid,
372    ) -> Result<datadog::ResponseContent<()>, datadog::Error<EscalateOnCallPageError>> {
373        let local_configuration = &self.config;
374        let operation_id = "v2.escalate_on_call_page";
375
376        let local_client = &self.client;
377
378        let local_uri_str = format!(
379            "{}/api/v2/on-call/pages/{page_id}/escalate",
380            local_configuration.get_operation_host(operation_id),
381            page_id = datadog::urlencode(page_id.to_string())
382        );
383        let mut local_req_builder =
384            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
385
386        // build headers
387        let mut headers = HeaderMap::new();
388        headers.insert("Accept", HeaderValue::from_static("*/*"));
389
390        // build user agent
391        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
392            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
393            Err(e) => {
394                log::warn!("Failed to parse user agent header: {e}, falling back to default");
395                headers.insert(
396                    reqwest::header::USER_AGENT,
397                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
398                )
399            }
400        };
401
402        // build auth
403        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
404            headers.insert(
405                "DD-API-KEY",
406                HeaderValue::from_str(local_key.key.as_str())
407                    .expect("failed to parse DD-API-KEY header"),
408            );
409        };
410        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
411            headers.insert(
412                "DD-APPLICATION-KEY",
413                HeaderValue::from_str(local_key.key.as_str())
414                    .expect("failed to parse DD-APPLICATION-KEY header"),
415            );
416        };
417
418        local_req_builder = local_req_builder.headers(headers);
419        let local_req = local_req_builder.build()?;
420        log::debug!("request content: {:?}", local_req.body());
421        let local_resp = local_client.execute(local_req).await?;
422
423        let local_status = local_resp.status();
424        let local_content = local_resp.text().await?;
425        log::debug!("response content: {}", local_content);
426
427        if !local_status.is_client_error() && !local_status.is_server_error() {
428            Ok(datadog::ResponseContent {
429                status: local_status,
430                content: local_content,
431                entity: None,
432            })
433        } else {
434            let local_entity: Option<EscalateOnCallPageError> =
435                serde_json::from_str(&local_content).ok();
436            let local_error = datadog::ResponseContent {
437                status: local_status,
438                content: local_content,
439                entity: local_entity,
440            };
441            Err(datadog::Error::ResponseError(local_error))
442        }
443    }
444
445    /// Resolves an On-Call Page.
446    ///
447    pub async fn resolve_on_call_page(
448        &self,
449        page_id: uuid::Uuid,
450    ) -> Result<(), datadog::Error<ResolveOnCallPageError>> {
451        match self.resolve_on_call_page_with_http_info(page_id).await {
452            Ok(_) => Ok(()),
453            Err(err) => Err(err),
454        }
455    }
456
457    /// Resolves an On-Call Page.
458    ///
459    pub async fn resolve_on_call_page_with_http_info(
460        &self,
461        page_id: uuid::Uuid,
462    ) -> Result<datadog::ResponseContent<()>, datadog::Error<ResolveOnCallPageError>> {
463        let local_configuration = &self.config;
464        let operation_id = "v2.resolve_on_call_page";
465
466        let local_client = &self.client;
467
468        let local_uri_str = format!(
469            "{}/api/v2/on-call/pages/{page_id}/resolve",
470            local_configuration.get_operation_host(operation_id),
471            page_id = datadog::urlencode(page_id.to_string())
472        );
473        let mut local_req_builder =
474            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
475
476        // build headers
477        let mut headers = HeaderMap::new();
478        headers.insert("Accept", HeaderValue::from_static("*/*"));
479
480        // build user agent
481        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
482            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
483            Err(e) => {
484                log::warn!("Failed to parse user agent header: {e}, falling back to default");
485                headers.insert(
486                    reqwest::header::USER_AGENT,
487                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
488                )
489            }
490        };
491
492        // build auth
493        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
494            headers.insert(
495                "DD-API-KEY",
496                HeaderValue::from_str(local_key.key.as_str())
497                    .expect("failed to parse DD-API-KEY header"),
498            );
499        };
500        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
501            headers.insert(
502                "DD-APPLICATION-KEY",
503                HeaderValue::from_str(local_key.key.as_str())
504                    .expect("failed to parse DD-APPLICATION-KEY header"),
505            );
506        };
507
508        local_req_builder = local_req_builder.headers(headers);
509        let local_req = local_req_builder.build()?;
510        log::debug!("request content: {:?}", local_req.body());
511        let local_resp = local_client.execute(local_req).await?;
512
513        let local_status = local_resp.status();
514        let local_content = local_resp.text().await?;
515        log::debug!("response content: {}", local_content);
516
517        if !local_status.is_client_error() && !local_status.is_server_error() {
518            Ok(datadog::ResponseContent {
519                status: local_status,
520                content: local_content,
521                entity: None,
522            })
523        } else {
524            let local_entity: Option<ResolveOnCallPageError> =
525                serde_json::from_str(&local_content).ok();
526            let local_error = datadog::ResponseContent {
527                status: local_status,
528                content: local_content,
529                entity: local_entity,
530            };
531            Err(datadog::Error::ResponseError(local_error))
532        }
533    }
534}