1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum CreateSpansMetricError {
17 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18 UnknownValue(serde_json::Value),
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum DeleteSpansMetricError {
25 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26 UnknownValue(serde_json::Value),
27}
28
29#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum GetSpansMetricError {
33 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34 UnknownValue(serde_json::Value),
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum ListSpansMetricsError {
41 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42 UnknownValue(serde_json::Value),
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(untagged)]
48pub enum UpdateSpansMetricError {
49 APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
50 UnknownValue(serde_json::Value),
51}
52
53#[derive(Debug, Clone)]
55pub struct SpansMetricsAPI {
56 config: datadog::Configuration,
57 client: reqwest_middleware::ClientWithMiddleware,
58}
59
60impl Default for SpansMetricsAPI {
61 fn default() -> Self {
62 Self::with_config(datadog::Configuration::default())
63 }
64}
65
66impl SpansMetricsAPI {
67 pub fn new() -> Self {
68 Self::default()
69 }
70 pub fn with_config(config: datadog::Configuration) -> Self {
71 let mut reqwest_client_builder = reqwest::Client::builder();
72
73 if let Some(proxy_url) = &config.proxy_url {
74 let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
75 reqwest_client_builder = reqwest_client_builder.proxy(proxy);
76 }
77
78 let mut middleware_client_builder =
79 reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
80
81 if config.enable_retry {
82 struct RetryableStatus;
83 impl reqwest_retry::RetryableStrategy for RetryableStatus {
84 fn handle(
85 &self,
86 res: &Result<reqwest::Response, reqwest_middleware::Error>,
87 ) -> Option<reqwest_retry::Retryable> {
88 match res {
89 Ok(success) => reqwest_retry::default_on_request_success(success),
90 Err(_) => None,
91 }
92 }
93 }
94 let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
95 .build_with_max_retries(config.max_retries);
96
97 let retry_middleware =
98 reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
99 backoff_policy,
100 RetryableStatus,
101 );
102
103 middleware_client_builder = middleware_client_builder.with(retry_middleware);
104 }
105
106 let client = middleware_client_builder.build();
107
108 Self { config, client }
109 }
110
111 pub fn with_client_and_config(
112 config: datadog::Configuration,
113 client: reqwest_middleware::ClientWithMiddleware,
114 ) -> Self {
115 Self { config, client }
116 }
117
118 pub async fn create_spans_metric(
121 &self,
122 body: crate::datadogV2::model::SpansMetricCreateRequest,
123 ) -> Result<crate::datadogV2::model::SpansMetricResponse, datadog::Error<CreateSpansMetricError>>
124 {
125 match self.create_spans_metric_with_http_info(body).await {
126 Ok(response_content) => {
127 if let Some(e) = response_content.entity {
128 Ok(e)
129 } else {
130 Err(datadog::Error::Serde(serde::de::Error::custom(
131 "response content was None",
132 )))
133 }
134 }
135 Err(err) => Err(err),
136 }
137 }
138
139 pub async fn create_spans_metric_with_http_info(
142 &self,
143 body: crate::datadogV2::model::SpansMetricCreateRequest,
144 ) -> Result<
145 datadog::ResponseContent<crate::datadogV2::model::SpansMetricResponse>,
146 datadog::Error<CreateSpansMetricError>,
147 > {
148 let local_configuration = &self.config;
149 let operation_id = "v2.create_spans_metric";
150
151 let local_client = &self.client;
152
153 let local_uri_str = format!(
154 "{}/api/v2/apm/config/metrics",
155 local_configuration.get_operation_host(operation_id)
156 );
157 let mut local_req_builder =
158 local_client.request(reqwest::Method::POST, local_uri_str.as_str());
159
160 let mut headers = HeaderMap::new();
162 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
163 headers.insert("Accept", HeaderValue::from_static("application/json"));
164
165 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
167 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
168 Err(e) => {
169 log::warn!("Failed to parse user agent header: {e}, falling back to default");
170 headers.insert(
171 reqwest::header::USER_AGENT,
172 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
173 )
174 }
175 };
176
177 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
179 headers.insert(
180 "DD-API-KEY",
181 HeaderValue::from_str(local_key.key.as_str())
182 .expect("failed to parse DD-API-KEY header"),
183 );
184 };
185 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
186 headers.insert(
187 "DD-APPLICATION-KEY",
188 HeaderValue::from_str(local_key.key.as_str())
189 .expect("failed to parse DD-APPLICATION-KEY header"),
190 );
191 };
192
193 let output = Vec::new();
195 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
196 if body.serialize(&mut ser).is_ok() {
197 if let Some(content_encoding) = headers.get("Content-Encoding") {
198 match content_encoding.to_str().unwrap_or_default() {
199 "gzip" => {
200 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
201 let _ = enc.write_all(ser.into_inner().as_slice());
202 match enc.finish() {
203 Ok(buf) => {
204 local_req_builder = local_req_builder.body(buf);
205 }
206 Err(e) => return Err(datadog::Error::Io(e)),
207 }
208 }
209 "deflate" => {
210 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
211 let _ = enc.write_all(ser.into_inner().as_slice());
212 match enc.finish() {
213 Ok(buf) => {
214 local_req_builder = local_req_builder.body(buf);
215 }
216 Err(e) => return Err(datadog::Error::Io(e)),
217 }
218 }
219 "zstd1" => {
220 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
221 let _ = enc.write_all(ser.into_inner().as_slice());
222 match enc.finish() {
223 Ok(buf) => {
224 local_req_builder = local_req_builder.body(buf);
225 }
226 Err(e) => return Err(datadog::Error::Io(e)),
227 }
228 }
229 _ => {
230 local_req_builder = local_req_builder.body(ser.into_inner());
231 }
232 }
233 } else {
234 local_req_builder = local_req_builder.body(ser.into_inner());
235 }
236 }
237
238 local_req_builder = local_req_builder.headers(headers);
239 let local_req = local_req_builder.build()?;
240 log::debug!("request content: {:?}", local_req.body());
241 let local_resp = local_client.execute(local_req).await?;
242
243 let local_status = local_resp.status();
244 let local_content = local_resp.text().await?;
245 log::debug!("response content: {}", local_content);
246
247 if !local_status.is_client_error() && !local_status.is_server_error() {
248 match serde_json::from_str::<crate::datadogV2::model::SpansMetricResponse>(
249 &local_content,
250 ) {
251 Ok(e) => {
252 return Ok(datadog::ResponseContent {
253 status: local_status,
254 content: local_content,
255 entity: Some(e),
256 })
257 }
258 Err(e) => return Err(datadog::Error::Serde(e)),
259 };
260 } else {
261 let local_entity: Option<CreateSpansMetricError> =
262 serde_json::from_str(&local_content).ok();
263 let local_error = datadog::ResponseContent {
264 status: local_status,
265 content: local_content,
266 entity: local_entity,
267 };
268 Err(datadog::Error::ResponseError(local_error))
269 }
270 }
271
272 pub async fn delete_spans_metric(
274 &self,
275 metric_id: String,
276 ) -> Result<(), datadog::Error<DeleteSpansMetricError>> {
277 match self.delete_spans_metric_with_http_info(metric_id).await {
278 Ok(_) => Ok(()),
279 Err(err) => Err(err),
280 }
281 }
282
283 pub async fn delete_spans_metric_with_http_info(
285 &self,
286 metric_id: String,
287 ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteSpansMetricError>> {
288 let local_configuration = &self.config;
289 let operation_id = "v2.delete_spans_metric";
290
291 let local_client = &self.client;
292
293 let local_uri_str = format!(
294 "{}/api/v2/apm/config/metrics/{metric_id}",
295 local_configuration.get_operation_host(operation_id),
296 metric_id = datadog::urlencode(metric_id)
297 );
298 let mut local_req_builder =
299 local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
300
301 let mut headers = HeaderMap::new();
303 headers.insert("Accept", HeaderValue::from_static("*/*"));
304
305 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
307 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
308 Err(e) => {
309 log::warn!("Failed to parse user agent header: {e}, falling back to default");
310 headers.insert(
311 reqwest::header::USER_AGENT,
312 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
313 )
314 }
315 };
316
317 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
319 headers.insert(
320 "DD-API-KEY",
321 HeaderValue::from_str(local_key.key.as_str())
322 .expect("failed to parse DD-API-KEY header"),
323 );
324 };
325 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
326 headers.insert(
327 "DD-APPLICATION-KEY",
328 HeaderValue::from_str(local_key.key.as_str())
329 .expect("failed to parse DD-APPLICATION-KEY header"),
330 );
331 };
332
333 local_req_builder = local_req_builder.headers(headers);
334 let local_req = local_req_builder.build()?;
335 log::debug!("request content: {:?}", local_req.body());
336 let local_resp = local_client.execute(local_req).await?;
337
338 let local_status = local_resp.status();
339 let local_content = local_resp.text().await?;
340 log::debug!("response content: {}", local_content);
341
342 if !local_status.is_client_error() && !local_status.is_server_error() {
343 Ok(datadog::ResponseContent {
344 status: local_status,
345 content: local_content,
346 entity: None,
347 })
348 } else {
349 let local_entity: Option<DeleteSpansMetricError> =
350 serde_json::from_str(&local_content).ok();
351 let local_error = datadog::ResponseContent {
352 status: local_status,
353 content: local_content,
354 entity: local_entity,
355 };
356 Err(datadog::Error::ResponseError(local_error))
357 }
358 }
359
360 pub async fn get_spans_metric(
362 &self,
363 metric_id: String,
364 ) -> Result<crate::datadogV2::model::SpansMetricResponse, datadog::Error<GetSpansMetricError>>
365 {
366 match self.get_spans_metric_with_http_info(metric_id).await {
367 Ok(response_content) => {
368 if let Some(e) = response_content.entity {
369 Ok(e)
370 } else {
371 Err(datadog::Error::Serde(serde::de::Error::custom(
372 "response content was None",
373 )))
374 }
375 }
376 Err(err) => Err(err),
377 }
378 }
379
380 pub async fn get_spans_metric_with_http_info(
382 &self,
383 metric_id: String,
384 ) -> Result<
385 datadog::ResponseContent<crate::datadogV2::model::SpansMetricResponse>,
386 datadog::Error<GetSpansMetricError>,
387 > {
388 let local_configuration = &self.config;
389 let operation_id = "v2.get_spans_metric";
390
391 let local_client = &self.client;
392
393 let local_uri_str = format!(
394 "{}/api/v2/apm/config/metrics/{metric_id}",
395 local_configuration.get_operation_host(operation_id),
396 metric_id = datadog::urlencode(metric_id)
397 );
398 let mut local_req_builder =
399 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
400
401 let mut headers = HeaderMap::new();
403 headers.insert("Accept", HeaderValue::from_static("application/json"));
404
405 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
407 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
408 Err(e) => {
409 log::warn!("Failed to parse user agent header: {e}, falling back to default");
410 headers.insert(
411 reqwest::header::USER_AGENT,
412 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
413 )
414 }
415 };
416
417 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
419 headers.insert(
420 "DD-API-KEY",
421 HeaderValue::from_str(local_key.key.as_str())
422 .expect("failed to parse DD-API-KEY header"),
423 );
424 };
425 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
426 headers.insert(
427 "DD-APPLICATION-KEY",
428 HeaderValue::from_str(local_key.key.as_str())
429 .expect("failed to parse DD-APPLICATION-KEY header"),
430 );
431 };
432
433 local_req_builder = local_req_builder.headers(headers);
434 let local_req = local_req_builder.build()?;
435 log::debug!("request content: {:?}", local_req.body());
436 let local_resp = local_client.execute(local_req).await?;
437
438 let local_status = local_resp.status();
439 let local_content = local_resp.text().await?;
440 log::debug!("response content: {}", local_content);
441
442 if !local_status.is_client_error() && !local_status.is_server_error() {
443 match serde_json::from_str::<crate::datadogV2::model::SpansMetricResponse>(
444 &local_content,
445 ) {
446 Ok(e) => {
447 return Ok(datadog::ResponseContent {
448 status: local_status,
449 content: local_content,
450 entity: Some(e),
451 })
452 }
453 Err(e) => return Err(datadog::Error::Serde(e)),
454 };
455 } else {
456 let local_entity: Option<GetSpansMetricError> =
457 serde_json::from_str(&local_content).ok();
458 let local_error = datadog::ResponseContent {
459 status: local_status,
460 content: local_content,
461 entity: local_entity,
462 };
463 Err(datadog::Error::ResponseError(local_error))
464 }
465 }
466
467 pub async fn list_spans_metrics(
469 &self,
470 ) -> Result<crate::datadogV2::model::SpansMetricsResponse, datadog::Error<ListSpansMetricsError>>
471 {
472 match self.list_spans_metrics_with_http_info().await {
473 Ok(response_content) => {
474 if let Some(e) = response_content.entity {
475 Ok(e)
476 } else {
477 Err(datadog::Error::Serde(serde::de::Error::custom(
478 "response content was None",
479 )))
480 }
481 }
482 Err(err) => Err(err),
483 }
484 }
485
486 pub async fn list_spans_metrics_with_http_info(
488 &self,
489 ) -> Result<
490 datadog::ResponseContent<crate::datadogV2::model::SpansMetricsResponse>,
491 datadog::Error<ListSpansMetricsError>,
492 > {
493 let local_configuration = &self.config;
494 let operation_id = "v2.list_spans_metrics";
495
496 let local_client = &self.client;
497
498 let local_uri_str = format!(
499 "{}/api/v2/apm/config/metrics",
500 local_configuration.get_operation_host(operation_id)
501 );
502 let mut local_req_builder =
503 local_client.request(reqwest::Method::GET, local_uri_str.as_str());
504
505 let mut headers = HeaderMap::new();
507 headers.insert("Accept", HeaderValue::from_static("application/json"));
508
509 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
511 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
512 Err(e) => {
513 log::warn!("Failed to parse user agent header: {e}, falling back to default");
514 headers.insert(
515 reqwest::header::USER_AGENT,
516 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
517 )
518 }
519 };
520
521 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
523 headers.insert(
524 "DD-API-KEY",
525 HeaderValue::from_str(local_key.key.as_str())
526 .expect("failed to parse DD-API-KEY header"),
527 );
528 };
529 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
530 headers.insert(
531 "DD-APPLICATION-KEY",
532 HeaderValue::from_str(local_key.key.as_str())
533 .expect("failed to parse DD-APPLICATION-KEY header"),
534 );
535 };
536
537 local_req_builder = local_req_builder.headers(headers);
538 let local_req = local_req_builder.build()?;
539 log::debug!("request content: {:?}", local_req.body());
540 let local_resp = local_client.execute(local_req).await?;
541
542 let local_status = local_resp.status();
543 let local_content = local_resp.text().await?;
544 log::debug!("response content: {}", local_content);
545
546 if !local_status.is_client_error() && !local_status.is_server_error() {
547 match serde_json::from_str::<crate::datadogV2::model::SpansMetricsResponse>(
548 &local_content,
549 ) {
550 Ok(e) => {
551 return Ok(datadog::ResponseContent {
552 status: local_status,
553 content: local_content,
554 entity: Some(e),
555 })
556 }
557 Err(e) => return Err(datadog::Error::Serde(e)),
558 };
559 } else {
560 let local_entity: Option<ListSpansMetricsError> =
561 serde_json::from_str(&local_content).ok();
562 let local_error = datadog::ResponseContent {
563 status: local_status,
564 content: local_content,
565 entity: local_entity,
566 };
567 Err(datadog::Error::ResponseError(local_error))
568 }
569 }
570
571 pub async fn update_spans_metric(
574 &self,
575 metric_id: String,
576 body: crate::datadogV2::model::SpansMetricUpdateRequest,
577 ) -> Result<crate::datadogV2::model::SpansMetricResponse, datadog::Error<UpdateSpansMetricError>>
578 {
579 match self
580 .update_spans_metric_with_http_info(metric_id, body)
581 .await
582 {
583 Ok(response_content) => {
584 if let Some(e) = response_content.entity {
585 Ok(e)
586 } else {
587 Err(datadog::Error::Serde(serde::de::Error::custom(
588 "response content was None",
589 )))
590 }
591 }
592 Err(err) => Err(err),
593 }
594 }
595
596 pub async fn update_spans_metric_with_http_info(
599 &self,
600 metric_id: String,
601 body: crate::datadogV2::model::SpansMetricUpdateRequest,
602 ) -> Result<
603 datadog::ResponseContent<crate::datadogV2::model::SpansMetricResponse>,
604 datadog::Error<UpdateSpansMetricError>,
605 > {
606 let local_configuration = &self.config;
607 let operation_id = "v2.update_spans_metric";
608
609 let local_client = &self.client;
610
611 let local_uri_str = format!(
612 "{}/api/v2/apm/config/metrics/{metric_id}",
613 local_configuration.get_operation_host(operation_id),
614 metric_id = datadog::urlencode(metric_id)
615 );
616 let mut local_req_builder =
617 local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
618
619 let mut headers = HeaderMap::new();
621 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
622 headers.insert("Accept", HeaderValue::from_static("application/json"));
623
624 match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
626 Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
627 Err(e) => {
628 log::warn!("Failed to parse user agent header: {e}, falling back to default");
629 headers.insert(
630 reqwest::header::USER_AGENT,
631 HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
632 )
633 }
634 };
635
636 if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
638 headers.insert(
639 "DD-API-KEY",
640 HeaderValue::from_str(local_key.key.as_str())
641 .expect("failed to parse DD-API-KEY header"),
642 );
643 };
644 if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
645 headers.insert(
646 "DD-APPLICATION-KEY",
647 HeaderValue::from_str(local_key.key.as_str())
648 .expect("failed to parse DD-APPLICATION-KEY header"),
649 );
650 };
651
652 let output = Vec::new();
654 let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
655 if body.serialize(&mut ser).is_ok() {
656 if let Some(content_encoding) = headers.get("Content-Encoding") {
657 match content_encoding.to_str().unwrap_or_default() {
658 "gzip" => {
659 let mut enc = GzEncoder::new(Vec::new(), Compression::default());
660 let _ = enc.write_all(ser.into_inner().as_slice());
661 match enc.finish() {
662 Ok(buf) => {
663 local_req_builder = local_req_builder.body(buf);
664 }
665 Err(e) => return Err(datadog::Error::Io(e)),
666 }
667 }
668 "deflate" => {
669 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
670 let _ = enc.write_all(ser.into_inner().as_slice());
671 match enc.finish() {
672 Ok(buf) => {
673 local_req_builder = local_req_builder.body(buf);
674 }
675 Err(e) => return Err(datadog::Error::Io(e)),
676 }
677 }
678 "zstd1" => {
679 let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
680 let _ = enc.write_all(ser.into_inner().as_slice());
681 match enc.finish() {
682 Ok(buf) => {
683 local_req_builder = local_req_builder.body(buf);
684 }
685 Err(e) => return Err(datadog::Error::Io(e)),
686 }
687 }
688 _ => {
689 local_req_builder = local_req_builder.body(ser.into_inner());
690 }
691 }
692 } else {
693 local_req_builder = local_req_builder.body(ser.into_inner());
694 }
695 }
696
697 local_req_builder = local_req_builder.headers(headers);
698 let local_req = local_req_builder.build()?;
699 log::debug!("request content: {:?}", local_req.body());
700 let local_resp = local_client.execute(local_req).await?;
701
702 let local_status = local_resp.status();
703 let local_content = local_resp.text().await?;
704 log::debug!("response content: {}", local_content);
705
706 if !local_status.is_client_error() && !local_status.is_server_error() {
707 match serde_json::from_str::<crate::datadogV2::model::SpansMetricResponse>(
708 &local_content,
709 ) {
710 Ok(e) => {
711 return Ok(datadog::ResponseContent {
712 status: local_status,
713 content: local_content,
714 entity: Some(e),
715 })
716 }
717 Err(e) => return Err(datadog::Error::Serde(e)),
718 };
719 } else {
720 let local_entity: Option<UpdateSpansMetricError> =
721 serde_json::from_str(&local_content).ok();
722 let local_error = datadog::ResponseContent {
723 status: local_status,
724 content: local_content,
725 entity: local_entity,
726 };
727 Err(datadog::Error::ResponseError(local_error))
728 }
729 }
730}