datadog_api_client/datadogV2/api/
api_data_deletion.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 log::warn;
10use reqwest::header::{HeaderMap, HeaderValue};
11use serde::{Deserialize, Serialize};
12use std::io::Write;
13
14/// GetDataDeletionRequestsOptionalParams is a struct for passing parameters to the method [`DataDeletionAPI::get_data_deletion_requests`]
15#[non_exhaustive]
16#[derive(Clone, Default, Debug)]
17pub struct GetDataDeletionRequestsOptionalParams {
18    /// The next page of the previous search. If the next_page parameter is included, the rest of the query elements are ignored.
19    pub next_page: Option<String>,
20    /// Retrieve only the requests related to the given product.
21    pub product: Option<String>,
22    /// Retrieve only the requests that matches the given query.
23    pub query: Option<String>,
24    /// Retrieve only the requests with the given status.
25    pub status: Option<String>,
26    /// Sets the page size of the search.
27    pub page_size: Option<i64>,
28}
29
30impl GetDataDeletionRequestsOptionalParams {
31    /// The next page of the previous search. If the next_page parameter is included, the rest of the query elements are ignored.
32    pub fn next_page(mut self, value: String) -> Self {
33        self.next_page = Some(value);
34        self
35    }
36    /// Retrieve only the requests related to the given product.
37    pub fn product(mut self, value: String) -> Self {
38        self.product = Some(value);
39        self
40    }
41    /// Retrieve only the requests that matches the given query.
42    pub fn query(mut self, value: String) -> Self {
43        self.query = Some(value);
44        self
45    }
46    /// Retrieve only the requests with the given status.
47    pub fn status(mut self, value: String) -> Self {
48        self.status = Some(value);
49        self
50    }
51    /// Sets the page size of the search.
52    pub fn page_size(mut self, value: i64) -> Self {
53        self.page_size = Some(value);
54        self
55    }
56}
57
58/// CancelDataDeletionRequestError is a struct for typed errors of method [`DataDeletionAPI::cancel_data_deletion_request`]
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[serde(untagged)]
61pub enum CancelDataDeletionRequestError {
62    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
63    UnknownValue(serde_json::Value),
64}
65
66/// CreateDataDeletionRequestError is a struct for typed errors of method [`DataDeletionAPI::create_data_deletion_request`]
67#[derive(Debug, Clone, Serialize, Deserialize)]
68#[serde(untagged)]
69pub enum CreateDataDeletionRequestError {
70    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
71    UnknownValue(serde_json::Value),
72}
73
74/// GetDataDeletionRequestsError is a struct for typed errors of method [`DataDeletionAPI::get_data_deletion_requests`]
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[serde(untagged)]
77pub enum GetDataDeletionRequestsError {
78    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
79    UnknownValue(serde_json::Value),
80}
81
82/// The Data Deletion API allows the user to target and delete data from the allowed products. It's currently enabled for Logs and RUM and depends on `logs_delete_data` and `rum_delete_data` permissions respectively.
83#[derive(Debug, Clone)]
84pub struct DataDeletionAPI {
85    config: datadog::Configuration,
86    client: reqwest_middleware::ClientWithMiddleware,
87}
88
89impl Default for DataDeletionAPI {
90    fn default() -> Self {
91        Self::with_config(datadog::Configuration::default())
92    }
93}
94
95impl DataDeletionAPI {
96    pub fn new() -> Self {
97        Self::default()
98    }
99    pub fn with_config(config: datadog::Configuration) -> Self {
100        let mut reqwest_client_builder = reqwest::Client::builder();
101
102        if let Some(proxy_url) = &config.proxy_url {
103            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
104            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
105        }
106
107        let mut middleware_client_builder =
108            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
109
110        if config.enable_retry {
111            struct RetryableStatus;
112            impl reqwest_retry::RetryableStrategy for RetryableStatus {
113                fn handle(
114                    &self,
115                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
116                ) -> Option<reqwest_retry::Retryable> {
117                    match res {
118                        Ok(success) => reqwest_retry::default_on_request_success(success),
119                        Err(_) => None,
120                    }
121                }
122            }
123            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
124                .build_with_max_retries(config.max_retries);
125
126            let retry_middleware =
127                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
128                    backoff_policy,
129                    RetryableStatus,
130                );
131
132            middleware_client_builder = middleware_client_builder.with(retry_middleware);
133        }
134
135        let client = middleware_client_builder.build();
136
137        Self { config, client }
138    }
139
140    pub fn with_client_and_config(
141        config: datadog::Configuration,
142        client: reqwest_middleware::ClientWithMiddleware,
143    ) -> Self {
144        Self { config, client }
145    }
146
147    /// Cancels a data deletion request by providing its ID.
148    pub async fn cancel_data_deletion_request(
149        &self,
150        id: String,
151    ) -> Result<
152        crate::datadogV2::model::CancelDataDeletionResponseBody,
153        datadog::Error<CancelDataDeletionRequestError>,
154    > {
155        match self.cancel_data_deletion_request_with_http_info(id).await {
156            Ok(response_content) => {
157                if let Some(e) = response_content.entity {
158                    Ok(e)
159                } else {
160                    Err(datadog::Error::Serde(serde::de::Error::custom(
161                        "response content was None",
162                    )))
163                }
164            }
165            Err(err) => Err(err),
166        }
167    }
168
169    /// Cancels a data deletion request by providing its ID.
170    pub async fn cancel_data_deletion_request_with_http_info(
171        &self,
172        id: String,
173    ) -> Result<
174        datadog::ResponseContent<crate::datadogV2::model::CancelDataDeletionResponseBody>,
175        datadog::Error<CancelDataDeletionRequestError>,
176    > {
177        let local_configuration = &self.config;
178        let operation_id = "v2.cancel_data_deletion_request";
179        if local_configuration.is_unstable_operation_enabled(operation_id) {
180            warn!("Using unstable operation {operation_id}");
181        } else {
182            let local_error = datadog::UnstableOperationDisabledError {
183                msg: "Operation 'v2.cancel_data_deletion_request' is not enabled".to_string(),
184            };
185            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
186        }
187
188        let local_client = &self.client;
189
190        let local_uri_str = format!(
191            "{}/api/v2/deletion/requests/{id}/cancel",
192            local_configuration.get_operation_host(operation_id),
193            id = datadog::urlencode(id)
194        );
195        let mut local_req_builder =
196            local_client.request(reqwest::Method::PUT, local_uri_str.as_str());
197
198        // build headers
199        let mut headers = HeaderMap::new();
200        headers.insert("Accept", HeaderValue::from_static("application/json"));
201
202        // build user agent
203        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
204            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
205            Err(e) => {
206                log::warn!("Failed to parse user agent header: {e}, falling back to default");
207                headers.insert(
208                    reqwest::header::USER_AGENT,
209                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
210                )
211            }
212        };
213
214        // build auth
215        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
216            headers.insert(
217                "DD-API-KEY",
218                HeaderValue::from_str(local_key.key.as_str())
219                    .expect("failed to parse DD-API-KEY header"),
220            );
221        };
222        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
223            headers.insert(
224                "DD-APPLICATION-KEY",
225                HeaderValue::from_str(local_key.key.as_str())
226                    .expect("failed to parse DD-APPLICATION-KEY header"),
227            );
228        };
229
230        local_req_builder = local_req_builder.headers(headers);
231        let local_req = local_req_builder.build()?;
232        log::debug!("request content: {:?}", local_req.body());
233        let local_resp = local_client.execute(local_req).await?;
234
235        let local_status = local_resp.status();
236        let local_content = local_resp.text().await?;
237        log::debug!("response content: {}", local_content);
238
239        if !local_status.is_client_error() && !local_status.is_server_error() {
240            match serde_json::from_str::<crate::datadogV2::model::CancelDataDeletionResponseBody>(
241                &local_content,
242            ) {
243                Ok(e) => {
244                    return Ok(datadog::ResponseContent {
245                        status: local_status,
246                        content: local_content,
247                        entity: Some(e),
248                    })
249                }
250                Err(e) => return Err(datadog::Error::Serde(e)),
251            };
252        } else {
253            let local_entity: Option<CancelDataDeletionRequestError> =
254                serde_json::from_str(&local_content).ok();
255            let local_error = datadog::ResponseContent {
256                status: local_status,
257                content: local_content,
258                entity: local_entity,
259            };
260            Err(datadog::Error::ResponseError(local_error))
261        }
262    }
263
264    /// Creates a data deletion request by providing a query and a timeframe targeting the proper data.
265    pub async fn create_data_deletion_request(
266        &self,
267        product: String,
268        body: crate::datadogV2::model::CreateDataDeletionRequestBody,
269    ) -> Result<
270        crate::datadogV2::model::CreateDataDeletionResponseBody,
271        datadog::Error<CreateDataDeletionRequestError>,
272    > {
273        match self
274            .create_data_deletion_request_with_http_info(product, body)
275            .await
276        {
277            Ok(response_content) => {
278                if let Some(e) = response_content.entity {
279                    Ok(e)
280                } else {
281                    Err(datadog::Error::Serde(serde::de::Error::custom(
282                        "response content was None",
283                    )))
284                }
285            }
286            Err(err) => Err(err),
287        }
288    }
289
290    /// Creates a data deletion request by providing a query and a timeframe targeting the proper data.
291    pub async fn create_data_deletion_request_with_http_info(
292        &self,
293        product: String,
294        body: crate::datadogV2::model::CreateDataDeletionRequestBody,
295    ) -> Result<
296        datadog::ResponseContent<crate::datadogV2::model::CreateDataDeletionResponseBody>,
297        datadog::Error<CreateDataDeletionRequestError>,
298    > {
299        let local_configuration = &self.config;
300        let operation_id = "v2.create_data_deletion_request";
301        if local_configuration.is_unstable_operation_enabled(operation_id) {
302            warn!("Using unstable operation {operation_id}");
303        } else {
304            let local_error = datadog::UnstableOperationDisabledError {
305                msg: "Operation 'v2.create_data_deletion_request' is not enabled".to_string(),
306            };
307            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
308        }
309
310        let local_client = &self.client;
311
312        let local_uri_str = format!(
313            "{}/api/v2/deletion/data/{product}",
314            local_configuration.get_operation_host(operation_id),
315            product = datadog::urlencode(product)
316        );
317        let mut local_req_builder =
318            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
319
320        // build headers
321        let mut headers = HeaderMap::new();
322        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
323        headers.insert("Accept", HeaderValue::from_static("application/json"));
324
325        // build user agent
326        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
327            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
328            Err(e) => {
329                log::warn!("Failed to parse user agent header: {e}, falling back to default");
330                headers.insert(
331                    reqwest::header::USER_AGENT,
332                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
333                )
334            }
335        };
336
337        // build auth
338        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
339            headers.insert(
340                "DD-API-KEY",
341                HeaderValue::from_str(local_key.key.as_str())
342                    .expect("failed to parse DD-API-KEY header"),
343            );
344        };
345        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
346            headers.insert(
347                "DD-APPLICATION-KEY",
348                HeaderValue::from_str(local_key.key.as_str())
349                    .expect("failed to parse DD-APPLICATION-KEY header"),
350            );
351        };
352
353        // build body parameters
354        let output = Vec::new();
355        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
356        if body.serialize(&mut ser).is_ok() {
357            if let Some(content_encoding) = headers.get("Content-Encoding") {
358                match content_encoding.to_str().unwrap_or_default() {
359                    "gzip" => {
360                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
361                        let _ = enc.write_all(ser.into_inner().as_slice());
362                        match enc.finish() {
363                            Ok(buf) => {
364                                local_req_builder = local_req_builder.body(buf);
365                            }
366                            Err(e) => return Err(datadog::Error::Io(e)),
367                        }
368                    }
369                    "deflate" => {
370                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
371                        let _ = enc.write_all(ser.into_inner().as_slice());
372                        match enc.finish() {
373                            Ok(buf) => {
374                                local_req_builder = local_req_builder.body(buf);
375                            }
376                            Err(e) => return Err(datadog::Error::Io(e)),
377                        }
378                    }
379                    "zstd1" => {
380                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
381                        let _ = enc.write_all(ser.into_inner().as_slice());
382                        match enc.finish() {
383                            Ok(buf) => {
384                                local_req_builder = local_req_builder.body(buf);
385                            }
386                            Err(e) => return Err(datadog::Error::Io(e)),
387                        }
388                    }
389                    _ => {
390                        local_req_builder = local_req_builder.body(ser.into_inner());
391                    }
392                }
393            } else {
394                local_req_builder = local_req_builder.body(ser.into_inner());
395            }
396        }
397
398        local_req_builder = local_req_builder.headers(headers);
399        let local_req = local_req_builder.build()?;
400        log::debug!("request content: {:?}", local_req.body());
401        let local_resp = local_client.execute(local_req).await?;
402
403        let local_status = local_resp.status();
404        let local_content = local_resp.text().await?;
405        log::debug!("response content: {}", local_content);
406
407        if !local_status.is_client_error() && !local_status.is_server_error() {
408            match serde_json::from_str::<crate::datadogV2::model::CreateDataDeletionResponseBody>(
409                &local_content,
410            ) {
411                Ok(e) => {
412                    return Ok(datadog::ResponseContent {
413                        status: local_status,
414                        content: local_content,
415                        entity: Some(e),
416                    })
417                }
418                Err(e) => return Err(datadog::Error::Serde(e)),
419            };
420        } else {
421            let local_entity: Option<CreateDataDeletionRequestError> =
422                serde_json::from_str(&local_content).ok();
423            let local_error = datadog::ResponseContent {
424                status: local_status,
425                content: local_content,
426                entity: local_entity,
427            };
428            Err(datadog::Error::ResponseError(local_error))
429        }
430    }
431
432    /// Gets a list of data deletion requests based on several filter parameters.
433    pub async fn get_data_deletion_requests(
434        &self,
435        params: GetDataDeletionRequestsOptionalParams,
436    ) -> Result<
437        crate::datadogV2::model::GetDataDeletionsResponseBody,
438        datadog::Error<GetDataDeletionRequestsError>,
439    > {
440        match self.get_data_deletion_requests_with_http_info(params).await {
441            Ok(response_content) => {
442                if let Some(e) = response_content.entity {
443                    Ok(e)
444                } else {
445                    Err(datadog::Error::Serde(serde::de::Error::custom(
446                        "response content was None",
447                    )))
448                }
449            }
450            Err(err) => Err(err),
451        }
452    }
453
454    /// Gets a list of data deletion requests based on several filter parameters.
455    pub async fn get_data_deletion_requests_with_http_info(
456        &self,
457        params: GetDataDeletionRequestsOptionalParams,
458    ) -> Result<
459        datadog::ResponseContent<crate::datadogV2::model::GetDataDeletionsResponseBody>,
460        datadog::Error<GetDataDeletionRequestsError>,
461    > {
462        let local_configuration = &self.config;
463        let operation_id = "v2.get_data_deletion_requests";
464        if local_configuration.is_unstable_operation_enabled(operation_id) {
465            warn!("Using unstable operation {operation_id}");
466        } else {
467            let local_error = datadog::UnstableOperationDisabledError {
468                msg: "Operation 'v2.get_data_deletion_requests' is not enabled".to_string(),
469            };
470            return Err(datadog::Error::UnstableOperationDisabledError(local_error));
471        }
472
473        // unbox and build optional parameters
474        let next_page = params.next_page;
475        let product = params.product;
476        let query = params.query;
477        let status = params.status;
478        let page_size = params.page_size;
479
480        let local_client = &self.client;
481
482        let local_uri_str = format!(
483            "{}/api/v2/deletion/requests",
484            local_configuration.get_operation_host(operation_id)
485        );
486        let mut local_req_builder =
487            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
488
489        if let Some(ref local_query_param) = next_page {
490            local_req_builder =
491                local_req_builder.query(&[("next_page", &local_query_param.to_string())]);
492        };
493        if let Some(ref local_query_param) = product {
494            local_req_builder =
495                local_req_builder.query(&[("product", &local_query_param.to_string())]);
496        };
497        if let Some(ref local_query_param) = query {
498            local_req_builder =
499                local_req_builder.query(&[("query", &local_query_param.to_string())]);
500        };
501        if let Some(ref local_query_param) = status {
502            local_req_builder =
503                local_req_builder.query(&[("status", &local_query_param.to_string())]);
504        };
505        if let Some(ref local_query_param) = page_size {
506            local_req_builder =
507                local_req_builder.query(&[("page_size", &local_query_param.to_string())]);
508        };
509
510        // build headers
511        let mut headers = HeaderMap::new();
512        headers.insert("Accept", HeaderValue::from_static("application/json"));
513
514        // build user agent
515        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
516            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
517            Err(e) => {
518                log::warn!("Failed to parse user agent header: {e}, falling back to default");
519                headers.insert(
520                    reqwest::header::USER_AGENT,
521                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
522                )
523            }
524        };
525
526        // build auth
527        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
528            headers.insert(
529                "DD-API-KEY",
530                HeaderValue::from_str(local_key.key.as_str())
531                    .expect("failed to parse DD-API-KEY header"),
532            );
533        };
534        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
535            headers.insert(
536                "DD-APPLICATION-KEY",
537                HeaderValue::from_str(local_key.key.as_str())
538                    .expect("failed to parse DD-APPLICATION-KEY header"),
539            );
540        };
541
542        local_req_builder = local_req_builder.headers(headers);
543        let local_req = local_req_builder.build()?;
544        log::debug!("request content: {:?}", local_req.body());
545        let local_resp = local_client.execute(local_req).await?;
546
547        let local_status = local_resp.status();
548        let local_content = local_resp.text().await?;
549        log::debug!("response content: {}", local_content);
550
551        if !local_status.is_client_error() && !local_status.is_server_error() {
552            match serde_json::from_str::<crate::datadogV2::model::GetDataDeletionsResponseBody>(
553                &local_content,
554            ) {
555                Ok(e) => {
556                    return Ok(datadog::ResponseContent {
557                        status: local_status,
558                        content: local_content,
559                        entity: Some(e),
560                    })
561                }
562                Err(e) => return Err(datadog::Error::Serde(e)),
563            };
564        } else {
565            let local_entity: Option<GetDataDeletionRequestsError> =
566                serde_json::from_str(&local_content).ok();
567            let local_error = datadog::ResponseContent {
568                status: local_status,
569                content: local_content,
570                entity: local_entity,
571            };
572            Err(datadog::Error::ResponseError(local_error))
573        }
574    }
575}