datadog_api_client/datadogV2/api/
api_users.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 async_stream::try_stream;
6use flate2::{
7    write::{GzEncoder, ZlibEncoder},
8    Compression,
9};
10use futures_core::stream::Stream;
11use reqwest::header::{HeaderMap, HeaderValue};
12use serde::{Deserialize, Serialize};
13use std::io::Write;
14
15/// ListUsersOptionalParams is a struct for passing parameters to the method [`UsersAPI::list_users`]
16#[non_exhaustive]
17#[derive(Clone, Default, Debug)]
18pub struct ListUsersOptionalParams {
19    /// Size for a given page. The maximum allowed value is 100.
20    pub page_size: Option<i64>,
21    /// Specific page number to return.
22    pub page_number: Option<i64>,
23    /// User attribute to order results by. Sort order is ascending by default.
24    /// Sort order is descending if the field
25    /// is prefixed by a negative sign, for example `sort=-name`. Options: `name`,
26    /// `modified_at`, `user_count`.
27    pub sort: Option<String>,
28    /// Direction of sort. Options: `asc`, `desc`.
29    pub sort_dir: Option<crate::datadogV2::model::QuerySortOrder>,
30    /// Filter all users by the given string. Defaults to no filtering.
31    pub filter: Option<String>,
32    /// Filter on status attribute.
33    /// Comma separated list, with possible values `Active`, `Pending`, and `Disabled`.
34    /// Defaults to no filtering.
35    pub filter_status: Option<String>,
36}
37
38impl ListUsersOptionalParams {
39    /// Size for a given page. The maximum allowed value is 100.
40    pub fn page_size(mut self, value: i64) -> Self {
41        self.page_size = Some(value);
42        self
43    }
44    /// Specific page number to return.
45    pub fn page_number(mut self, value: i64) -> Self {
46        self.page_number = Some(value);
47        self
48    }
49    /// User attribute to order results by. Sort order is ascending by default.
50    /// Sort order is descending if the field
51    /// is prefixed by a negative sign, for example `sort=-name`. Options: `name`,
52    /// `modified_at`, `user_count`.
53    pub fn sort(mut self, value: String) -> Self {
54        self.sort = Some(value);
55        self
56    }
57    /// Direction of sort. Options: `asc`, `desc`.
58    pub fn sort_dir(mut self, value: crate::datadogV2::model::QuerySortOrder) -> Self {
59        self.sort_dir = Some(value);
60        self
61    }
62    /// Filter all users by the given string. Defaults to no filtering.
63    pub fn filter(mut self, value: String) -> Self {
64        self.filter = Some(value);
65        self
66    }
67    /// Filter on status attribute.
68    /// Comma separated list, with possible values `Active`, `Pending`, and `Disabled`.
69    /// Defaults to no filtering.
70    pub fn filter_status(mut self, value: String) -> Self {
71        self.filter_status = Some(value);
72        self
73    }
74}
75
76/// CreateUserError is a struct for typed errors of method [`UsersAPI::create_user`]
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(untagged)]
79pub enum CreateUserError {
80    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
81    UnknownValue(serde_json::Value),
82}
83
84/// DisableUserError is a struct for typed errors of method [`UsersAPI::disable_user`]
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(untagged)]
87pub enum DisableUserError {
88    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
89    UnknownValue(serde_json::Value),
90}
91
92/// GetInvitationError is a struct for typed errors of method [`UsersAPI::get_invitation`]
93#[derive(Debug, Clone, Serialize, Deserialize)]
94#[serde(untagged)]
95pub enum GetInvitationError {
96    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
97    UnknownValue(serde_json::Value),
98}
99
100/// GetUserError is a struct for typed errors of method [`UsersAPI::get_user`]
101#[derive(Debug, Clone, Serialize, Deserialize)]
102#[serde(untagged)]
103pub enum GetUserError {
104    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
105    UnknownValue(serde_json::Value),
106}
107
108/// ListUserOrganizationsError is a struct for typed errors of method [`UsersAPI::list_user_organizations`]
109#[derive(Debug, Clone, Serialize, Deserialize)]
110#[serde(untagged)]
111pub enum ListUserOrganizationsError {
112    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
113    UnknownValue(serde_json::Value),
114}
115
116/// ListUserPermissionsError is a struct for typed errors of method [`UsersAPI::list_user_permissions`]
117#[derive(Debug, Clone, Serialize, Deserialize)]
118#[serde(untagged)]
119pub enum ListUserPermissionsError {
120    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
121    UnknownValue(serde_json::Value),
122}
123
124/// ListUsersError is a struct for typed errors of method [`UsersAPI::list_users`]
125#[derive(Debug, Clone, Serialize, Deserialize)]
126#[serde(untagged)]
127pub enum ListUsersError {
128    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
129    UnknownValue(serde_json::Value),
130}
131
132/// SendInvitationsError is a struct for typed errors of method [`UsersAPI::send_invitations`]
133#[derive(Debug, Clone, Serialize, Deserialize)]
134#[serde(untagged)]
135pub enum SendInvitationsError {
136    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
137    UnknownValue(serde_json::Value),
138}
139
140/// UpdateUserError is a struct for typed errors of method [`UsersAPI::update_user`]
141#[derive(Debug, Clone, Serialize, Deserialize)]
142#[serde(untagged)]
143pub enum UpdateUserError {
144    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
145    UnknownValue(serde_json::Value),
146}
147
148/// Create, edit, and disable users.
149#[derive(Debug, Clone)]
150pub struct UsersAPI {
151    config: datadog::Configuration,
152    client: reqwest_middleware::ClientWithMiddleware,
153}
154
155impl Default for UsersAPI {
156    fn default() -> Self {
157        Self::with_config(datadog::Configuration::default())
158    }
159}
160
161impl UsersAPI {
162    pub fn new() -> Self {
163        Self::default()
164    }
165    pub fn with_config(config: datadog::Configuration) -> Self {
166        let mut reqwest_client_builder = reqwest::Client::builder();
167
168        if let Some(proxy_url) = &config.proxy_url {
169            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
170            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
171        }
172
173        let mut middleware_client_builder =
174            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
175
176        if config.enable_retry {
177            struct RetryableStatus;
178            impl reqwest_retry::RetryableStrategy for RetryableStatus {
179                fn handle(
180                    &self,
181                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
182                ) -> Option<reqwest_retry::Retryable> {
183                    match res {
184                        Ok(success) => reqwest_retry::default_on_request_success(success),
185                        Err(_) => None,
186                    }
187                }
188            }
189            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
190                .build_with_max_retries(config.max_retries);
191
192            let retry_middleware =
193                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
194                    backoff_policy,
195                    RetryableStatus,
196                );
197
198            middleware_client_builder = middleware_client_builder.with(retry_middleware);
199        }
200
201        let client = middleware_client_builder.build();
202
203        Self { config, client }
204    }
205
206    pub fn with_client_and_config(
207        config: datadog::Configuration,
208        client: reqwest_middleware::ClientWithMiddleware,
209    ) -> Self {
210        Self { config, client }
211    }
212
213    /// Create a user for your organization.
214    pub async fn create_user(
215        &self,
216        body: crate::datadogV2::model::UserCreateRequest,
217    ) -> Result<crate::datadogV2::model::UserResponse, datadog::Error<CreateUserError>> {
218        match self.create_user_with_http_info(body).await {
219            Ok(response_content) => {
220                if let Some(e) = response_content.entity {
221                    Ok(e)
222                } else {
223                    Err(datadog::Error::Serde(serde::de::Error::custom(
224                        "response content was None",
225                    )))
226                }
227            }
228            Err(err) => Err(err),
229        }
230    }
231
232    /// Create a user for your organization.
233    pub async fn create_user_with_http_info(
234        &self,
235        body: crate::datadogV2::model::UserCreateRequest,
236    ) -> Result<
237        datadog::ResponseContent<crate::datadogV2::model::UserResponse>,
238        datadog::Error<CreateUserError>,
239    > {
240        let local_configuration = &self.config;
241        let operation_id = "v2.create_user";
242
243        let local_client = &self.client;
244
245        let local_uri_str = format!(
246            "{}/api/v2/users",
247            local_configuration.get_operation_host(operation_id)
248        );
249        let mut local_req_builder =
250            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
251
252        // build headers
253        let mut headers = HeaderMap::new();
254        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
255        headers.insert("Accept", HeaderValue::from_static("application/json"));
256
257        // build user agent
258        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
259            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
260            Err(e) => {
261                log::warn!("Failed to parse user agent header: {e}, falling back to default");
262                headers.insert(
263                    reqwest::header::USER_AGENT,
264                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
265                )
266            }
267        };
268
269        // build auth
270        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
271            headers.insert(
272                "DD-API-KEY",
273                HeaderValue::from_str(local_key.key.as_str())
274                    .expect("failed to parse DD-API-KEY header"),
275            );
276        };
277        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
278            headers.insert(
279                "DD-APPLICATION-KEY",
280                HeaderValue::from_str(local_key.key.as_str())
281                    .expect("failed to parse DD-APPLICATION-KEY header"),
282            );
283        };
284
285        // build body parameters
286        let output = Vec::new();
287        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
288        if body.serialize(&mut ser).is_ok() {
289            if let Some(content_encoding) = headers.get("Content-Encoding") {
290                match content_encoding.to_str().unwrap_or_default() {
291                    "gzip" => {
292                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
293                        let _ = enc.write_all(ser.into_inner().as_slice());
294                        match enc.finish() {
295                            Ok(buf) => {
296                                local_req_builder = local_req_builder.body(buf);
297                            }
298                            Err(e) => return Err(datadog::Error::Io(e)),
299                        }
300                    }
301                    "deflate" => {
302                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
303                        let _ = enc.write_all(ser.into_inner().as_slice());
304                        match enc.finish() {
305                            Ok(buf) => {
306                                local_req_builder = local_req_builder.body(buf);
307                            }
308                            Err(e) => return Err(datadog::Error::Io(e)),
309                        }
310                    }
311                    "zstd1" => {
312                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
313                        let _ = enc.write_all(ser.into_inner().as_slice());
314                        match enc.finish() {
315                            Ok(buf) => {
316                                local_req_builder = local_req_builder.body(buf);
317                            }
318                            Err(e) => return Err(datadog::Error::Io(e)),
319                        }
320                    }
321                    _ => {
322                        local_req_builder = local_req_builder.body(ser.into_inner());
323                    }
324                }
325            } else {
326                local_req_builder = local_req_builder.body(ser.into_inner());
327            }
328        }
329
330        local_req_builder = local_req_builder.headers(headers);
331        let local_req = local_req_builder.build()?;
332        log::debug!("request content: {:?}", local_req.body());
333        let local_resp = local_client.execute(local_req).await?;
334
335        let local_status = local_resp.status();
336        let local_content = local_resp.text().await?;
337        log::debug!("response content: {}", local_content);
338
339        if !local_status.is_client_error() && !local_status.is_server_error() {
340            match serde_json::from_str::<crate::datadogV2::model::UserResponse>(&local_content) {
341                Ok(e) => {
342                    return Ok(datadog::ResponseContent {
343                        status: local_status,
344                        content: local_content,
345                        entity: Some(e),
346                    })
347                }
348                Err(e) => return Err(datadog::Error::Serde(e)),
349            };
350        } else {
351            let local_entity: Option<CreateUserError> = serde_json::from_str(&local_content).ok();
352            let local_error = datadog::ResponseContent {
353                status: local_status,
354                content: local_content,
355                entity: local_entity,
356            };
357            Err(datadog::Error::ResponseError(local_error))
358        }
359    }
360
361    /// Disable a user. Can only be used with an application key belonging
362    /// to an administrator user.
363    pub async fn disable_user(
364        &self,
365        user_id: String,
366    ) -> Result<(), datadog::Error<DisableUserError>> {
367        match self.disable_user_with_http_info(user_id).await {
368            Ok(_) => Ok(()),
369            Err(err) => Err(err),
370        }
371    }
372
373    /// Disable a user. Can only be used with an application key belonging
374    /// to an administrator user.
375    pub async fn disable_user_with_http_info(
376        &self,
377        user_id: String,
378    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DisableUserError>> {
379        let local_configuration = &self.config;
380        let operation_id = "v2.disable_user";
381
382        let local_client = &self.client;
383
384        let local_uri_str = format!(
385            "{}/api/v2/users/{user_id}",
386            local_configuration.get_operation_host(operation_id),
387            user_id = datadog::urlencode(user_id)
388        );
389        let mut local_req_builder =
390            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
391
392        // build headers
393        let mut headers = HeaderMap::new();
394        headers.insert("Accept", HeaderValue::from_static("*/*"));
395
396        // build user agent
397        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
398            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
399            Err(e) => {
400                log::warn!("Failed to parse user agent header: {e}, falling back to default");
401                headers.insert(
402                    reqwest::header::USER_AGENT,
403                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
404                )
405            }
406        };
407
408        // build auth
409        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
410            headers.insert(
411                "DD-API-KEY",
412                HeaderValue::from_str(local_key.key.as_str())
413                    .expect("failed to parse DD-API-KEY header"),
414            );
415        };
416        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
417            headers.insert(
418                "DD-APPLICATION-KEY",
419                HeaderValue::from_str(local_key.key.as_str())
420                    .expect("failed to parse DD-APPLICATION-KEY header"),
421            );
422        };
423
424        local_req_builder = local_req_builder.headers(headers);
425        let local_req = local_req_builder.build()?;
426        log::debug!("request content: {:?}", local_req.body());
427        let local_resp = local_client.execute(local_req).await?;
428
429        let local_status = local_resp.status();
430        let local_content = local_resp.text().await?;
431        log::debug!("response content: {}", local_content);
432
433        if !local_status.is_client_error() && !local_status.is_server_error() {
434            Ok(datadog::ResponseContent {
435                status: local_status,
436                content: local_content,
437                entity: None,
438            })
439        } else {
440            let local_entity: Option<DisableUserError> = serde_json::from_str(&local_content).ok();
441            let local_error = datadog::ResponseContent {
442                status: local_status,
443                content: local_content,
444                entity: local_entity,
445            };
446            Err(datadog::Error::ResponseError(local_error))
447        }
448    }
449
450    /// Returns a single user invitation by its UUID.
451    pub async fn get_invitation(
452        &self,
453        user_invitation_uuid: String,
454    ) -> Result<crate::datadogV2::model::UserInvitationResponse, datadog::Error<GetInvitationError>>
455    {
456        match self
457            .get_invitation_with_http_info(user_invitation_uuid)
458            .await
459        {
460            Ok(response_content) => {
461                if let Some(e) = response_content.entity {
462                    Ok(e)
463                } else {
464                    Err(datadog::Error::Serde(serde::de::Error::custom(
465                        "response content was None",
466                    )))
467                }
468            }
469            Err(err) => Err(err),
470        }
471    }
472
473    /// Returns a single user invitation by its UUID.
474    pub async fn get_invitation_with_http_info(
475        &self,
476        user_invitation_uuid: String,
477    ) -> Result<
478        datadog::ResponseContent<crate::datadogV2::model::UserInvitationResponse>,
479        datadog::Error<GetInvitationError>,
480    > {
481        let local_configuration = &self.config;
482        let operation_id = "v2.get_invitation";
483
484        let local_client = &self.client;
485
486        let local_uri_str = format!(
487            "{}/api/v2/user_invitations/{user_invitation_uuid}",
488            local_configuration.get_operation_host(operation_id),
489            user_invitation_uuid = datadog::urlencode(user_invitation_uuid)
490        );
491        let mut local_req_builder =
492            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
493
494        // build headers
495        let mut headers = HeaderMap::new();
496        headers.insert("Accept", HeaderValue::from_static("application/json"));
497
498        // build user agent
499        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
500            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
501            Err(e) => {
502                log::warn!("Failed to parse user agent header: {e}, falling back to default");
503                headers.insert(
504                    reqwest::header::USER_AGENT,
505                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
506                )
507            }
508        };
509
510        // build auth
511        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
512            headers.insert(
513                "DD-API-KEY",
514                HeaderValue::from_str(local_key.key.as_str())
515                    .expect("failed to parse DD-API-KEY header"),
516            );
517        };
518        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
519            headers.insert(
520                "DD-APPLICATION-KEY",
521                HeaderValue::from_str(local_key.key.as_str())
522                    .expect("failed to parse DD-APPLICATION-KEY header"),
523            );
524        };
525
526        local_req_builder = local_req_builder.headers(headers);
527        let local_req = local_req_builder.build()?;
528        log::debug!("request content: {:?}", local_req.body());
529        let local_resp = local_client.execute(local_req).await?;
530
531        let local_status = local_resp.status();
532        let local_content = local_resp.text().await?;
533        log::debug!("response content: {}", local_content);
534
535        if !local_status.is_client_error() && !local_status.is_server_error() {
536            match serde_json::from_str::<crate::datadogV2::model::UserInvitationResponse>(
537                &local_content,
538            ) {
539                Ok(e) => {
540                    return Ok(datadog::ResponseContent {
541                        status: local_status,
542                        content: local_content,
543                        entity: Some(e),
544                    })
545                }
546                Err(e) => return Err(datadog::Error::Serde(e)),
547            };
548        } else {
549            let local_entity: Option<GetInvitationError> =
550                serde_json::from_str(&local_content).ok();
551            let local_error = datadog::ResponseContent {
552                status: local_status,
553                content: local_content,
554                entity: local_entity,
555            };
556            Err(datadog::Error::ResponseError(local_error))
557        }
558    }
559
560    /// Get a user in the organization specified by the user’s `user_id`.
561    pub async fn get_user(
562        &self,
563        user_id: String,
564    ) -> Result<crate::datadogV2::model::UserResponse, datadog::Error<GetUserError>> {
565        match self.get_user_with_http_info(user_id).await {
566            Ok(response_content) => {
567                if let Some(e) = response_content.entity {
568                    Ok(e)
569                } else {
570                    Err(datadog::Error::Serde(serde::de::Error::custom(
571                        "response content was None",
572                    )))
573                }
574            }
575            Err(err) => Err(err),
576        }
577    }
578
579    /// Get a user in the organization specified by the user’s `user_id`.
580    pub async fn get_user_with_http_info(
581        &self,
582        user_id: String,
583    ) -> Result<
584        datadog::ResponseContent<crate::datadogV2::model::UserResponse>,
585        datadog::Error<GetUserError>,
586    > {
587        let local_configuration = &self.config;
588        let operation_id = "v2.get_user";
589
590        let local_client = &self.client;
591
592        let local_uri_str = format!(
593            "{}/api/v2/users/{user_id}",
594            local_configuration.get_operation_host(operation_id),
595            user_id = datadog::urlencode(user_id)
596        );
597        let mut local_req_builder =
598            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
599
600        // build headers
601        let mut headers = HeaderMap::new();
602        headers.insert("Accept", HeaderValue::from_static("application/json"));
603
604        // build user agent
605        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
606            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
607            Err(e) => {
608                log::warn!("Failed to parse user agent header: {e}, falling back to default");
609                headers.insert(
610                    reqwest::header::USER_AGENT,
611                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
612                )
613            }
614        };
615
616        // build auth
617        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
618            headers.insert(
619                "DD-API-KEY",
620                HeaderValue::from_str(local_key.key.as_str())
621                    .expect("failed to parse DD-API-KEY header"),
622            );
623        };
624        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
625            headers.insert(
626                "DD-APPLICATION-KEY",
627                HeaderValue::from_str(local_key.key.as_str())
628                    .expect("failed to parse DD-APPLICATION-KEY header"),
629            );
630        };
631
632        local_req_builder = local_req_builder.headers(headers);
633        let local_req = local_req_builder.build()?;
634        log::debug!("request content: {:?}", local_req.body());
635        let local_resp = local_client.execute(local_req).await?;
636
637        let local_status = local_resp.status();
638        let local_content = local_resp.text().await?;
639        log::debug!("response content: {}", local_content);
640
641        if !local_status.is_client_error() && !local_status.is_server_error() {
642            match serde_json::from_str::<crate::datadogV2::model::UserResponse>(&local_content) {
643                Ok(e) => {
644                    return Ok(datadog::ResponseContent {
645                        status: local_status,
646                        content: local_content,
647                        entity: Some(e),
648                    })
649                }
650                Err(e) => return Err(datadog::Error::Serde(e)),
651            };
652        } else {
653            let local_entity: Option<GetUserError> = serde_json::from_str(&local_content).ok();
654            let local_error = datadog::ResponseContent {
655                status: local_status,
656                content: local_content,
657                entity: local_entity,
658            };
659            Err(datadog::Error::ResponseError(local_error))
660        }
661    }
662
663    /// Get a user organization. Returns the user information and all organizations
664    /// joined by this user.
665    pub async fn list_user_organizations(
666        &self,
667        user_id: String,
668    ) -> Result<crate::datadogV2::model::UserResponse, datadog::Error<ListUserOrganizationsError>>
669    {
670        match self.list_user_organizations_with_http_info(user_id).await {
671            Ok(response_content) => {
672                if let Some(e) = response_content.entity {
673                    Ok(e)
674                } else {
675                    Err(datadog::Error::Serde(serde::de::Error::custom(
676                        "response content was None",
677                    )))
678                }
679            }
680            Err(err) => Err(err),
681        }
682    }
683
684    /// Get a user organization. Returns the user information and all organizations
685    /// joined by this user.
686    pub async fn list_user_organizations_with_http_info(
687        &self,
688        user_id: String,
689    ) -> Result<
690        datadog::ResponseContent<crate::datadogV2::model::UserResponse>,
691        datadog::Error<ListUserOrganizationsError>,
692    > {
693        let local_configuration = &self.config;
694        let operation_id = "v2.list_user_organizations";
695
696        let local_client = &self.client;
697
698        let local_uri_str = format!(
699            "{}/api/v2/users/{user_id}/orgs",
700            local_configuration.get_operation_host(operation_id),
701            user_id = datadog::urlencode(user_id)
702        );
703        let mut local_req_builder =
704            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
705
706        // build headers
707        let mut headers = HeaderMap::new();
708        headers.insert("Accept", HeaderValue::from_static("application/json"));
709
710        // build user agent
711        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
712            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
713            Err(e) => {
714                log::warn!("Failed to parse user agent header: {e}, falling back to default");
715                headers.insert(
716                    reqwest::header::USER_AGENT,
717                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
718                )
719            }
720        };
721
722        // build auth
723        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
724            headers.insert(
725                "DD-API-KEY",
726                HeaderValue::from_str(local_key.key.as_str())
727                    .expect("failed to parse DD-API-KEY header"),
728            );
729        };
730        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
731            headers.insert(
732                "DD-APPLICATION-KEY",
733                HeaderValue::from_str(local_key.key.as_str())
734                    .expect("failed to parse DD-APPLICATION-KEY header"),
735            );
736        };
737
738        local_req_builder = local_req_builder.headers(headers);
739        let local_req = local_req_builder.build()?;
740        log::debug!("request content: {:?}", local_req.body());
741        let local_resp = local_client.execute(local_req).await?;
742
743        let local_status = local_resp.status();
744        let local_content = local_resp.text().await?;
745        log::debug!("response content: {}", local_content);
746
747        if !local_status.is_client_error() && !local_status.is_server_error() {
748            match serde_json::from_str::<crate::datadogV2::model::UserResponse>(&local_content) {
749                Ok(e) => {
750                    return Ok(datadog::ResponseContent {
751                        status: local_status,
752                        content: local_content,
753                        entity: Some(e),
754                    })
755                }
756                Err(e) => return Err(datadog::Error::Serde(e)),
757            };
758        } else {
759            let local_entity: Option<ListUserOrganizationsError> =
760                serde_json::from_str(&local_content).ok();
761            let local_error = datadog::ResponseContent {
762                status: local_status,
763                content: local_content,
764                entity: local_entity,
765            };
766            Err(datadog::Error::ResponseError(local_error))
767        }
768    }
769
770    /// Get a user permission set. Returns a list of the user’s permissions
771    /// granted by the associated user's roles.
772    pub async fn list_user_permissions(
773        &self,
774        user_id: String,
775    ) -> Result<
776        crate::datadogV2::model::PermissionsResponse,
777        datadog::Error<ListUserPermissionsError>,
778    > {
779        match self.list_user_permissions_with_http_info(user_id).await {
780            Ok(response_content) => {
781                if let Some(e) = response_content.entity {
782                    Ok(e)
783                } else {
784                    Err(datadog::Error::Serde(serde::de::Error::custom(
785                        "response content was None",
786                    )))
787                }
788            }
789            Err(err) => Err(err),
790        }
791    }
792
793    /// Get a user permission set. Returns a list of the user’s permissions
794    /// granted by the associated user's roles.
795    pub async fn list_user_permissions_with_http_info(
796        &self,
797        user_id: String,
798    ) -> Result<
799        datadog::ResponseContent<crate::datadogV2::model::PermissionsResponse>,
800        datadog::Error<ListUserPermissionsError>,
801    > {
802        let local_configuration = &self.config;
803        let operation_id = "v2.list_user_permissions";
804
805        let local_client = &self.client;
806
807        let local_uri_str = format!(
808            "{}/api/v2/users/{user_id}/permissions",
809            local_configuration.get_operation_host(operation_id),
810            user_id = datadog::urlencode(user_id)
811        );
812        let mut local_req_builder =
813            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
814
815        // build headers
816        let mut headers = HeaderMap::new();
817        headers.insert("Accept", HeaderValue::from_static("application/json"));
818
819        // build user agent
820        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
821            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
822            Err(e) => {
823                log::warn!("Failed to parse user agent header: {e}, falling back to default");
824                headers.insert(
825                    reqwest::header::USER_AGENT,
826                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
827                )
828            }
829        };
830
831        // build auth
832        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
833            headers.insert(
834                "DD-API-KEY",
835                HeaderValue::from_str(local_key.key.as_str())
836                    .expect("failed to parse DD-API-KEY header"),
837            );
838        };
839        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
840            headers.insert(
841                "DD-APPLICATION-KEY",
842                HeaderValue::from_str(local_key.key.as_str())
843                    .expect("failed to parse DD-APPLICATION-KEY header"),
844            );
845        };
846
847        local_req_builder = local_req_builder.headers(headers);
848        let local_req = local_req_builder.build()?;
849        log::debug!("request content: {:?}", local_req.body());
850        let local_resp = local_client.execute(local_req).await?;
851
852        let local_status = local_resp.status();
853        let local_content = local_resp.text().await?;
854        log::debug!("response content: {}", local_content);
855
856        if !local_status.is_client_error() && !local_status.is_server_error() {
857            match serde_json::from_str::<crate::datadogV2::model::PermissionsResponse>(
858                &local_content,
859            ) {
860                Ok(e) => {
861                    return Ok(datadog::ResponseContent {
862                        status: local_status,
863                        content: local_content,
864                        entity: Some(e),
865                    })
866                }
867                Err(e) => return Err(datadog::Error::Serde(e)),
868            };
869        } else {
870            let local_entity: Option<ListUserPermissionsError> =
871                serde_json::from_str(&local_content).ok();
872            let local_error = datadog::ResponseContent {
873                status: local_status,
874                content: local_content,
875                entity: local_entity,
876            };
877            Err(datadog::Error::ResponseError(local_error))
878        }
879    }
880
881    /// Get the list of all users in the organization. This list includes
882    /// all users even if they are deactivated or unverified.
883    pub async fn list_users(
884        &self,
885        params: ListUsersOptionalParams,
886    ) -> Result<crate::datadogV2::model::UsersResponse, datadog::Error<ListUsersError>> {
887        match self.list_users_with_http_info(params).await {
888            Ok(response_content) => {
889                if let Some(e) = response_content.entity {
890                    Ok(e)
891                } else {
892                    Err(datadog::Error::Serde(serde::de::Error::custom(
893                        "response content was None",
894                    )))
895                }
896            }
897            Err(err) => Err(err),
898        }
899    }
900
901    pub fn list_users_with_pagination(
902        &self,
903        mut params: ListUsersOptionalParams,
904    ) -> impl Stream<Item = Result<crate::datadogV2::model::User, datadog::Error<ListUsersError>>> + '_
905    {
906        try_stream! {
907            let mut page_size: i64 = 10;
908            if params.page_size.is_none() {
909                params.page_size = Some(page_size);
910            } else {
911                page_size = params.page_size.unwrap().clone();
912            }
913            if params.page_number.is_none() {
914                params.page_number = Some(0);
915            }
916            loop {
917                let resp = self.list_users(params.clone()).await?;
918                let Some(data) = resp.data else { break };
919
920                let r = data;
921                let count = r.len();
922                for team in r {
923                    yield team;
924                }
925
926                if count < page_size as usize {
927                    break;
928                }
929                params.page_number = Some(params.page_number.unwrap() + 1);
930            }
931        }
932    }
933
934    /// Get the list of all users in the organization. This list includes
935    /// all users even if they are deactivated or unverified.
936    pub async fn list_users_with_http_info(
937        &self,
938        params: ListUsersOptionalParams,
939    ) -> Result<
940        datadog::ResponseContent<crate::datadogV2::model::UsersResponse>,
941        datadog::Error<ListUsersError>,
942    > {
943        let local_configuration = &self.config;
944        let operation_id = "v2.list_users";
945
946        // unbox and build optional parameters
947        let page_size = params.page_size;
948        let page_number = params.page_number;
949        let sort = params.sort;
950        let sort_dir = params.sort_dir;
951        let filter = params.filter;
952        let filter_status = params.filter_status;
953
954        let local_client = &self.client;
955
956        let local_uri_str = format!(
957            "{}/api/v2/users",
958            local_configuration.get_operation_host(operation_id)
959        );
960        let mut local_req_builder =
961            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
962
963        if let Some(ref local_query_param) = page_size {
964            local_req_builder =
965                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
966        };
967        if let Some(ref local_query_param) = page_number {
968            local_req_builder =
969                local_req_builder.query(&[("page[number]", &local_query_param.to_string())]);
970        };
971        if let Some(ref local_query_param) = sort {
972            local_req_builder =
973                local_req_builder.query(&[("sort", &local_query_param.to_string())]);
974        };
975        if let Some(ref local_query_param) = sort_dir {
976            local_req_builder =
977                local_req_builder.query(&[("sort_dir", &local_query_param.to_string())]);
978        };
979        if let Some(ref local_query_param) = filter {
980            local_req_builder =
981                local_req_builder.query(&[("filter", &local_query_param.to_string())]);
982        };
983        if let Some(ref local_query_param) = filter_status {
984            local_req_builder =
985                local_req_builder.query(&[("filter[status]", &local_query_param.to_string())]);
986        };
987
988        // build headers
989        let mut headers = HeaderMap::new();
990        headers.insert("Accept", HeaderValue::from_static("application/json"));
991
992        // build user agent
993        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
994            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
995            Err(e) => {
996                log::warn!("Failed to parse user agent header: {e}, falling back to default");
997                headers.insert(
998                    reqwest::header::USER_AGENT,
999                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1000                )
1001            }
1002        };
1003
1004        // build auth
1005        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1006            headers.insert(
1007                "DD-API-KEY",
1008                HeaderValue::from_str(local_key.key.as_str())
1009                    .expect("failed to parse DD-API-KEY header"),
1010            );
1011        };
1012        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1013            headers.insert(
1014                "DD-APPLICATION-KEY",
1015                HeaderValue::from_str(local_key.key.as_str())
1016                    .expect("failed to parse DD-APPLICATION-KEY header"),
1017            );
1018        };
1019
1020        local_req_builder = local_req_builder.headers(headers);
1021        let local_req = local_req_builder.build()?;
1022        log::debug!("request content: {:?}", local_req.body());
1023        let local_resp = local_client.execute(local_req).await?;
1024
1025        let local_status = local_resp.status();
1026        let local_content = local_resp.text().await?;
1027        log::debug!("response content: {}", local_content);
1028
1029        if !local_status.is_client_error() && !local_status.is_server_error() {
1030            match serde_json::from_str::<crate::datadogV2::model::UsersResponse>(&local_content) {
1031                Ok(e) => {
1032                    return Ok(datadog::ResponseContent {
1033                        status: local_status,
1034                        content: local_content,
1035                        entity: Some(e),
1036                    })
1037                }
1038                Err(e) => return Err(datadog::Error::Serde(e)),
1039            };
1040        } else {
1041            let local_entity: Option<ListUsersError> = serde_json::from_str(&local_content).ok();
1042            let local_error = datadog::ResponseContent {
1043                status: local_status,
1044                content: local_content,
1045                entity: local_entity,
1046            };
1047            Err(datadog::Error::ResponseError(local_error))
1048        }
1049    }
1050
1051    /// Sends emails to one or more users inviting them to join the organization.
1052    pub async fn send_invitations(
1053        &self,
1054        body: crate::datadogV2::model::UserInvitationsRequest,
1055    ) -> Result<
1056        crate::datadogV2::model::UserInvitationsResponse,
1057        datadog::Error<SendInvitationsError>,
1058    > {
1059        match self.send_invitations_with_http_info(body).await {
1060            Ok(response_content) => {
1061                if let Some(e) = response_content.entity {
1062                    Ok(e)
1063                } else {
1064                    Err(datadog::Error::Serde(serde::de::Error::custom(
1065                        "response content was None",
1066                    )))
1067                }
1068            }
1069            Err(err) => Err(err),
1070        }
1071    }
1072
1073    /// Sends emails to one or more users inviting them to join the organization.
1074    pub async fn send_invitations_with_http_info(
1075        &self,
1076        body: crate::datadogV2::model::UserInvitationsRequest,
1077    ) -> Result<
1078        datadog::ResponseContent<crate::datadogV2::model::UserInvitationsResponse>,
1079        datadog::Error<SendInvitationsError>,
1080    > {
1081        let local_configuration = &self.config;
1082        let operation_id = "v2.send_invitations";
1083
1084        let local_client = &self.client;
1085
1086        let local_uri_str = format!(
1087            "{}/api/v2/user_invitations",
1088            local_configuration.get_operation_host(operation_id)
1089        );
1090        let mut local_req_builder =
1091            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
1092
1093        // build headers
1094        let mut headers = HeaderMap::new();
1095        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1096        headers.insert("Accept", HeaderValue::from_static("application/json"));
1097
1098        // build user agent
1099        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1100            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1101            Err(e) => {
1102                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1103                headers.insert(
1104                    reqwest::header::USER_AGENT,
1105                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1106                )
1107            }
1108        };
1109
1110        // build auth
1111        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1112            headers.insert(
1113                "DD-API-KEY",
1114                HeaderValue::from_str(local_key.key.as_str())
1115                    .expect("failed to parse DD-API-KEY header"),
1116            );
1117        };
1118        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1119            headers.insert(
1120                "DD-APPLICATION-KEY",
1121                HeaderValue::from_str(local_key.key.as_str())
1122                    .expect("failed to parse DD-APPLICATION-KEY header"),
1123            );
1124        };
1125
1126        // build body parameters
1127        let output = Vec::new();
1128        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1129        if body.serialize(&mut ser).is_ok() {
1130            if let Some(content_encoding) = headers.get("Content-Encoding") {
1131                match content_encoding.to_str().unwrap_or_default() {
1132                    "gzip" => {
1133                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1134                        let _ = enc.write_all(ser.into_inner().as_slice());
1135                        match enc.finish() {
1136                            Ok(buf) => {
1137                                local_req_builder = local_req_builder.body(buf);
1138                            }
1139                            Err(e) => return Err(datadog::Error::Io(e)),
1140                        }
1141                    }
1142                    "deflate" => {
1143                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1144                        let _ = enc.write_all(ser.into_inner().as_slice());
1145                        match enc.finish() {
1146                            Ok(buf) => {
1147                                local_req_builder = local_req_builder.body(buf);
1148                            }
1149                            Err(e) => return Err(datadog::Error::Io(e)),
1150                        }
1151                    }
1152                    "zstd1" => {
1153                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1154                        let _ = enc.write_all(ser.into_inner().as_slice());
1155                        match enc.finish() {
1156                            Ok(buf) => {
1157                                local_req_builder = local_req_builder.body(buf);
1158                            }
1159                            Err(e) => return Err(datadog::Error::Io(e)),
1160                        }
1161                    }
1162                    _ => {
1163                        local_req_builder = local_req_builder.body(ser.into_inner());
1164                    }
1165                }
1166            } else {
1167                local_req_builder = local_req_builder.body(ser.into_inner());
1168            }
1169        }
1170
1171        local_req_builder = local_req_builder.headers(headers);
1172        let local_req = local_req_builder.build()?;
1173        log::debug!("request content: {:?}", local_req.body());
1174        let local_resp = local_client.execute(local_req).await?;
1175
1176        let local_status = local_resp.status();
1177        let local_content = local_resp.text().await?;
1178        log::debug!("response content: {}", local_content);
1179
1180        if !local_status.is_client_error() && !local_status.is_server_error() {
1181            match serde_json::from_str::<crate::datadogV2::model::UserInvitationsResponse>(
1182                &local_content,
1183            ) {
1184                Ok(e) => {
1185                    return Ok(datadog::ResponseContent {
1186                        status: local_status,
1187                        content: local_content,
1188                        entity: Some(e),
1189                    })
1190                }
1191                Err(e) => return Err(datadog::Error::Serde(e)),
1192            };
1193        } else {
1194            let local_entity: Option<SendInvitationsError> =
1195                serde_json::from_str(&local_content).ok();
1196            let local_error = datadog::ResponseContent {
1197                status: local_status,
1198                content: local_content,
1199                entity: local_entity,
1200            };
1201            Err(datadog::Error::ResponseError(local_error))
1202        }
1203    }
1204
1205    /// Edit a user. Can only be used with an application key belonging
1206    /// to an administrator user.
1207    pub async fn update_user(
1208        &self,
1209        user_id: String,
1210        body: crate::datadogV2::model::UserUpdateRequest,
1211    ) -> Result<crate::datadogV2::model::UserResponse, datadog::Error<UpdateUserError>> {
1212        match self.update_user_with_http_info(user_id, body).await {
1213            Ok(response_content) => {
1214                if let Some(e) = response_content.entity {
1215                    Ok(e)
1216                } else {
1217                    Err(datadog::Error::Serde(serde::de::Error::custom(
1218                        "response content was None",
1219                    )))
1220                }
1221            }
1222            Err(err) => Err(err),
1223        }
1224    }
1225
1226    /// Edit a user. Can only be used with an application key belonging
1227    /// to an administrator user.
1228    pub async fn update_user_with_http_info(
1229        &self,
1230        user_id: String,
1231        body: crate::datadogV2::model::UserUpdateRequest,
1232    ) -> Result<
1233        datadog::ResponseContent<crate::datadogV2::model::UserResponse>,
1234        datadog::Error<UpdateUserError>,
1235    > {
1236        let local_configuration = &self.config;
1237        let operation_id = "v2.update_user";
1238
1239        let local_client = &self.client;
1240
1241        let local_uri_str = format!(
1242            "{}/api/v2/users/{user_id}",
1243            local_configuration.get_operation_host(operation_id),
1244            user_id = datadog::urlencode(user_id)
1245        );
1246        let mut local_req_builder =
1247            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
1248
1249        // build headers
1250        let mut headers = HeaderMap::new();
1251        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1252        headers.insert("Accept", HeaderValue::from_static("application/json"));
1253
1254        // build user agent
1255        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1256            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1257            Err(e) => {
1258                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1259                headers.insert(
1260                    reqwest::header::USER_AGENT,
1261                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1262                )
1263            }
1264        };
1265
1266        // build auth
1267        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1268            headers.insert(
1269                "DD-API-KEY",
1270                HeaderValue::from_str(local_key.key.as_str())
1271                    .expect("failed to parse DD-API-KEY header"),
1272            );
1273        };
1274        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1275            headers.insert(
1276                "DD-APPLICATION-KEY",
1277                HeaderValue::from_str(local_key.key.as_str())
1278                    .expect("failed to parse DD-APPLICATION-KEY header"),
1279            );
1280        };
1281
1282        // build body parameters
1283        let output = Vec::new();
1284        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1285        if body.serialize(&mut ser).is_ok() {
1286            if let Some(content_encoding) = headers.get("Content-Encoding") {
1287                match content_encoding.to_str().unwrap_or_default() {
1288                    "gzip" => {
1289                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1290                        let _ = enc.write_all(ser.into_inner().as_slice());
1291                        match enc.finish() {
1292                            Ok(buf) => {
1293                                local_req_builder = local_req_builder.body(buf);
1294                            }
1295                            Err(e) => return Err(datadog::Error::Io(e)),
1296                        }
1297                    }
1298                    "deflate" => {
1299                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1300                        let _ = enc.write_all(ser.into_inner().as_slice());
1301                        match enc.finish() {
1302                            Ok(buf) => {
1303                                local_req_builder = local_req_builder.body(buf);
1304                            }
1305                            Err(e) => return Err(datadog::Error::Io(e)),
1306                        }
1307                    }
1308                    "zstd1" => {
1309                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1310                        let _ = enc.write_all(ser.into_inner().as_slice());
1311                        match enc.finish() {
1312                            Ok(buf) => {
1313                                local_req_builder = local_req_builder.body(buf);
1314                            }
1315                            Err(e) => return Err(datadog::Error::Io(e)),
1316                        }
1317                    }
1318                    _ => {
1319                        local_req_builder = local_req_builder.body(ser.into_inner());
1320                    }
1321                }
1322            } else {
1323                local_req_builder = local_req_builder.body(ser.into_inner());
1324            }
1325        }
1326
1327        local_req_builder = local_req_builder.headers(headers);
1328        let local_req = local_req_builder.build()?;
1329        log::debug!("request content: {:?}", local_req.body());
1330        let local_resp = local_client.execute(local_req).await?;
1331
1332        let local_status = local_resp.status();
1333        let local_content = local_resp.text().await?;
1334        log::debug!("response content: {}", local_content);
1335
1336        if !local_status.is_client_error() && !local_status.is_server_error() {
1337            match serde_json::from_str::<crate::datadogV2::model::UserResponse>(&local_content) {
1338                Ok(e) => {
1339                    return Ok(datadog::ResponseContent {
1340                        status: local_status,
1341                        content: local_content,
1342                        entity: Some(e),
1343                    })
1344                }
1345                Err(e) => return Err(datadog::Error::Serde(e)),
1346            };
1347        } else {
1348            let local_entity: Option<UpdateUserError> = serde_json::from_str(&local_content).ok();
1349            let local_error = datadog::ResponseContent {
1350                status: local_status,
1351                content: local_content,
1352                entity: local_entity,
1353            };
1354            Err(datadog::Error::ResponseError(local_error))
1355        }
1356    }
1357}