datadog_api_client/datadogV2/api/
api_restriction_policies.rs1use 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#[non_exhaustive]
15#[derive(Clone, Default, Debug)]
16pub struct UpdateRestrictionPolicyOptionalParams {
17 pub allow_self_lockout: Option<bool>,
19}
20
21impl UpdateRestrictionPolicyOptionalParams {
22 pub fn allow_self_lockout(mut self, value: bool) -> Self {
24 self.allow_self_lockout = Some(value);
25 self
26 }
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum DeleteRestrictionPolicyError {
33 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34 UnknownValue(serde_json::Value),
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum GetRestrictionPolicyError {
41 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42 UnknownValue(serde_json::Value),
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(untagged)]
48pub enum UpdateRestrictionPolicyError {
49 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
50 UnknownValue(serde_json::Value),
51}
52
53#[derive(Debug, Clone)]
57pub struct RestrictionPoliciesAPI {
58 config: datadog::Configuration,
59 client: reqwest_middleware::ClientWithMiddleware,
60}
61
62impl Default for RestrictionPoliciesAPI {
63 fn default() -> Self {
64 Self::with_config(datadog::Configuration::default())
65 }
66}
67
68impl RestrictionPoliciesAPI {
69 pub fn new() -> Self {
70 Self::default()
71 }
72 pub fn with_config(config: datadog::Configuration) -> Self {
73 let mut reqwest_client_builder = reqwest::Client::builder();
74
75 if let Some(proxy_url) = &config.proxy_url {
76 let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
77 reqwest_client_builder = reqwest_client_builder.proxy(proxy);
78 }
79
80 let mut middleware_client_builder =
81 reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
82
83 if config.enable_retry {
84 struct RetryableStatus;
85 impl reqwest_retry::RetryableStrategy for RetryableStatus {
86 fn handle(
87 &self,
88 res: &Result<reqwest::Response, reqwest_middleware::Error>,
89 ) -> Option<reqwest_retry::Retryable> {
90 match res {
91 Ok(success) => reqwest_retry::default_on_request_success(success),
92 Err(_) => None,
93 }
94 }
95 }
96 let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
97 .build_with_max_retries(config.max_retries);
98
99 let retry_middleware =
100 reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
101 backoff_policy,
102 RetryableStatus,
103 );
104
105 middleware_client_builder = middleware_client_builder.with(retry_middleware);
106 }
107
108 let client = middleware_client_builder.build();
109
110 Self { config, client }
111 }
112
113 pub fn with_client_and_config(
114 config: datadog::Configuration,
115 client: reqwest_middleware::ClientWithMiddleware,
116 ) -> Self {
117 Self { config, client }
118 }
119
120 pub async fn delete_restriction_policy(
122 &self,
123 resource_id: String,
124 ) -> Result<(), datadog::Error<DeleteRestrictionPolicyError>> {
125 match self
126 .delete_restriction_policy_with_http_info(resource_id)
127 .await
128 {
129 Ok(_) => Ok(()),
130 Err(err) => Err(err),
131 }
132 }
133
134 pub async fn delete_restriction_policy_with_http_info(
136 &self,
137 resource_id: String,
138 ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteRestrictionPolicyError>> {
139 let local_configuration = &self.config;
140 let operation_id = "v2.delete_restriction_policy";
141
142 let local_client = &self.client;
143
144 let local_uri_str = format!(
145 "{}/api/v2/restriction_policy/{resource_id}",
146 local_configuration.get_operation_host(operation_id),
147 resource_id = datadog::urlencode(resource_id)
148 );
149 let mut local_req_builder =
150 local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
151
152 let mut headers = HeaderMap::new();
154 headers.insert("Accept", HeaderValue::from_static("*/*"));
155
156 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
158 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
159 Err(e) => {
160 log::warn!("Failed to parse user agent header: {e}, falling back to default");
161 headers.insert(
162 reqwest::header::USER_AGENT,
163 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
164 )
165 }
166 };
167
168 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
170 headers.insert(
171 "DD-API-KEY",
172 HeaderValue::from_str(local_key.key.as_str())
173 .expect("failed to parse DD-API-KEY header"),
174 );
175 };
176 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
177 headers.insert(
178 "DD-APPLICATION-KEY",
179 HeaderValue::from_str(local_key.key.as_str())
180 .expect("failed to parse DD-APPLICATION-KEY header"),
181 );
182 };
183
184 local_req_builder = local_req_builder.headers(headers);
185 let local_req = local_req_builder.build()?;
186 log::debug!("request content: {:?}", local_req.body());
187 let local_resp = local_client.execute(local_req).await?;
188
189 let local_status = local_resp.status();
190 let local_content = local_resp.text().await?;
191 log::debug!("response content: {}", local_content);
192
193 if !local_status.is_client_error() && !local_status.is_server_error() {
194 Ok(datadog::ResponseContent {
195 status: local_status,
196 content: local_content,
197 entity: None,
198 })
199 } else {
200 let local_entity: Option<DeleteRestrictionPolicyError> =
201 serde_json::from_str(&local_content).ok();
202 let local_error = datadog::ResponseContent {
203 status: local_status,
204 content: local_content,
205 entity: local_entity,
206 };
207 Err(datadog::Error::ResponseError(local_error))
208 }
209 }
210
211 pub async fn get_restriction_policy(
213 &self,
214 resource_id: String,
215 ) -> Result<
216 crate::datadogV2::model::RestrictionPolicyResponse,
217 datadog::Error<GetRestrictionPolicyError>,
218 > {
219 match self
220 .get_restriction_policy_with_http_info(resource_id)
221 .await
222 {
223 Ok(response_content) => {
224 if let Some(e) = response_content.entity {
225 Ok(e)
226 } else {
227 Err(datadog::Error::Serde(serde::de::Error::custom(
228 "response content was None",
229 )))
230 }
231 }
232 Err(err) => Err(err),
233 }
234 }
235
236 pub async fn get_restriction_policy_with_http_info(
238 &self,
239 resource_id: String,
240 ) -> Result<
241 datadog::ResponseContent<crate::datadogV2::model::RestrictionPolicyResponse>,
242 datadog::Error<GetRestrictionPolicyError>,
243 > {
244 let local_configuration = &self.config;
245 let operation_id = "v2.get_restriction_policy";
246
247 let local_client = &self.client;
248
249 let local_uri_str = format!(
250 "{}/api/v2/restriction_policy/{resource_id}",
251 local_configuration.get_operation_host(operation_id),
252 resource_id = datadog::urlencode(resource_id)
253 );
254 let mut local_req_builder =
255 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
256
257 let mut headers = HeaderMap::new();
259 headers.insert("Accept", HeaderValue::from_static("application/json"));
260
261 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
263 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
264 Err(e) => {
265 log::warn!("Failed to parse user agent header: {e}, falling back to default");
266 headers.insert(
267 reqwest::header::USER_AGENT,
268 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
269 )
270 }
271 };
272
273 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
275 headers.insert(
276 "DD-API-KEY",
277 HeaderValue::from_str(local_key.key.as_str())
278 .expect("failed to parse DD-API-KEY header"),
279 );
280 };
281 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
282 headers.insert(
283 "DD-APPLICATION-KEY",
284 HeaderValue::from_str(local_key.key.as_str())
285 .expect("failed to parse DD-APPLICATION-KEY header"),
286 );
287 };
288
289 local_req_builder = local_req_builder.headers(headers);
290 let local_req = local_req_builder.build()?;
291 log::debug!("request content: {:?}", local_req.body());
292 let local_resp = local_client.execute(local_req).await?;
293
294 let local_status = local_resp.status();
295 let local_content = local_resp.text().await?;
296 log::debug!("response content: {}", local_content);
297
298 if !local_status.is_client_error() && !local_status.is_server_error() {
299 match serde_json::from_str::<crate::datadogV2::model::RestrictionPolicyResponse>(
300 &local_content,
301 ) {
302 Ok(e) => {
303 return Ok(datadog::ResponseContent {
304 status: local_status,
305 content: local_content,
306 entity: Some(e),
307 })
308 }
309 Err(e) => return Err(datadog::Error::Serde(e)),
310 };
311 } else {
312 let local_entity: Option<GetRestrictionPolicyError> =
313 serde_json::from_str(&local_content).ok();
314 let local_error = datadog::ResponseContent {
315 status: local_status,
316 content: local_content,
317 entity: local_entity,
318 };
319 Err(datadog::Error::ResponseError(local_error))
320 }
321 }
322
323 pub async fn update_restriction_policy(
376 &self,
377 resource_id: String,
378 body: crate::datadogV2::model::RestrictionPolicyUpdateRequest,
379 params: UpdateRestrictionPolicyOptionalParams,
380 ) -> Result<
381 crate::datadogV2::model::RestrictionPolicyResponse,
382 datadog::Error<UpdateRestrictionPolicyError>,
383 > {
384 match self
385 .update_restriction_policy_with_http_info(resource_id, body, params)
386 .await
387 {
388 Ok(response_content) => {
389 if let Some(e) = response_content.entity {
390 Ok(e)
391 } else {
392 Err(datadog::Error::Serde(serde::de::Error::custom(
393 "response content was None",
394 )))
395 }
396 }
397 Err(err) => Err(err),
398 }
399 }
400
401 pub async fn update_restriction_policy_with_http_info(
454 &self,
455 resource_id: String,
456 body: crate::datadogV2::model::RestrictionPolicyUpdateRequest,
457 params: UpdateRestrictionPolicyOptionalParams,
458 ) -> Result<
459 datadog::ResponseContent<crate::datadogV2::model::RestrictionPolicyResponse>,
460 datadog::Error<UpdateRestrictionPolicyError>,
461 > {
462 let local_configuration = &self.config;
463 let operation_id = "v2.update_restriction_policy";
464
465 let allow_self_lockout = params.allow_self_lockout;
467
468 let local_client = &self.client;
469
470 let local_uri_str = format!(
471 "{}/api/v2/restriction_policy/{resource_id}",
472 local_configuration.get_operation_host(operation_id),
473 resource_id = datadog::urlencode(resource_id)
474 );
475 let mut local_req_builder =
476 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
477
478 if let Some(ref local_query_param) = allow_self_lockout {
479 local_req_builder =
480 local_req_builder.query(&[("allow_self_lockout", &local_query_param.to_string())]);
481 };
482
483 let mut headers = HeaderMap::new();
485 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
486 headers.insert("Accept", HeaderValue::from_static("application/json"));
487
488 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
490 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
491 Err(e) => {
492 log::warn!("Failed to parse user agent header: {e}, falling back to default");
493 headers.insert(
494 reqwest::header::USER_AGENT,
495 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
496 )
497 }
498 };
499
500 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
502 headers.insert(
503 "DD-API-KEY",
504 HeaderValue::from_str(local_key.key.as_str())
505 .expect("failed to parse DD-API-KEY header"),
506 );
507 };
508 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
509 headers.insert(
510 "DD-APPLICATION-KEY",
511 HeaderValue::from_str(local_key.key.as_str())
512 .expect("failed to parse DD-APPLICATION-KEY header"),
513 );
514 };
515
516 let output = Vec::new();
518 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
519 if body.serialize(&mut ser).is_ok() {
520 if let Some(content_encoding) = headers.get("Content-Encoding") {
521 match content_encoding.to_str().unwrap_or_default() {
522 "gzip" => {
523 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
524 let _ = enc.write_all(ser.into_inner().as_slice());
525 match enc.finish() {
526 Ok(buf) => {
527 local_req_builder = local_req_builder.body(buf);
528 }
529 Err(e) => return Err(datadog::Error::Io(e)),
530 }
531 }
532 "deflate" => {
533 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
534 let _ = enc.write_all(ser.into_inner().as_slice());
535 match enc.finish() {
536 Ok(buf) => {
537 local_req_builder = local_req_builder.body(buf);
538 }
539 Err(e) => return Err(datadog::Error::Io(e)),
540 }
541 }
542 "zstd1" => {
543 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
544 let _ = enc.write_all(ser.into_inner().as_slice());
545 match enc.finish() {
546 Ok(buf) => {
547 local_req_builder = local_req_builder.body(buf);
548 }
549 Err(e) => return Err(datadog::Error::Io(e)),
550 }
551 }
552 _ => {
553 local_req_builder = local_req_builder.body(ser.into_inner());
554 }
555 }
556 } else {
557 local_req_builder = local_req_builder.body(ser.into_inner());
558 }
559 }
560
561 local_req_builder = local_req_builder.headers(headers);
562 let local_req = local_req_builder.build()?;
563 log::debug!("request content: {:?}", local_req.body());
564 let local_resp = local_client.execute(local_req).await?;
565
566 let local_status = local_resp.status();
567 let local_content = local_resp.text().await?;
568 log::debug!("response content: {}", local_content);
569
570 if !local_status.is_client_error() && !local_status.is_server_error() {
571 match serde_json::from_str::<crate::datadogV2::model::RestrictionPolicyResponse>(
572 &local_content,
573 ) {
574 Ok(e) => {
575 return Ok(datadog::ResponseContent {
576 status: local_status,
577 content: local_content,
578 entity: Some(e),
579 })
580 }
581 Err(e) => return Err(datadog::Error::Serde(e)),
582 };
583 } else {
584 let local_entity: Option<UpdateRestrictionPolicyError> =
585 serde_json::from_str(&local_content).ok();
586 let local_error = datadog::ResponseContent {
587 status: local_status,
588 content: local_content,
589 entity: local_entity,
590 };
591 Err(datadog::Error::ResponseError(local_error))
592 }
593 }
594}