datadog_api_client/datadogV1/api/
api_pager_duty_integration.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/// CreatePagerDutyIntegrationServiceError is a struct for typed errors of method [`PagerDutyIntegrationAPI::create_pager_duty_integration_service`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum CreatePagerDutyIntegrationServiceError {
17    APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// DeletePagerDutyIntegrationServiceError is a struct for typed errors of method [`PagerDutyIntegrationAPI::delete_pager_duty_integration_service`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum DeletePagerDutyIntegrationServiceError {
25    APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// GetPagerDutyIntegrationServiceError is a struct for typed errors of method [`PagerDutyIntegrationAPI::get_pager_duty_integration_service`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum GetPagerDutyIntegrationServiceError {
33    APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// UpdatePagerDutyIntegrationServiceError is a struct for typed errors of method [`PagerDutyIntegrationAPI::update_pager_duty_integration_service`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum UpdatePagerDutyIntegrationServiceError {
41    APIErrorResponse(crate::datadogV1::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// Configure your [Datadog-PagerDuty integration](<https://docs.datadoghq.com/integrations/pagerduty/>)
46/// directly through the Datadog API.
47#[derive(Debug, Clone)]
48pub struct PagerDutyIntegrationAPI {
49    config: datadog::Configuration,
50    client: reqwest_middleware::ClientWithMiddleware,
51}
52
53impl Default for PagerDutyIntegrationAPI {
54    fn default() -> Self {
55        Self::with_config(datadog::Configuration::default())
56    }
57}
58
59impl PagerDutyIntegrationAPI {
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    /// Create a new service object in the PagerDuty integration.
112    pub async fn create_pager_duty_integration_service(
113        &self,
114        body: crate::datadogV1::model::PagerDutyService,
115    ) -> Result<
116        crate::datadogV1::model::PagerDutyServiceName,
117        datadog::Error<CreatePagerDutyIntegrationServiceError>,
118    > {
119        match self
120            .create_pager_duty_integration_service_with_http_info(body)
121            .await
122        {
123            Ok(response_content) => {
124                if let Some(e) = response_content.entity {
125                    Ok(e)
126                } else {
127                    Err(datadog::Error::Serde(serde::de::Error::custom(
128                        "response content was None",
129                    )))
130                }
131            }
132            Err(err) => Err(err),
133        }
134    }
135
136    /// Create a new service object in the PagerDuty integration.
137    pub async fn create_pager_duty_integration_service_with_http_info(
138        &self,
139        body: crate::datadogV1::model::PagerDutyService,
140    ) -> Result<
141        datadog::ResponseContent<crate::datadogV1::model::PagerDutyServiceName>,
142        datadog::Error<CreatePagerDutyIntegrationServiceError>,
143    > {
144        let local_configuration = &self.config;
145        let operation_id = "v1.create_pager_duty_integration_service";
146
147        let local_client = &self.client;
148
149        let local_uri_str = format!(
150            "{}/api/v1/integration/pagerduty/configuration/services",
151            local_configuration.get_operation_host(operation_id)
152        );
153        let mut local_req_builder =
154            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
155
156        // build headers
157        let mut headers = HeaderMap::new();
158        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
159        headers.insert("Accept", HeaderValue::from_static("application/json"));
160
161        // build user agent
162        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
163            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
164            Err(e) => {
165                log::warn!("Failed to parse user agent header: {e}, falling back to default");
166                headers.insert(
167                    reqwest::header::USER_AGENT,
168                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
169                )
170            }
171        };
172
173        // build auth
174        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
175            headers.insert(
176                "DD-API-KEY",
177                HeaderValue::from_str(local_key.key.as_str())
178                    .expect("failed to parse DD-API-KEY header"),
179            );
180        };
181        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
182            headers.insert(
183                "DD-APPLICATION-KEY",
184                HeaderValue::from_str(local_key.key.as_str())
185                    .expect("failed to parse DD-APPLICATION-KEY header"),
186            );
187        };
188
189        // build body parameters
190        let output = Vec::new();
191        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
192        if body.serialize(&mut ser).is_ok() {
193            if let Some(content_encoding) = headers.get("Content-Encoding") {
194                match content_encoding.to_str().unwrap_or_default() {
195                    "gzip" => {
196                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
197                        let _ = enc.write_all(ser.into_inner().as_slice());
198                        match enc.finish() {
199                            Ok(buf) => {
200                                local_req_builder = local_req_builder.body(buf);
201                            }
202                            Err(e) => return Err(datadog::Error::Io(e)),
203                        }
204                    }
205                    "deflate" => {
206                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
207                        let _ = enc.write_all(ser.into_inner().as_slice());
208                        match enc.finish() {
209                            Ok(buf) => {
210                                local_req_builder = local_req_builder.body(buf);
211                            }
212                            Err(e) => return Err(datadog::Error::Io(e)),
213                        }
214                    }
215                    "zstd1" => {
216                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
217                        let _ = enc.write_all(ser.into_inner().as_slice());
218                        match enc.finish() {
219                            Ok(buf) => {
220                                local_req_builder = local_req_builder.body(buf);
221                            }
222                            Err(e) => return Err(datadog::Error::Io(e)),
223                        }
224                    }
225                    _ => {
226                        local_req_builder = local_req_builder.body(ser.into_inner());
227                    }
228                }
229            } else {
230                local_req_builder = local_req_builder.body(ser.into_inner());
231            }
232        }
233
234        local_req_builder = local_req_builder.headers(headers);
235        let local_req = local_req_builder.build()?;
236        log::debug!("request content: {:?}", local_req.body());
237        let local_resp = local_client.execute(local_req).await?;
238
239        let local_status = local_resp.status();
240        let local_content = local_resp.text().await?;
241        log::debug!("response content: {}", local_content);
242
243        if !local_status.is_client_error() && !local_status.is_server_error() {
244            match serde_json::from_str::<crate::datadogV1::model::PagerDutyServiceName>(
245                &local_content,
246            ) {
247                Ok(e) => {
248                    return Ok(datadog::ResponseContent {
249                        status: local_status,
250                        content: local_content,
251                        entity: Some(e),
252                    })
253                }
254                Err(e) => return Err(datadog::Error::Serde(e)),
255            };
256        } else {
257            let local_entity: Option<CreatePagerDutyIntegrationServiceError> =
258                serde_json::from_str(&local_content).ok();
259            let local_error = datadog::ResponseContent {
260                status: local_status,
261                content: local_content,
262                entity: local_entity,
263            };
264            Err(datadog::Error::ResponseError(local_error))
265        }
266    }
267
268    /// Delete a single service object in the Datadog-PagerDuty integration.
269    pub async fn delete_pager_duty_integration_service(
270        &self,
271        service_name: String,
272    ) -> Result<(), datadog::Error<DeletePagerDutyIntegrationServiceError>> {
273        match self
274            .delete_pager_duty_integration_service_with_http_info(service_name)
275            .await
276        {
277            Ok(_) => Ok(()),
278            Err(err) => Err(err),
279        }
280    }
281
282    /// Delete a single service object in the Datadog-PagerDuty integration.
283    pub async fn delete_pager_duty_integration_service_with_http_info(
284        &self,
285        service_name: String,
286    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeletePagerDutyIntegrationServiceError>>
287    {
288        let local_configuration = &self.config;
289        let operation_id = "v1.delete_pager_duty_integration_service";
290
291        let local_client = &self.client;
292
293        let local_uri_str = format!(
294            "{}/api/v1/integration/pagerduty/configuration/services/{service_name}",
295            local_configuration.get_operation_host(operation_id),
296            service_name = datadog::urlencode(service_name)
297        );
298        let mut local_req_builder =
299            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
300
301        // build headers
302        let mut headers = HeaderMap::new();
303        headers.insert("Accept", HeaderValue::from_static("*/*"));
304
305        // build user agent
306        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
307            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
308            Err(e) => {
309                log::warn!("Failed to parse user agent header: {e}, falling back to default");
310                headers.insert(
311                    reqwest::header::USER_AGENT,
312                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
313                )
314            }
315        };
316
317        // build auth
318        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
319            headers.insert(
320                "DD-API-KEY",
321                HeaderValue::from_str(local_key.key.as_str())
322                    .expect("failed to parse DD-API-KEY header"),
323            );
324        };
325        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
326            headers.insert(
327                "DD-APPLICATION-KEY",
328                HeaderValue::from_str(local_key.key.as_str())
329                    .expect("failed to parse DD-APPLICATION-KEY header"),
330            );
331        };
332
333        local_req_builder = local_req_builder.headers(headers);
334        let local_req = local_req_builder.build()?;
335        log::debug!("request content: {:?}", local_req.body());
336        let local_resp = local_client.execute(local_req).await?;
337
338        let local_status = local_resp.status();
339        let local_content = local_resp.text().await?;
340        log::debug!("response content: {}", local_content);
341
342        if !local_status.is_client_error() && !local_status.is_server_error() {
343            Ok(datadog::ResponseContent {
344                status: local_status,
345                content: local_content,
346                entity: None,
347            })
348        } else {
349            let local_entity: Option<DeletePagerDutyIntegrationServiceError> =
350                serde_json::from_str(&local_content).ok();
351            let local_error = datadog::ResponseContent {
352                status: local_status,
353                content: local_content,
354                entity: local_entity,
355            };
356            Err(datadog::Error::ResponseError(local_error))
357        }
358    }
359
360    /// Get service name in the Datadog-PagerDuty integration.
361    pub async fn get_pager_duty_integration_service(
362        &self,
363        service_name: String,
364    ) -> Result<
365        crate::datadogV1::model::PagerDutyServiceName,
366        datadog::Error<GetPagerDutyIntegrationServiceError>,
367    > {
368        match self
369            .get_pager_duty_integration_service_with_http_info(service_name)
370            .await
371        {
372            Ok(response_content) => {
373                if let Some(e) = response_content.entity {
374                    Ok(e)
375                } else {
376                    Err(datadog::Error::Serde(serde::de::Error::custom(
377                        "response content was None",
378                    )))
379                }
380            }
381            Err(err) => Err(err),
382        }
383    }
384
385    /// Get service name in the Datadog-PagerDuty integration.
386    pub async fn get_pager_duty_integration_service_with_http_info(
387        &self,
388        service_name: String,
389    ) -> Result<
390        datadog::ResponseContent<crate::datadogV1::model::PagerDutyServiceName>,
391        datadog::Error<GetPagerDutyIntegrationServiceError>,
392    > {
393        let local_configuration = &self.config;
394        let operation_id = "v1.get_pager_duty_integration_service";
395
396        let local_client = &self.client;
397
398        let local_uri_str = format!(
399            "{}/api/v1/integration/pagerduty/configuration/services/{service_name}",
400            local_configuration.get_operation_host(operation_id),
401            service_name = datadog::urlencode(service_name)
402        );
403        let mut local_req_builder =
404            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
405
406        // build headers
407        let mut headers = HeaderMap::new();
408        headers.insert("Accept", HeaderValue::from_static("application/json"));
409
410        // build user agent
411        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
412            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
413            Err(e) => {
414                log::warn!("Failed to parse user agent header: {e}, falling back to default");
415                headers.insert(
416                    reqwest::header::USER_AGENT,
417                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
418                )
419            }
420        };
421
422        // build auth
423        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
424            headers.insert(
425                "DD-API-KEY",
426                HeaderValue::from_str(local_key.key.as_str())
427                    .expect("failed to parse DD-API-KEY header"),
428            );
429        };
430        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
431            headers.insert(
432                "DD-APPLICATION-KEY",
433                HeaderValue::from_str(local_key.key.as_str())
434                    .expect("failed to parse DD-APPLICATION-KEY header"),
435            );
436        };
437
438        local_req_builder = local_req_builder.headers(headers);
439        let local_req = local_req_builder.build()?;
440        log::debug!("request content: {:?}", local_req.body());
441        let local_resp = local_client.execute(local_req).await?;
442
443        let local_status = local_resp.status();
444        let local_content = local_resp.text().await?;
445        log::debug!("response content: {}", local_content);
446
447        if !local_status.is_client_error() && !local_status.is_server_error() {
448            match serde_json::from_str::<crate::datadogV1::model::PagerDutyServiceName>(
449                &local_content,
450            ) {
451                Ok(e) => {
452                    return Ok(datadog::ResponseContent {
453                        status: local_status,
454                        content: local_content,
455                        entity: Some(e),
456                    })
457                }
458                Err(e) => return Err(datadog::Error::Serde(e)),
459            };
460        } else {
461            let local_entity: Option<GetPagerDutyIntegrationServiceError> =
462                serde_json::from_str(&local_content).ok();
463            let local_error = datadog::ResponseContent {
464                status: local_status,
465                content: local_content,
466                entity: local_entity,
467            };
468            Err(datadog::Error::ResponseError(local_error))
469        }
470    }
471
472    /// Update a single service object in the Datadog-PagerDuty integration.
473    pub async fn update_pager_duty_integration_service(
474        &self,
475        service_name: String,
476        body: crate::datadogV1::model::PagerDutyServiceKey,
477    ) -> Result<(), datadog::Error<UpdatePagerDutyIntegrationServiceError>> {
478        match self
479            .update_pager_duty_integration_service_with_http_info(service_name, body)
480            .await
481        {
482            Ok(_) => Ok(()),
483            Err(err) => Err(err),
484        }
485    }
486
487    /// Update a single service object in the Datadog-PagerDuty integration.
488    pub async fn update_pager_duty_integration_service_with_http_info(
489        &self,
490        service_name: String,
491        body: crate::datadogV1::model::PagerDutyServiceKey,
492    ) -> Result<datadog::ResponseContent<()>, datadog::Error<UpdatePagerDutyIntegrationServiceError>>
493    {
494        let local_configuration = &self.config;
495        let operation_id = "v1.update_pager_duty_integration_service";
496
497        let local_client = &self.client;
498
499        let local_uri_str = format!(
500            "{}/api/v1/integration/pagerduty/configuration/services/{service_name}",
501            local_configuration.get_operation_host(operation_id),
502            service_name = datadog::urlencode(service_name)
503        );
504        let mut local_req_builder =
505            local_client.request(reqwest::Method::PUT, local_uri_str.as_str());
506
507        // build headers
508        let mut headers = HeaderMap::new();
509        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
510        headers.insert("Accept", HeaderValue::from_static("*/*"));
511
512        // build user agent
513        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
514            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
515            Err(e) => {
516                log::warn!("Failed to parse user agent header: {e}, falling back to default");
517                headers.insert(
518                    reqwest::header::USER_AGENT,
519                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
520                )
521            }
522        };
523
524        // build auth
525        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
526            headers.insert(
527                "DD-API-KEY",
528                HeaderValue::from_str(local_key.key.as_str())
529                    .expect("failed to parse DD-API-KEY header"),
530            );
531        };
532        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
533            headers.insert(
534                "DD-APPLICATION-KEY",
535                HeaderValue::from_str(local_key.key.as_str())
536                    .expect("failed to parse DD-APPLICATION-KEY header"),
537            );
538        };
539
540        // build body parameters
541        let output = Vec::new();
542        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
543        if body.serialize(&mut ser).is_ok() {
544            if let Some(content_encoding) = headers.get("Content-Encoding") {
545                match content_encoding.to_str().unwrap_or_default() {
546                    "gzip" => {
547                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
548                        let _ = enc.write_all(ser.into_inner().as_slice());
549                        match enc.finish() {
550                            Ok(buf) => {
551                                local_req_builder = local_req_builder.body(buf);
552                            }
553                            Err(e) => return Err(datadog::Error::Io(e)),
554                        }
555                    }
556                    "deflate" => {
557                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
558                        let _ = enc.write_all(ser.into_inner().as_slice());
559                        match enc.finish() {
560                            Ok(buf) => {
561                                local_req_builder = local_req_builder.body(buf);
562                            }
563                            Err(e) => return Err(datadog::Error::Io(e)),
564                        }
565                    }
566                    "zstd1" => {
567                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
568                        let _ = enc.write_all(ser.into_inner().as_slice());
569                        match enc.finish() {
570                            Ok(buf) => {
571                                local_req_builder = local_req_builder.body(buf);
572                            }
573                            Err(e) => return Err(datadog::Error::Io(e)),
574                        }
575                    }
576                    _ => {
577                        local_req_builder = local_req_builder.body(ser.into_inner());
578                    }
579                }
580            } else {
581                local_req_builder = local_req_builder.body(ser.into_inner());
582            }
583        }
584
585        local_req_builder = local_req_builder.headers(headers);
586        let local_req = local_req_builder.build()?;
587        log::debug!("request content: {:?}", local_req.body());
588        let local_resp = local_client.execute(local_req).await?;
589
590        let local_status = local_resp.status();
591        let local_content = local_resp.text().await?;
592        log::debug!("response content: {}", local_content);
593
594        if !local_status.is_client_error() && !local_status.is_server_error() {
595            Ok(datadog::ResponseContent {
596                status: local_status,
597                content: local_content,
598                entity: None,
599            })
600        } else {
601            let local_entity: Option<UpdatePagerDutyIntegrationServiceError> =
602                serde_json::from_str(&local_content).ok();
603            let local_error = datadog::ResponseContent {
604                status: local_status,
605                content: local_content,
606                entity: local_entity,
607            };
608            Err(datadog::Error::ResponseError(local_error))
609        }
610    }
611}