datadog_api_client/datadogV2/api/
api_datasets.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/// CreateDatasetError is a struct for typed errors of method [`DatasetsAPI::create_dataset`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum CreateDatasetError {
17    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// DeleteDatasetError is a struct for typed errors of method [`DatasetsAPI::delete_dataset`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum DeleteDatasetError {
25    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// GetAllDatasetsError is a struct for typed errors of method [`DatasetsAPI::get_all_datasets`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum GetAllDatasetsError {
33    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// GetDatasetError is a struct for typed errors of method [`DatasetsAPI::get_dataset`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum GetDatasetError {
41    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// Data Access Controls in Datadog is a feature that allows administrators and access managers to regulate
46/// access to sensitive data. By defining Restricted Datasets, you can ensure that only specific teams or roles can
47/// view certain types of telemetry (for example, logs, traces, metrics, and RUM data).
48#[derive(Debug, Clone)]
49pub struct DatasetsAPI {
50    config: datadog::Configuration,
51    client: reqwest_middleware::ClientWithMiddleware,
52}
53
54impl Default for DatasetsAPI {
55    fn default() -> Self {
56        Self::with_config(datadog::Configuration::default())
57    }
58}
59
60impl DatasetsAPI {
61    pub fn new() -> Self {
62        Self::default()
63    }
64    pub fn with_config(config: datadog::Configuration) -> Self {
65        let mut reqwest_client_builder = reqwest::Client::builder();
66
67        if let Some(proxy_url) = &config.proxy_url {
68            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
69            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
70        }
71
72        let mut middleware_client_builder =
73            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
74
75        if config.enable_retry {
76            struct RetryableStatus;
77            impl reqwest_retry::RetryableStrategy for RetryableStatus {
78                fn handle(
79                    &self,
80                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
81                ) -> Option<reqwest_retry::Retryable> {
82                    match res {
83                        Ok(success) => reqwest_retry::default_on_request_success(success),
84                        Err(_) => None,
85                    }
86                }
87            }
88            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
89                .build_with_max_retries(config.max_retries);
90
91            let retry_middleware =
92                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
93                    backoff_policy,
94                    RetryableStatus,
95                );
96
97            middleware_client_builder = middleware_client_builder.with(retry_middleware);
98        }
99
100        let client = middleware_client_builder.build();
101
102        Self { config, client }
103    }
104
105    pub fn with_client_and_config(
106        config: datadog::Configuration,
107        client: reqwest_middleware::ClientWithMiddleware,
108    ) -> Self {
109        Self { config, client }
110    }
111
112    /// Create a dataset with the configurations in the request.
113    pub async fn create_dataset(
114        &self,
115        body: crate::datadogV2::model::DatasetCreateRequest,
116    ) -> Result<crate::datadogV2::model::DatasetResponseSingle, datadog::Error<CreateDatasetError>>
117    {
118        match self.create_dataset_with_http_info(body).await {
119            Ok(response_content) => {
120                if let Some(e) = response_content.entity {
121                    Ok(e)
122                } else {
123                    Err(datadog::Error::Serde(serde::de::Error::custom(
124                        "response content was None",
125                    )))
126                }
127            }
128            Err(err) => Err(err),
129        }
130    }
131
132    /// Create a dataset with the configurations in the request.
133    pub async fn create_dataset_with_http_info(
134        &self,
135        body: crate::datadogV2::model::DatasetCreateRequest,
136    ) -> Result<
137        datadog::ResponseContent<crate::datadogV2::model::DatasetResponseSingle>,
138        datadog::Error<CreateDatasetError>,
139    > {
140        let local_configuration = &self.config;
141        let operation_id = "v2.create_dataset";
142
143        let local_client = &self.client;
144
145        let local_uri_str = format!(
146            "{}/api/v2/datasets",
147            local_configuration.get_operation_host(operation_id)
148        );
149        let mut local_req_builder =
150            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
151
152        // build headers
153        let mut headers = HeaderMap::new();
154        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
155        headers.insert("Accept", HeaderValue::from_static("application/json"));
156
157        // build user agent
158        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
159            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
160            Err(e) => {
161                log::warn!("Failed to parse user agent header: {e}, falling back to default");
162                headers.insert(
163                    reqwest::header::USER_AGENT,
164                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
165                )
166            }
167        };
168
169        // build auth
170        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
171            headers.insert(
172                "DD-API-KEY",
173                HeaderValue::from_str(local_key.key.as_str())
174                    .expect("failed to parse DD-API-KEY header"),
175            );
176        };
177        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
178            headers.insert(
179                "DD-APPLICATION-KEY",
180                HeaderValue::from_str(local_key.key.as_str())
181                    .expect("failed to parse DD-APPLICATION-KEY header"),
182            );
183        };
184
185        // build body parameters
186        let output = Vec::new();
187        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
188        if body.serialize(&mut ser).is_ok() {
189            if let Some(content_encoding) = headers.get("Content-Encoding") {
190                match content_encoding.to_str().unwrap_or_default() {
191                    "gzip" => {
192                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
193                        let _ = enc.write_all(ser.into_inner().as_slice());
194                        match enc.finish() {
195                            Ok(buf) => {
196                                local_req_builder = local_req_builder.body(buf);
197                            }
198                            Err(e) => return Err(datadog::Error::Io(e)),
199                        }
200                    }
201                    "deflate" => {
202                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
203                        let _ = enc.write_all(ser.into_inner().as_slice());
204                        match enc.finish() {
205                            Ok(buf) => {
206                                local_req_builder = local_req_builder.body(buf);
207                            }
208                            Err(e) => return Err(datadog::Error::Io(e)),
209                        }
210                    }
211                    "zstd1" => {
212                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
213                        let _ = enc.write_all(ser.into_inner().as_slice());
214                        match enc.finish() {
215                            Ok(buf) => {
216                                local_req_builder = local_req_builder.body(buf);
217                            }
218                            Err(e) => return Err(datadog::Error::Io(e)),
219                        }
220                    }
221                    _ => {
222                        local_req_builder = local_req_builder.body(ser.into_inner());
223                    }
224                }
225            } else {
226                local_req_builder = local_req_builder.body(ser.into_inner());
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::DatasetResponseSingle>(
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<CreateDatasetError> =
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    /// Deletes the dataset associated with the ID.
265    pub async fn delete_dataset(
266        &self,
267        dataset_id: String,
268    ) -> Result<(), datadog::Error<DeleteDatasetError>> {
269        match self.delete_dataset_with_http_info(dataset_id).await {
270            Ok(_) => Ok(()),
271            Err(err) => Err(err),
272        }
273    }
274
275    /// Deletes the dataset associated with the ID.
276    pub async fn delete_dataset_with_http_info(
277        &self,
278        dataset_id: String,
279    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteDatasetError>> {
280        let local_configuration = &self.config;
281        let operation_id = "v2.delete_dataset";
282
283        let local_client = &self.client;
284
285        let local_uri_str = format!(
286            "{}/api/v2/datasets/{dataset_id}",
287            local_configuration.get_operation_host(operation_id),
288            dataset_id = datadog::urlencode(dataset_id)
289        );
290        let mut local_req_builder =
291            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
292
293        // build headers
294        let mut headers = HeaderMap::new();
295        headers.insert("Accept", HeaderValue::from_static("*/*"));
296
297        // build user agent
298        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
299            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
300            Err(e) => {
301                log::warn!("Failed to parse user agent header: {e}, falling back to default");
302                headers.insert(
303                    reqwest::header::USER_AGENT,
304                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
305                )
306            }
307        };
308
309        // build auth
310        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
311            headers.insert(
312                "DD-API-KEY",
313                HeaderValue::from_str(local_key.key.as_str())
314                    .expect("failed to parse DD-API-KEY header"),
315            );
316        };
317        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
318            headers.insert(
319                "DD-APPLICATION-KEY",
320                HeaderValue::from_str(local_key.key.as_str())
321                    .expect("failed to parse DD-APPLICATION-KEY header"),
322            );
323        };
324
325        local_req_builder = local_req_builder.headers(headers);
326        let local_req = local_req_builder.build()?;
327        log::debug!("request content: {:?}", local_req.body());
328        let local_resp = local_client.execute(local_req).await?;
329
330        let local_status = local_resp.status();
331        let local_content = local_resp.text().await?;
332        log::debug!("response content: {}", local_content);
333
334        if !local_status.is_client_error() && !local_status.is_server_error() {
335            Ok(datadog::ResponseContent {
336                status: local_status,
337                content: local_content,
338                entity: None,
339            })
340        } else {
341            let local_entity: Option<DeleteDatasetError> =
342                serde_json::from_str(&local_content).ok();
343            let local_error = datadog::ResponseContent {
344                status: local_status,
345                content: local_content,
346                entity: local_entity,
347            };
348            Err(datadog::Error::ResponseError(local_error))
349        }
350    }
351
352    /// Get all datasets that have been configured for an organization.
353    pub async fn get_all_datasets(
354        &self,
355    ) -> Result<crate::datadogV2::model::DatasetResponseMulti, datadog::Error<GetAllDatasetsError>>
356    {
357        match self.get_all_datasets_with_http_info().await {
358            Ok(response_content) => {
359                if let Some(e) = response_content.entity {
360                    Ok(e)
361                } else {
362                    Err(datadog::Error::Serde(serde::de::Error::custom(
363                        "response content was None",
364                    )))
365                }
366            }
367            Err(err) => Err(err),
368        }
369    }
370
371    /// Get all datasets that have been configured for an organization.
372    pub async fn get_all_datasets_with_http_info(
373        &self,
374    ) -> Result<
375        datadog::ResponseContent<crate::datadogV2::model::DatasetResponseMulti>,
376        datadog::Error<GetAllDatasetsError>,
377    > {
378        let local_configuration = &self.config;
379        let operation_id = "v2.get_all_datasets";
380
381        let local_client = &self.client;
382
383        let local_uri_str = format!(
384            "{}/api/v2/datasets",
385            local_configuration.get_operation_host(operation_id)
386        );
387        let mut local_req_builder =
388            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
389
390        // build headers
391        let mut headers = HeaderMap::new();
392        headers.insert("Accept", HeaderValue::from_static("application/json"));
393
394        // build user agent
395        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
396            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
397            Err(e) => {
398                log::warn!("Failed to parse user agent header: {e}, falling back to default");
399                headers.insert(
400                    reqwest::header::USER_AGENT,
401                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
402                )
403            }
404        };
405
406        // build auth
407        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
408            headers.insert(
409                "DD-API-KEY",
410                HeaderValue::from_str(local_key.key.as_str())
411                    .expect("failed to parse DD-API-KEY header"),
412            );
413        };
414        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
415            headers.insert(
416                "DD-APPLICATION-KEY",
417                HeaderValue::from_str(local_key.key.as_str())
418                    .expect("failed to parse DD-APPLICATION-KEY header"),
419            );
420        };
421
422        local_req_builder = local_req_builder.headers(headers);
423        let local_req = local_req_builder.build()?;
424        log::debug!("request content: {:?}", local_req.body());
425        let local_resp = local_client.execute(local_req).await?;
426
427        let local_status = local_resp.status();
428        let local_content = local_resp.text().await?;
429        log::debug!("response content: {}", local_content);
430
431        if !local_status.is_client_error() && !local_status.is_server_error() {
432            match serde_json::from_str::<crate::datadogV2::model::DatasetResponseMulti>(
433                &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<GetAllDatasetsError> =
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    /// Retrieves the dataset associated with the ID.
457    pub async fn get_dataset(
458        &self,
459        dataset_id: String,
460    ) -> Result<crate::datadogV2::model::DatasetResponseSingle, datadog::Error<GetDatasetError>>
461    {
462        match self.get_dataset_with_http_info(dataset_id).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    /// Retrieves the dataset associated with the ID.
477    pub async fn get_dataset_with_http_info(
478        &self,
479        dataset_id: String,
480    ) -> Result<
481        datadog::ResponseContent<crate::datadogV2::model::DatasetResponseSingle>,
482        datadog::Error<GetDatasetError>,
483    > {
484        let local_configuration = &self.config;
485        let operation_id = "v2.get_dataset";
486
487        let local_client = &self.client;
488
489        let local_uri_str = format!(
490            "{}/api/v2/datasets/{dataset_id}",
491            local_configuration.get_operation_host(operation_id),
492            dataset_id = datadog::urlencode(dataset_id)
493        );
494        let mut local_req_builder =
495            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
496
497        // build headers
498        let mut headers = HeaderMap::new();
499        headers.insert("Accept", HeaderValue::from_static("application/json"));
500
501        // build user agent
502        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
503            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
504            Err(e) => {
505                log::warn!("Failed to parse user agent header: {e}, falling back to default");
506                headers.insert(
507                    reqwest::header::USER_AGENT,
508                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
509                )
510            }
511        };
512
513        // build auth
514        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
515            headers.insert(
516                "DD-API-KEY",
517                HeaderValue::from_str(local_key.key.as_str())
518                    .expect("failed to parse DD-API-KEY header"),
519            );
520        };
521        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
522            headers.insert(
523                "DD-APPLICATION-KEY",
524                HeaderValue::from_str(local_key.key.as_str())
525                    .expect("failed to parse DD-APPLICATION-KEY header"),
526            );
527        };
528
529        local_req_builder = local_req_builder.headers(headers);
530        let local_req = local_req_builder.build()?;
531        log::debug!("request content: {:?}", local_req.body());
532        let local_resp = local_client.execute(local_req).await?;
533
534        let local_status = local_resp.status();
535        let local_content = local_resp.text().await?;
536        log::debug!("response content: {}", local_content);
537
538        if !local_status.is_client_error() && !local_status.is_server_error() {
539            match serde_json::from_str::<crate::datadogV2::model::DatasetResponseSingle>(
540                &local_content,
541            ) {
542                Ok(e) => {
543                    return Ok(datadog::ResponseContent {
544                        status: local_status,
545                        content: local_content,
546                        entity: Some(e),
547                    })
548                }
549                Err(e) => return Err(datadog::Error::Serde(e)),
550            };
551        } else {
552            let local_entity: Option<GetDatasetError> = serde_json::from_str(&local_content).ok();
553            let local_error = datadog::ResponseContent {
554                status: local_status,
555                content: local_content,
556                entity: local_entity,
557            };
558            Err(datadog::Error::ResponseError(local_error))
559        }
560    }
561}