datadog_api_client/datadogV2/api/
api_domain_allowlist.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/// GetDomainAllowlistError is a struct for typed errors of method [`DomainAllowlistAPI::get_domain_allowlist`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum GetDomainAllowlistError {
17    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// PatchDomainAllowlistError is a struct for typed errors of method [`DomainAllowlistAPI::patch_domain_allowlist`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum PatchDomainAllowlistError {
25    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// Configure your Datadog Email Domain Allowlist directly through the Datadog API.
30/// The Email Domain Allowlist controls the domains that certain datadog emails can be sent to.
31/// For more information, see the [Domain Allowlist docs page](<https://docs.datadoghq.com/account_management/org_settings/domain_allowlist>)
32#[derive(Debug, Clone)]
33pub struct DomainAllowlistAPI {
34    config: datadog::Configuration,
35    client: reqwest_middleware::ClientWithMiddleware,
36}
37
38impl Default for DomainAllowlistAPI {
39    fn default() -> Self {
40        Self::with_config(datadog::Configuration::default())
41    }
42}
43
44impl DomainAllowlistAPI {
45    pub fn new() -> Self {
46        Self::default()
47    }
48    pub fn with_config(config: datadog::Configuration) -> Self {
49        let mut reqwest_client_builder = reqwest::Client::builder();
50
51        if let Some(proxy_url) = &config.proxy_url {
52            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
53            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
54        }
55
56        let mut middleware_client_builder =
57            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
58
59        if config.enable_retry {
60            struct RetryableStatus;
61            impl reqwest_retry::RetryableStrategy for RetryableStatus {
62                fn handle(
63                    &self,
64                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
65                ) -> Option<reqwest_retry::Retryable> {
66                    match res {
67                        Ok(success) => reqwest_retry::default_on_request_success(success),
68                        Err(_) => None,
69                    }
70                }
71            }
72            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
73                .build_with_max_retries(config.max_retries);
74
75            let retry_middleware =
76                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
77                    backoff_policy,
78                    RetryableStatus,
79                );
80
81            middleware_client_builder = middleware_client_builder.with(retry_middleware);
82        }
83
84        let client = middleware_client_builder.build();
85
86        Self { config, client }
87    }
88
89    pub fn with_client_and_config(
90        config: datadog::Configuration,
91        client: reqwest_middleware::ClientWithMiddleware,
92    ) -> Self {
93        Self { config, client }
94    }
95
96    /// Get the domain allowlist for an organization.
97    pub async fn get_domain_allowlist(
98        &self,
99    ) -> Result<
100        crate::datadogV2::model::DomainAllowlistResponse,
101        datadog::Error<GetDomainAllowlistError>,
102    > {
103        match self.get_domain_allowlist_with_http_info().await {
104            Ok(response_content) => {
105                if let Some(e) = response_content.entity {
106                    Ok(e)
107                } else {
108                    Err(datadog::Error::Serde(serde::de::Error::custom(
109                        "response content was None",
110                    )))
111                }
112            }
113            Err(err) => Err(err),
114        }
115    }
116
117    /// Get the domain allowlist for an organization.
118    pub async fn get_domain_allowlist_with_http_info(
119        &self,
120    ) -> Result<
121        datadog::ResponseContent<crate::datadogV2::model::DomainAllowlistResponse>,
122        datadog::Error<GetDomainAllowlistError>,
123    > {
124        let local_configuration = &self.config;
125        let operation_id = "v2.get_domain_allowlist";
126
127        let local_client = &self.client;
128
129        let local_uri_str = format!(
130            "{}/api/v2/domain_allowlist",
131            local_configuration.get_operation_host(operation_id)
132        );
133        let mut local_req_builder =
134            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
135
136        // build headers
137        let mut headers = HeaderMap::new();
138        headers.insert("Accept", HeaderValue::from_static("application/json"));
139
140        // build user agent
141        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
142            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
143            Err(e) => {
144                log::warn!("Failed to parse user agent header: {e}, falling back to default");
145                headers.insert(
146                    reqwest::header::USER_AGENT,
147                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
148                )
149            }
150        };
151
152        // build auth
153        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
154            headers.insert(
155                "DD-API-KEY",
156                HeaderValue::from_str(local_key.key.as_str())
157                    .expect("failed to parse DD-API-KEY header"),
158            );
159        };
160        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
161            headers.insert(
162                "DD-APPLICATION-KEY",
163                HeaderValue::from_str(local_key.key.as_str())
164                    .expect("failed to parse DD-APPLICATION-KEY header"),
165            );
166        };
167
168        local_req_builder = local_req_builder.headers(headers);
169        let local_req = local_req_builder.build()?;
170        log::debug!("request content: {:?}", local_req.body());
171        let local_resp = local_client.execute(local_req).await?;
172
173        let local_status = local_resp.status();
174        let local_content = local_resp.text().await?;
175        log::debug!("response content: {}", local_content);
176
177        if !local_status.is_client_error() && !local_status.is_server_error() {
178            match serde_json::from_str::<crate::datadogV2::model::DomainAllowlistResponse>(
179                &local_content,
180            ) {
181                Ok(e) => {
182                    return Ok(datadog::ResponseContent {
183                        status: local_status,
184                        content: local_content,
185                        entity: Some(e),
186                    })
187                }
188                Err(e) => return Err(datadog::Error::Serde(e)),
189            };
190        } else {
191            let local_entity: Option<GetDomainAllowlistError> =
192                serde_json::from_str(&local_content).ok();
193            let local_error = datadog::ResponseContent {
194                status: local_status,
195                content: local_content,
196                entity: local_entity,
197            };
198            Err(datadog::Error::ResponseError(local_error))
199        }
200    }
201
202    /// Update the domain allowlist for an organization.
203    pub async fn patch_domain_allowlist(
204        &self,
205        body: crate::datadogV2::model::DomainAllowlistRequest,
206    ) -> Result<
207        crate::datadogV2::model::DomainAllowlistResponse,
208        datadog::Error<PatchDomainAllowlistError>,
209    > {
210        match self.patch_domain_allowlist_with_http_info(body).await {
211            Ok(response_content) => {
212                if let Some(e) = response_content.entity {
213                    Ok(e)
214                } else {
215                    Err(datadog::Error::Serde(serde::de::Error::custom(
216                        "response content was None",
217                    )))
218                }
219            }
220            Err(err) => Err(err),
221        }
222    }
223
224    /// Update the domain allowlist for an organization.
225    pub async fn patch_domain_allowlist_with_http_info(
226        &self,
227        body: crate::datadogV2::model::DomainAllowlistRequest,
228    ) -> Result<
229        datadog::ResponseContent<crate::datadogV2::model::DomainAllowlistResponse>,
230        datadog::Error<PatchDomainAllowlistError>,
231    > {
232        let local_configuration = &self.config;
233        let operation_id = "v2.patch_domain_allowlist";
234
235        let local_client = &self.client;
236
237        let local_uri_str = format!(
238            "{}/api/v2/domain_allowlist",
239            local_configuration.get_operation_host(operation_id)
240        );
241        let mut local_req_builder =
242            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
243
244        // build headers
245        let mut headers = HeaderMap::new();
246        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
247        headers.insert("Accept", HeaderValue::from_static("application/json"));
248
249        // build user agent
250        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
251            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
252            Err(e) => {
253                log::warn!("Failed to parse user agent header: {e}, falling back to default");
254                headers.insert(
255                    reqwest::header::USER_AGENT,
256                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
257                )
258            }
259        };
260
261        // build auth
262        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
263            headers.insert(
264                "DD-API-KEY",
265                HeaderValue::from_str(local_key.key.as_str())
266                    .expect("failed to parse DD-API-KEY header"),
267            );
268        };
269        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
270            headers.insert(
271                "DD-APPLICATION-KEY",
272                HeaderValue::from_str(local_key.key.as_str())
273                    .expect("failed to parse DD-APPLICATION-KEY header"),
274            );
275        };
276
277        // build body parameters
278        let output = Vec::new();
279        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
280        if body.serialize(&mut ser).is_ok() {
281            if let Some(content_encoding) = headers.get("Content-Encoding") {
282                match content_encoding.to_str().unwrap_or_default() {
283                    "gzip" => {
284                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
285                        let _ = enc.write_all(ser.into_inner().as_slice());
286                        match enc.finish() {
287                            Ok(buf) => {
288                                local_req_builder = local_req_builder.body(buf);
289                            }
290                            Err(e) => return Err(datadog::Error::Io(e)),
291                        }
292                    }
293                    "deflate" => {
294                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
295                        let _ = enc.write_all(ser.into_inner().as_slice());
296                        match enc.finish() {
297                            Ok(buf) => {
298                                local_req_builder = local_req_builder.body(buf);
299                            }
300                            Err(e) => return Err(datadog::Error::Io(e)),
301                        }
302                    }
303                    "zstd1" => {
304                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
305                        let _ = enc.write_all(ser.into_inner().as_slice());
306                        match enc.finish() {
307                            Ok(buf) => {
308                                local_req_builder = local_req_builder.body(buf);
309                            }
310                            Err(e) => return Err(datadog::Error::Io(e)),
311                        }
312                    }
313                    _ => {
314                        local_req_builder = local_req_builder.body(ser.into_inner());
315                    }
316                }
317            } else {
318                local_req_builder = local_req_builder.body(ser.into_inner());
319            }
320        }
321
322        local_req_builder = local_req_builder.headers(headers);
323        let local_req = local_req_builder.build()?;
324        log::debug!("request content: {:?}", local_req.body());
325        let local_resp = local_client.execute(local_req).await?;
326
327        let local_status = local_resp.status();
328        let local_content = local_resp.text().await?;
329        log::debug!("response content: {}", local_content);
330
331        if !local_status.is_client_error() && !local_status.is_server_error() {
332            match serde_json::from_str::<crate::datadogV2::model::DomainAllowlistResponse>(
333                &local_content,
334            ) {
335                Ok(e) => {
336                    return Ok(datadog::ResponseContent {
337                        status: local_status,
338                        content: local_content,
339                        entity: Some(e),
340                    })
341                }
342                Err(e) => return Err(datadog::Error::Serde(e)),
343            };
344        } else {
345            let local_entity: Option<PatchDomainAllowlistError> =
346                serde_json::from_str(&local_content).ok();
347            let local_error = datadog::ResponseContent {
348                status: local_status,
349                content: local_content,
350                entity: local_entity,
351            };
352            Err(datadog::Error::ResponseError(local_error))
353        }
354    }
355}