datadog_api_client/datadogV2/api/
api_reference_tables.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/// ListTablesOptionalParams is a struct for passing parameters to the method [`ReferenceTablesAPI::list_tables`]
14#[non_exhaustive]
15#[derive(Clone, Default, Debug)]
16pub struct ListTablesOptionalParams {
17    /// Number of tables to return.
18    pub limit: Option<i64>,
19    /// Number of tables to skip for pagination.
20    pub offset: Option<i64>,
21    /// Sort field and direction. Use field name for ascending, prefix with "-" for descending.
22    pub sort: Option<crate::datadogV2::model::ReferenceTableSortType>,
23    /// Filter by table status.
24    pub filter_status: Option<String>,
25    /// Filter by exact table name match.
26    pub filter_table_name_exact: Option<String>,
27    /// Filter by table name containing substring.
28    pub filter_table_name_contains: Option<String>,
29}
30
31impl ListTablesOptionalParams {
32    /// Number of tables to return.
33    pub fn limit(mut self, value: i64) -> Self {
34        self.limit = Some(value);
35        self
36    }
37    /// Number of tables to skip for pagination.
38    pub fn offset(mut self, value: i64) -> Self {
39        self.offset = Some(value);
40        self
41    }
42    /// Sort field and direction. Use field name for ascending, prefix with "-" for descending.
43    pub fn sort(mut self, value: crate::datadogV2::model::ReferenceTableSortType) -> Self {
44        self.sort = Some(value);
45        self
46    }
47    /// Filter by table status.
48    pub fn filter_status(mut self, value: String) -> Self {
49        self.filter_status = Some(value);
50        self
51    }
52    /// Filter by exact table name match.
53    pub fn filter_table_name_exact(mut self, value: String) -> Self {
54        self.filter_table_name_exact = Some(value);
55        self
56    }
57    /// Filter by table name containing substring.
58    pub fn filter_table_name_contains(mut self, value: String) -> Self {
59        self.filter_table_name_contains = Some(value);
60        self
61    }
62}
63
64/// CreateReferenceTableError is a struct for typed errors of method [`ReferenceTablesAPI::create_reference_table`]
65#[derive(Debug, Clone, Serialize, Deserialize)]
66#[serde(untagged)]
67pub enum CreateReferenceTableError {
68    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
69    UnknownValue(serde_json::Value),
70}
71
72/// CreateReferenceTableUploadError is a struct for typed errors of method [`ReferenceTablesAPI::create_reference_table_upload`]
73#[derive(Debug, Clone, Serialize, Deserialize)]
74#[serde(untagged)]
75pub enum CreateReferenceTableUploadError {
76    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
77    UnknownValue(serde_json::Value),
78}
79
80/// DeleteTableError is a struct for typed errors of method [`ReferenceTablesAPI::delete_table`]
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(untagged)]
83pub enum DeleteTableError {
84    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
85    UnknownValue(serde_json::Value),
86}
87
88/// GetRowsByIDError is a struct for typed errors of method [`ReferenceTablesAPI::get_rows_by_id`]
89#[derive(Debug, Clone, Serialize, Deserialize)]
90#[serde(untagged)]
91pub enum GetRowsByIDError {
92    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
93    UnknownValue(serde_json::Value),
94}
95
96/// GetTableError is a struct for typed errors of method [`ReferenceTablesAPI::get_table`]
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(untagged)]
99pub enum GetTableError {
100    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
101    UnknownValue(serde_json::Value),
102}
103
104/// ListTablesError is a struct for typed errors of method [`ReferenceTablesAPI::list_tables`]
105#[derive(Debug, Clone, Serialize, Deserialize)]
106#[serde(untagged)]
107pub enum ListTablesError {
108    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
109    UnknownValue(serde_json::Value),
110}
111
112/// UpdateReferenceTableError is a struct for typed errors of method [`ReferenceTablesAPI::update_reference_table`]
113#[derive(Debug, Clone, Serialize, Deserialize)]
114#[serde(untagged)]
115pub enum UpdateReferenceTableError {
116    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
117    UnknownValue(serde_json::Value),
118}
119
120/// Auto-generated tag Reference Tables
121#[derive(Debug, Clone)]
122pub struct ReferenceTablesAPI {
123    config: datadog::Configuration,
124    client: reqwest_middleware::ClientWithMiddleware,
125}
126
127impl Default for ReferenceTablesAPI {
128    fn default() -> Self {
129        Self::with_config(datadog::Configuration::default())
130    }
131}
132
133impl ReferenceTablesAPI {
134    pub fn new() -> Self {
135        Self::default()
136    }
137    pub fn with_config(config: datadog::Configuration) -> Self {
138        let mut reqwest_client_builder = reqwest::Client::builder();
139
140        if let Some(proxy_url) = &config.proxy_url {
141            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
142            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
143        }
144
145        let mut middleware_client_builder =
146            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
147
148        if config.enable_retry {
149            struct RetryableStatus;
150            impl reqwest_retry::RetryableStrategy for RetryableStatus {
151                fn handle(
152                    &self,
153                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
154                ) -> Option<reqwest_retry::Retryable> {
155                    match res {
156                        Ok(success) => reqwest_retry::default_on_request_success(success),
157                        Err(_) => None,
158                    }
159                }
160            }
161            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
162                .build_with_max_retries(config.max_retries);
163
164            let retry_middleware =
165                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
166                    backoff_policy,
167                    RetryableStatus,
168                );
169
170            middleware_client_builder = middleware_client_builder.with(retry_middleware);
171        }
172
173        let client = middleware_client_builder.build();
174
175        Self { config, client }
176    }
177
178    pub fn with_client_and_config(
179        config: datadog::Configuration,
180        client: reqwest_middleware::ClientWithMiddleware,
181    ) -> Self {
182        Self { config, client }
183    }
184
185    /// Create a new reference table. You can provide data in two ways: 1) Call POST api/v2/reference-tables/upload first to get an upload ID, then PUT chunks of CSV data to each provided URL, and finally call this POST endpoint with the upload_id in file_metadata, OR 2) Provide access_details in file_metadata pointing to a CSV file in cloud storage (Amazon S3, Azure Blob Storage, or GCP Cloud Storage).
186    pub async fn create_reference_table(
187        &self,
188        body: crate::datadogV2::model::CreateTableRequest,
189    ) -> Result<crate::datadogV2::model::TableResultV2, datadog::Error<CreateReferenceTableError>>
190    {
191        match self.create_reference_table_with_http_info(body).await {
192            Ok(response_content) => {
193                if let Some(e) = response_content.entity {
194                    Ok(e)
195                } else {
196                    Err(datadog::Error::Serde(serde::de::Error::custom(
197                        "response content was None",
198                    )))
199                }
200            }
201            Err(err) => Err(err),
202        }
203    }
204
205    /// Create a new reference table. You can provide data in two ways: 1) Call POST api/v2/reference-tables/upload first to get an upload ID, then PUT chunks of CSV data to each provided URL, and finally call this POST endpoint with the upload_id in file_metadata, OR 2) Provide access_details in file_metadata pointing to a CSV file in cloud storage (Amazon S3, Azure Blob Storage, or GCP Cloud Storage).
206    pub async fn create_reference_table_with_http_info(
207        &self,
208        body: crate::datadogV2::model::CreateTableRequest,
209    ) -> Result<
210        datadog::ResponseContent<crate::datadogV2::model::TableResultV2>,
211        datadog::Error<CreateReferenceTableError>,
212    > {
213        let local_configuration = &self.config;
214        let operation_id = "v2.create_reference_table";
215
216        let local_client = &self.client;
217
218        let local_uri_str = format!(
219            "{}/api/v2/reference-tables/tables",
220            local_configuration.get_operation_host(operation_id)
221        );
222        let mut local_req_builder =
223            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
224
225        // build headers
226        let mut headers = HeaderMap::new();
227        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
228        headers.insert("Accept", HeaderValue::from_static("application/json"));
229
230        // build user agent
231        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
232            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
233            Err(e) => {
234                log::warn!("Failed to parse user agent header: {e}, falling back to default");
235                headers.insert(
236                    reqwest::header::USER_AGENT,
237                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
238                )
239            }
240        };
241
242        // build auth
243        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
244            headers.insert(
245                "DD-API-KEY",
246                HeaderValue::from_str(local_key.key.as_str())
247                    .expect("failed to parse DD-API-KEY header"),
248            );
249        };
250        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
251            headers.insert(
252                "DD-APPLICATION-KEY",
253                HeaderValue::from_str(local_key.key.as_str())
254                    .expect("failed to parse DD-APPLICATION-KEY header"),
255            );
256        };
257
258        // build body parameters
259        let output = Vec::new();
260        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
261        if body.serialize(&mut ser).is_ok() {
262            if let Some(content_encoding) = headers.get("Content-Encoding") {
263                match content_encoding.to_str().unwrap_or_default() {
264                    "gzip" => {
265                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
266                        let _ = enc.write_all(ser.into_inner().as_slice());
267                        match enc.finish() {
268                            Ok(buf) => {
269                                local_req_builder = local_req_builder.body(buf);
270                            }
271                            Err(e) => return Err(datadog::Error::Io(e)),
272                        }
273                    }
274                    "deflate" => {
275                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
276                        let _ = enc.write_all(ser.into_inner().as_slice());
277                        match enc.finish() {
278                            Ok(buf) => {
279                                local_req_builder = local_req_builder.body(buf);
280                            }
281                            Err(e) => return Err(datadog::Error::Io(e)),
282                        }
283                    }
284                    "zstd1" => {
285                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
286                        let _ = enc.write_all(ser.into_inner().as_slice());
287                        match enc.finish() {
288                            Ok(buf) => {
289                                local_req_builder = local_req_builder.body(buf);
290                            }
291                            Err(e) => return Err(datadog::Error::Io(e)),
292                        }
293                    }
294                    _ => {
295                        local_req_builder = local_req_builder.body(ser.into_inner());
296                    }
297                }
298            } else {
299                local_req_builder = local_req_builder.body(ser.into_inner());
300            }
301        }
302
303        local_req_builder = local_req_builder.headers(headers);
304        let local_req = local_req_builder.build()?;
305        log::debug!("request content: {:?}", local_req.body());
306        let local_resp = local_client.execute(local_req).await?;
307
308        let local_status = local_resp.status();
309        let local_content = local_resp.text().await?;
310        log::debug!("response content: {}", local_content);
311
312        if !local_status.is_client_error() && !local_status.is_server_error() {
313            match serde_json::from_str::<crate::datadogV2::model::TableResultV2>(&local_content) {
314                Ok(e) => {
315                    return Ok(datadog::ResponseContent {
316                        status: local_status,
317                        content: local_content,
318                        entity: Some(e),
319                    })
320                }
321                Err(e) => return Err(datadog::Error::Serde(e)),
322            };
323        } else {
324            let local_entity: Option<CreateReferenceTableError> =
325                serde_json::from_str(&local_content).ok();
326            let local_error = datadog::ResponseContent {
327                status: local_status,
328                content: local_content,
329                entity: local_entity,
330            };
331            Err(datadog::Error::ResponseError(local_error))
332        }
333    }
334
335    /// Create a reference table upload for bulk data ingestion
336    pub async fn create_reference_table_upload(
337        &self,
338        body: crate::datadogV2::model::CreateUploadRequest,
339    ) -> Result<
340        crate::datadogV2::model::CreateUploadResponse,
341        datadog::Error<CreateReferenceTableUploadError>,
342    > {
343        match self
344            .create_reference_table_upload_with_http_info(body)
345            .await
346        {
347            Ok(response_content) => {
348                if let Some(e) = response_content.entity {
349                    Ok(e)
350                } else {
351                    Err(datadog::Error::Serde(serde::de::Error::custom(
352                        "response content was None",
353                    )))
354                }
355            }
356            Err(err) => Err(err),
357        }
358    }
359
360    /// Create a reference table upload for bulk data ingestion
361    pub async fn create_reference_table_upload_with_http_info(
362        &self,
363        body: crate::datadogV2::model::CreateUploadRequest,
364    ) -> Result<
365        datadog::ResponseContent<crate::datadogV2::model::CreateUploadResponse>,
366        datadog::Error<CreateReferenceTableUploadError>,
367    > {
368        let local_configuration = &self.config;
369        let operation_id = "v2.create_reference_table_upload";
370
371        let local_client = &self.client;
372
373        let local_uri_str = format!(
374            "{}/api/v2/reference-tables/uploads",
375            local_configuration.get_operation_host(operation_id)
376        );
377        let mut local_req_builder =
378            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
379
380        // build headers
381        let mut headers = HeaderMap::new();
382        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
383        headers.insert("Accept", HeaderValue::from_static("application/json"));
384
385        // build user agent
386        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
387            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
388            Err(e) => {
389                log::warn!("Failed to parse user agent header: {e}, falling back to default");
390                headers.insert(
391                    reqwest::header::USER_AGENT,
392                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
393                )
394            }
395        };
396
397        // build auth
398        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
399            headers.insert(
400                "DD-API-KEY",
401                HeaderValue::from_str(local_key.key.as_str())
402                    .expect("failed to parse DD-API-KEY header"),
403            );
404        };
405        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
406            headers.insert(
407                "DD-APPLICATION-KEY",
408                HeaderValue::from_str(local_key.key.as_str())
409                    .expect("failed to parse DD-APPLICATION-KEY header"),
410            );
411        };
412
413        // build body parameters
414        let output = Vec::new();
415        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
416        if body.serialize(&mut ser).is_ok() {
417            if let Some(content_encoding) = headers.get("Content-Encoding") {
418                match content_encoding.to_str().unwrap_or_default() {
419                    "gzip" => {
420                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
421                        let _ = enc.write_all(ser.into_inner().as_slice());
422                        match enc.finish() {
423                            Ok(buf) => {
424                                local_req_builder = local_req_builder.body(buf);
425                            }
426                            Err(e) => return Err(datadog::Error::Io(e)),
427                        }
428                    }
429                    "deflate" => {
430                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
431                        let _ = enc.write_all(ser.into_inner().as_slice());
432                        match enc.finish() {
433                            Ok(buf) => {
434                                local_req_builder = local_req_builder.body(buf);
435                            }
436                            Err(e) => return Err(datadog::Error::Io(e)),
437                        }
438                    }
439                    "zstd1" => {
440                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
441                        let _ = enc.write_all(ser.into_inner().as_slice());
442                        match enc.finish() {
443                            Ok(buf) => {
444                                local_req_builder = local_req_builder.body(buf);
445                            }
446                            Err(e) => return Err(datadog::Error::Io(e)),
447                        }
448                    }
449                    _ => {
450                        local_req_builder = local_req_builder.body(ser.into_inner());
451                    }
452                }
453            } else {
454                local_req_builder = local_req_builder.body(ser.into_inner());
455            }
456        }
457
458        local_req_builder = local_req_builder.headers(headers);
459        let local_req = local_req_builder.build()?;
460        log::debug!("request content: {:?}", local_req.body());
461        let local_resp = local_client.execute(local_req).await?;
462
463        let local_status = local_resp.status();
464        let local_content = local_resp.text().await?;
465        log::debug!("response content: {}", local_content);
466
467        if !local_status.is_client_error() && !local_status.is_server_error() {
468            match serde_json::from_str::<crate::datadogV2::model::CreateUploadResponse>(
469                &local_content,
470            ) {
471                Ok(e) => {
472                    return Ok(datadog::ResponseContent {
473                        status: local_status,
474                        content: local_content,
475                        entity: Some(e),
476                    })
477                }
478                Err(e) => return Err(datadog::Error::Serde(e)),
479            };
480        } else {
481            let local_entity: Option<CreateReferenceTableUploadError> =
482                serde_json::from_str(&local_content).ok();
483            let local_error = datadog::ResponseContent {
484                status: local_status,
485                content: local_content,
486                entity: local_entity,
487            };
488            Err(datadog::Error::ResponseError(local_error))
489        }
490    }
491
492    /// Delete a reference table by ID
493    pub async fn delete_table(&self, id: String) -> Result<(), datadog::Error<DeleteTableError>> {
494        match self.delete_table_with_http_info(id).await {
495            Ok(_) => Ok(()),
496            Err(err) => Err(err),
497        }
498    }
499
500    /// Delete a reference table by ID
501    pub async fn delete_table_with_http_info(
502        &self,
503        id: String,
504    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteTableError>> {
505        let local_configuration = &self.config;
506        let operation_id = "v2.delete_table";
507
508        let local_client = &self.client;
509
510        let local_uri_str = format!(
511            "{}/api/v2/reference-tables/tables/{id}",
512            local_configuration.get_operation_host(operation_id),
513            id = datadog::urlencode(id)
514        );
515        let mut local_req_builder =
516            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
517
518        // build headers
519        let mut headers = HeaderMap::new();
520        headers.insert("Accept", HeaderValue::from_static("*/*"));
521
522        // build user agent
523        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
524            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
525            Err(e) => {
526                log::warn!("Failed to parse user agent header: {e}, falling back to default");
527                headers.insert(
528                    reqwest::header::USER_AGENT,
529                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
530                )
531            }
532        };
533
534        // build auth
535        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
536            headers.insert(
537                "DD-API-KEY",
538                HeaderValue::from_str(local_key.key.as_str())
539                    .expect("failed to parse DD-API-KEY header"),
540            );
541        };
542        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
543            headers.insert(
544                "DD-APPLICATION-KEY",
545                HeaderValue::from_str(local_key.key.as_str())
546                    .expect("failed to parse DD-APPLICATION-KEY header"),
547            );
548        };
549
550        local_req_builder = local_req_builder.headers(headers);
551        let local_req = local_req_builder.build()?;
552        log::debug!("request content: {:?}", local_req.body());
553        let local_resp = local_client.execute(local_req).await?;
554
555        let local_status = local_resp.status();
556        let local_content = local_resp.text().await?;
557        log::debug!("response content: {}", local_content);
558
559        if !local_status.is_client_error() && !local_status.is_server_error() {
560            Ok(datadog::ResponseContent {
561                status: local_status,
562                content: local_content,
563                entity: None,
564            })
565        } else {
566            let local_entity: Option<DeleteTableError> = 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
576    /// Get reference table rows by their primary key values.
577    pub async fn get_rows_by_id(
578        &self,
579        id: String,
580        row_id: Vec<String>,
581    ) -> Result<crate::datadogV2::model::TableRowResourceArray, datadog::Error<GetRowsByIDError>>
582    {
583        match self.get_rows_by_id_with_http_info(id, row_id).await {
584            Ok(response_content) => {
585                if let Some(e) = response_content.entity {
586                    Ok(e)
587                } else {
588                    Err(datadog::Error::Serde(serde::de::Error::custom(
589                        "response content was None",
590                    )))
591                }
592            }
593            Err(err) => Err(err),
594        }
595    }
596
597    /// Get reference table rows by their primary key values.
598    pub async fn get_rows_by_id_with_http_info(
599        &self,
600        id: String,
601        row_id: Vec<String>,
602    ) -> Result<
603        datadog::ResponseContent<crate::datadogV2::model::TableRowResourceArray>,
604        datadog::Error<GetRowsByIDError>,
605    > {
606        let local_configuration = &self.config;
607        let operation_id = "v2.get_rows_by_id";
608
609        let local_client = &self.client;
610
611        let local_uri_str = format!(
612            "{}/api/v2/reference-tables/tables/{id}/rows",
613            local_configuration.get_operation_host(operation_id),
614            id = datadog::urlencode(id)
615        );
616        let mut local_req_builder =
617            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
618
619        local_req_builder = local_req_builder.query(&[(
620            "row_id",
621            &row_id
622                .iter()
623                .map(|p| p.to_string())
624                .collect::<Vec<String>>()
625                .join(",")
626                .to_string(),
627        )]);
628
629        // build headers
630        let mut headers = HeaderMap::new();
631        headers.insert("Accept", HeaderValue::from_static("application/json"));
632
633        // build user agent
634        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
635            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
636            Err(e) => {
637                log::warn!("Failed to parse user agent header: {e}, falling back to default");
638                headers.insert(
639                    reqwest::header::USER_AGENT,
640                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
641                )
642            }
643        };
644
645        // build auth
646        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
647            headers.insert(
648                "DD-API-KEY",
649                HeaderValue::from_str(local_key.key.as_str())
650                    .expect("failed to parse DD-API-KEY header"),
651            );
652        };
653        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
654            headers.insert(
655                "DD-APPLICATION-KEY",
656                HeaderValue::from_str(local_key.key.as_str())
657                    .expect("failed to parse DD-APPLICATION-KEY header"),
658            );
659        };
660
661        local_req_builder = local_req_builder.headers(headers);
662        let local_req = local_req_builder.build()?;
663        log::debug!("request content: {:?}", local_req.body());
664        let local_resp = local_client.execute(local_req).await?;
665
666        let local_status = local_resp.status();
667        let local_content = local_resp.text().await?;
668        log::debug!("response content: {}", local_content);
669
670        if !local_status.is_client_error() && !local_status.is_server_error() {
671            match serde_json::from_str::<crate::datadogV2::model::TableRowResourceArray>(
672                &local_content,
673            ) {
674                Ok(e) => {
675                    return Ok(datadog::ResponseContent {
676                        status: local_status,
677                        content: local_content,
678                        entity: Some(e),
679                    })
680                }
681                Err(e) => return Err(datadog::Error::Serde(e)),
682            };
683        } else {
684            let local_entity: Option<GetRowsByIDError> = serde_json::from_str(&local_content).ok();
685            let local_error = datadog::ResponseContent {
686                status: local_status,
687                content: local_content,
688                entity: local_entity,
689            };
690            Err(datadog::Error::ResponseError(local_error))
691        }
692    }
693
694    /// Get a reference table by ID
695    pub async fn get_table(
696        &self,
697        id: String,
698    ) -> Result<crate::datadogV2::model::TableResultV2, datadog::Error<GetTableError>> {
699        match self.get_table_with_http_info(id).await {
700            Ok(response_content) => {
701                if let Some(e) = response_content.entity {
702                    Ok(e)
703                } else {
704                    Err(datadog::Error::Serde(serde::de::Error::custom(
705                        "response content was None",
706                    )))
707                }
708            }
709            Err(err) => Err(err),
710        }
711    }
712
713    /// Get a reference table by ID
714    pub async fn get_table_with_http_info(
715        &self,
716        id: String,
717    ) -> Result<
718        datadog::ResponseContent<crate::datadogV2::model::TableResultV2>,
719        datadog::Error<GetTableError>,
720    > {
721        let local_configuration = &self.config;
722        let operation_id = "v2.get_table";
723
724        let local_client = &self.client;
725
726        let local_uri_str = format!(
727            "{}/api/v2/reference-tables/tables/{id}",
728            local_configuration.get_operation_host(operation_id),
729            id = datadog::urlencode(id)
730        );
731        let mut local_req_builder =
732            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
733
734        // build headers
735        let mut headers = HeaderMap::new();
736        headers.insert("Accept", HeaderValue::from_static("application/json"));
737
738        // build user agent
739        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
740            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
741            Err(e) => {
742                log::warn!("Failed to parse user agent header: {e}, falling back to default");
743                headers.insert(
744                    reqwest::header::USER_AGENT,
745                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
746                )
747            }
748        };
749
750        // build auth
751        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
752            headers.insert(
753                "DD-API-KEY",
754                HeaderValue::from_str(local_key.key.as_str())
755                    .expect("failed to parse DD-API-KEY header"),
756            );
757        };
758        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
759            headers.insert(
760                "DD-APPLICATION-KEY",
761                HeaderValue::from_str(local_key.key.as_str())
762                    .expect("failed to parse DD-APPLICATION-KEY header"),
763            );
764        };
765
766        local_req_builder = local_req_builder.headers(headers);
767        let local_req = local_req_builder.build()?;
768        log::debug!("request content: {:?}", local_req.body());
769        let local_resp = local_client.execute(local_req).await?;
770
771        let local_status = local_resp.status();
772        let local_content = local_resp.text().await?;
773        log::debug!("response content: {}", local_content);
774
775        if !local_status.is_client_error() && !local_status.is_server_error() {
776            match serde_json::from_str::<crate::datadogV2::model::TableResultV2>(&local_content) {
777                Ok(e) => {
778                    return Ok(datadog::ResponseContent {
779                        status: local_status,
780                        content: local_content,
781                        entity: Some(e),
782                    })
783                }
784                Err(e) => return Err(datadog::Error::Serde(e)),
785            };
786        } else {
787            let local_entity: Option<GetTableError> = serde_json::from_str(&local_content).ok();
788            let local_error = datadog::ResponseContent {
789                status: local_status,
790                content: local_content,
791                entity: local_entity,
792            };
793            Err(datadog::Error::ResponseError(local_error))
794        }
795    }
796
797    /// List all reference tables in this organization.
798    pub async fn list_tables(
799        &self,
800        params: ListTablesOptionalParams,
801    ) -> Result<crate::datadogV2::model::TableResultV2Array, datadog::Error<ListTablesError>> {
802        match self.list_tables_with_http_info(params).await {
803            Ok(response_content) => {
804                if let Some(e) = response_content.entity {
805                    Ok(e)
806                } else {
807                    Err(datadog::Error::Serde(serde::de::Error::custom(
808                        "response content was None",
809                    )))
810                }
811            }
812            Err(err) => Err(err),
813        }
814    }
815
816    /// List all reference tables in this organization.
817    pub async fn list_tables_with_http_info(
818        &self,
819        params: ListTablesOptionalParams,
820    ) -> Result<
821        datadog::ResponseContent<crate::datadogV2::model::TableResultV2Array>,
822        datadog::Error<ListTablesError>,
823    > {
824        let local_configuration = &self.config;
825        let operation_id = "v2.list_tables";
826
827        // unbox and build optional parameters
828        let limit = params.limit;
829        let offset = params.offset;
830        let sort = params.sort;
831        let filter_status = params.filter_status;
832        let filter_table_name_exact = params.filter_table_name_exact;
833        let filter_table_name_contains = params.filter_table_name_contains;
834
835        let local_client = &self.client;
836
837        let local_uri_str = format!(
838            "{}/api/v2/reference-tables/tables",
839            local_configuration.get_operation_host(operation_id)
840        );
841        let mut local_req_builder =
842            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
843
844        if let Some(ref local_query_param) = limit {
845            local_req_builder =
846                local_req_builder.query(&[("limit", &local_query_param.to_string())]);
847        };
848        if let Some(ref local_query_param) = offset {
849            local_req_builder =
850                local_req_builder.query(&[("offset", &local_query_param.to_string())]);
851        };
852        if let Some(ref local_query_param) = sort {
853            local_req_builder =
854                local_req_builder.query(&[("sort", &local_query_param.to_string())]);
855        };
856        if let Some(ref local_query_param) = filter_status {
857            local_req_builder =
858                local_req_builder.query(&[("filter[status]", &local_query_param.to_string())]);
859        };
860        if let Some(ref local_query_param) = filter_table_name_exact {
861            local_req_builder = local_req_builder
862                .query(&[("filter[table_name][exact]", &local_query_param.to_string())]);
863        };
864        if let Some(ref local_query_param) = filter_table_name_contains {
865            local_req_builder = local_req_builder.query(&[(
866                "filter[table_name][contains]",
867                &local_query_param.to_string(),
868            )]);
869        };
870
871        // build headers
872        let mut headers = HeaderMap::new();
873        headers.insert("Accept", HeaderValue::from_static("application/json"));
874
875        // build user agent
876        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
877            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
878            Err(e) => {
879                log::warn!("Failed to parse user agent header: {e}, falling back to default");
880                headers.insert(
881                    reqwest::header::USER_AGENT,
882                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
883                )
884            }
885        };
886
887        // build auth
888        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
889            headers.insert(
890                "DD-API-KEY",
891                HeaderValue::from_str(local_key.key.as_str())
892                    .expect("failed to parse DD-API-KEY header"),
893            );
894        };
895        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
896            headers.insert(
897                "DD-APPLICATION-KEY",
898                HeaderValue::from_str(local_key.key.as_str())
899                    .expect("failed to parse DD-APPLICATION-KEY header"),
900            );
901        };
902
903        local_req_builder = local_req_builder.headers(headers);
904        let local_req = local_req_builder.build()?;
905        log::debug!("request content: {:?}", local_req.body());
906        let local_resp = local_client.execute(local_req).await?;
907
908        let local_status = local_resp.status();
909        let local_content = local_resp.text().await?;
910        log::debug!("response content: {}", local_content);
911
912        if !local_status.is_client_error() && !local_status.is_server_error() {
913            match serde_json::from_str::<crate::datadogV2::model::TableResultV2Array>(
914                &local_content,
915            ) {
916                Ok(e) => {
917                    return Ok(datadog::ResponseContent {
918                        status: local_status,
919                        content: local_content,
920                        entity: Some(e),
921                    })
922                }
923                Err(e) => return Err(datadog::Error::Serde(e)),
924            };
925        } else {
926            let local_entity: Option<ListTablesError> = serde_json::from_str(&local_content).ok();
927            let local_error = datadog::ResponseContent {
928                status: local_status,
929                content: local_content,
930                entity: local_entity,
931            };
932            Err(datadog::Error::ResponseError(local_error))
933        }
934    }
935
936    /// Update a reference table by ID. You can update the table's data, description, and tags. Note: The source type cannot be changed after table creation. For data updates: For existing tables of type `source:LOCAL_FILE`, call POST api/v2/reference-tables/uploads first to get an upload ID, then PUT chunks of CSV data to each provided URL, and finally call this PATCH endpoint with the upload_id in file_metadata. For existing tables with `source:` types of `S3`, `GCS`, or `AZURE`, provide updated access_details in file_metadata pointing to a CSV file in the same type of cloud storage.
937    pub async fn update_reference_table(
938        &self,
939        id: String,
940        body: crate::datadogV2::model::PatchTableRequest,
941    ) -> Result<(), datadog::Error<UpdateReferenceTableError>> {
942        match self.update_reference_table_with_http_info(id, body).await {
943            Ok(_) => Ok(()),
944            Err(err) => Err(err),
945        }
946    }
947
948    /// Update a reference table by ID. You can update the table's data, description, and tags. Note: The source type cannot be changed after table creation. For data updates: For existing tables of type `source:LOCAL_FILE`, call POST api/v2/reference-tables/uploads first to get an upload ID, then PUT chunks of CSV data to each provided URL, and finally call this PATCH endpoint with the upload_id in file_metadata. For existing tables with `source:` types of `S3`, `GCS`, or `AZURE`, provide updated access_details in file_metadata pointing to a CSV file in the same type of cloud storage.
949    pub async fn update_reference_table_with_http_info(
950        &self,
951        id: String,
952        body: crate::datadogV2::model::PatchTableRequest,
953    ) -> Result<datadog::ResponseContent<()>, datadog::Error<UpdateReferenceTableError>> {
954        let local_configuration = &self.config;
955        let operation_id = "v2.update_reference_table";
956
957        let local_client = &self.client;
958
959        let local_uri_str = format!(
960            "{}/api/v2/reference-tables/tables/{id}",
961            local_configuration.get_operation_host(operation_id),
962            id = datadog::urlencode(id)
963        );
964        let mut local_req_builder =
965            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
966
967        // build headers
968        let mut headers = HeaderMap::new();
969        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
970        headers.insert("Accept", HeaderValue::from_static("*/*"));
971
972        // build user agent
973        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
974            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
975            Err(e) => {
976                log::warn!("Failed to parse user agent header: {e}, falling back to default");
977                headers.insert(
978                    reqwest::header::USER_AGENT,
979                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
980                )
981            }
982        };
983
984        // build auth
985        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
986            headers.insert(
987                "DD-API-KEY",
988                HeaderValue::from_str(local_key.key.as_str())
989                    .expect("failed to parse DD-API-KEY header"),
990            );
991        };
992        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
993            headers.insert(
994                "DD-APPLICATION-KEY",
995                HeaderValue::from_str(local_key.key.as_str())
996                    .expect("failed to parse DD-APPLICATION-KEY header"),
997            );
998        };
999
1000        // build body parameters
1001        let output = Vec::new();
1002        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1003        if body.serialize(&mut ser).is_ok() {
1004            if let Some(content_encoding) = headers.get("Content-Encoding") {
1005                match content_encoding.to_str().unwrap_or_default() {
1006                    "gzip" => {
1007                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1008                        let _ = enc.write_all(ser.into_inner().as_slice());
1009                        match enc.finish() {
1010                            Ok(buf) => {
1011                                local_req_builder = local_req_builder.body(buf);
1012                            }
1013                            Err(e) => return Err(datadog::Error::Io(e)),
1014                        }
1015                    }
1016                    "deflate" => {
1017                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1018                        let _ = enc.write_all(ser.into_inner().as_slice());
1019                        match enc.finish() {
1020                            Ok(buf) => {
1021                                local_req_builder = local_req_builder.body(buf);
1022                            }
1023                            Err(e) => return Err(datadog::Error::Io(e)),
1024                        }
1025                    }
1026                    "zstd1" => {
1027                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1028                        let _ = enc.write_all(ser.into_inner().as_slice());
1029                        match enc.finish() {
1030                            Ok(buf) => {
1031                                local_req_builder = local_req_builder.body(buf);
1032                            }
1033                            Err(e) => return Err(datadog::Error::Io(e)),
1034                        }
1035                    }
1036                    _ => {
1037                        local_req_builder = local_req_builder.body(ser.into_inner());
1038                    }
1039                }
1040            } else {
1041                local_req_builder = local_req_builder.body(ser.into_inner());
1042            }
1043        }
1044
1045        local_req_builder = local_req_builder.headers(headers);
1046        let local_req = local_req_builder.build()?;
1047        log::debug!("request content: {:?}", local_req.body());
1048        let local_resp = local_client.execute(local_req).await?;
1049
1050        let local_status = local_resp.status();
1051        let local_content = local_resp.text().await?;
1052        log::debug!("response content: {}", local_content);
1053
1054        if !local_status.is_client_error() && !local_status.is_server_error() {
1055            Ok(datadog::ResponseContent {
1056                status: local_status,
1057                content: local_content,
1058                entity: None,
1059            })
1060        } else {
1061            let local_entity: Option<UpdateReferenceTableError> =
1062                serde_json::from_str(&local_content).ok();
1063            let local_error = datadog::ResponseContent {
1064                status: local_status,
1065                content: local_content,
1066                entity: local_entity,
1067            };
1068            Err(datadog::Error::ResponseError(local_error))
1069        }
1070    }
1071}