datadog_api_client/datadogV2/api/
api_ci_visibility_pipelines.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/// ListCIAppPipelineEventsOptionalParams is a struct for passing parameters to the method [`CIVisibilityPipelinesAPI::list_ci_app_pipeline_events`]
16#[non_exhaustive]
17#[derive(Clone, Default, Debug)]
18pub struct ListCIAppPipelineEventsOptionalParams {
19    /// Search query following log syntax.
20    pub filter_query: Option<String>,
21    /// Minimum timestamp for requested events.
22    pub filter_from: Option<chrono::DateTime<chrono::Utc>>,
23    /// Maximum timestamp for requested events.
24    pub filter_to: Option<chrono::DateTime<chrono::Utc>>,
25    /// Order of events in results.
26    pub sort: Option<crate::datadogV2::model::CIAppSort>,
27    /// List following results with a cursor provided in the previous query.
28    pub page_cursor: Option<String>,
29    /// Maximum number of events in the response.
30    pub page_limit: Option<i32>,
31}
32
33impl ListCIAppPipelineEventsOptionalParams {
34    /// Search query following log syntax.
35    pub fn filter_query(mut self, value: String) -> Self {
36        self.filter_query = Some(value);
37        self
38    }
39    /// Minimum timestamp for requested events.
40    pub fn filter_from(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
41        self.filter_from = Some(value);
42        self
43    }
44    /// Maximum timestamp for requested events.
45    pub fn filter_to(mut self, value: chrono::DateTime<chrono::Utc>) -> Self {
46        self.filter_to = Some(value);
47        self
48    }
49    /// Order of events in results.
50    pub fn sort(mut self, value: crate::datadogV2::model::CIAppSort) -> Self {
51        self.sort = Some(value);
52        self
53    }
54    /// List following results with a cursor provided in the previous query.
55    pub fn page_cursor(mut self, value: String) -> Self {
56        self.page_cursor = Some(value);
57        self
58    }
59    /// Maximum number of events in the response.
60    pub fn page_limit(mut self, value: i32) -> Self {
61        self.page_limit = Some(value);
62        self
63    }
64}
65
66/// SearchCIAppPipelineEventsOptionalParams is a struct for passing parameters to the method [`CIVisibilityPipelinesAPI::search_ci_app_pipeline_events`]
67#[non_exhaustive]
68#[derive(Clone, Default, Debug)]
69pub struct SearchCIAppPipelineEventsOptionalParams {
70    pub body: Option<crate::datadogV2::model::CIAppPipelineEventsRequest>,
71}
72
73impl SearchCIAppPipelineEventsOptionalParams {
74    pub fn body(mut self, value: crate::datadogV2::model::CIAppPipelineEventsRequest) -> Self {
75        self.body = Some(value);
76        self
77    }
78}
79
80/// AggregateCIAppPipelineEventsError is a struct for typed errors of method [`CIVisibilityPipelinesAPI::aggregate_ci_app_pipeline_events`]
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(untagged)]
83pub enum AggregateCIAppPipelineEventsError {
84    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
85    UnknownValue(serde_json::Value),
86}
87
88/// CreateCIAppPipelineEventError is a struct for typed errors of method [`CIVisibilityPipelinesAPI::create_ci_app_pipeline_event`]
89#[derive(Debug, Clone, Serialize, Deserialize)]
90#[serde(untagged)]
91pub enum CreateCIAppPipelineEventError {
92    HTTPCIAppErrors(crate::datadogV2::model::HTTPCIAppErrors),
93    UnknownValue(serde_json::Value),
94}
95
96/// ListCIAppPipelineEventsError is a struct for typed errors of method [`CIVisibilityPipelinesAPI::list_ci_app_pipeline_events`]
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(untagged)]
99pub enum ListCIAppPipelineEventsError {
100    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
101    UnknownValue(serde_json::Value),
102}
103
104/// SearchCIAppPipelineEventsError is a struct for typed errors of method [`CIVisibilityPipelinesAPI::search_ci_app_pipeline_events`]
105#[derive(Debug, Clone, Serialize, Deserialize)]
106#[serde(untagged)]
107pub enum SearchCIAppPipelineEventsError {
108    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
109    UnknownValue(serde_json::Value),
110}
111
112/// Search or aggregate your CI Visibility pipeline events and send them to your Datadog site over HTTP. See the [CI Pipeline Visibility in Datadog page](<https://docs.datadoghq.com/continuous_integration/pipelines/>) for more information.
113#[derive(Debug, Clone)]
114pub struct CIVisibilityPipelinesAPI {
115    config: datadog::Configuration,
116    client: reqwest_middleware::ClientWithMiddleware,
117}
118
119impl Default for CIVisibilityPipelinesAPI {
120    fn default() -> Self {
121        Self::with_config(datadog::Configuration::default())
122    }
123}
124
125impl CIVisibilityPipelinesAPI {
126    pub fn new() -> Self {
127        Self::default()
128    }
129    pub fn with_config(config: datadog::Configuration) -> Self {
130        let mut reqwest_client_builder = reqwest::Client::builder();
131
132        if let Some(proxy_url) = &config.proxy_url {
133            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
134            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
135        }
136
137        let mut middleware_client_builder =
138            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
139
140        if config.enable_retry {
141            struct RetryableStatus;
142            impl reqwest_retry::RetryableStrategy for RetryableStatus {
143                fn handle(
144                    &self,
145                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
146                ) -> Option<reqwest_retry::Retryable> {
147                    match res {
148                        Ok(success) => reqwest_retry::default_on_request_success(success),
149                        Err(_) => None,
150                    }
151                }
152            }
153            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
154                .build_with_max_retries(config.max_retries);
155
156            let retry_middleware =
157                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
158                    backoff_policy,
159                    RetryableStatus,
160                );
161
162            middleware_client_builder = middleware_client_builder.with(retry_middleware);
163        }
164
165        let client = middleware_client_builder.build();
166
167        Self { config, client }
168    }
169
170    pub fn with_client_and_config(
171        config: datadog::Configuration,
172        client: reqwest_middleware::ClientWithMiddleware,
173    ) -> Self {
174        Self { config, client }
175    }
176
177    /// Use this API endpoint to aggregate CI Visibility pipeline events into buckets of computed metrics and timeseries.
178    pub async fn aggregate_ci_app_pipeline_events(
179        &self,
180        body: crate::datadogV2::model::CIAppPipelinesAggregateRequest,
181    ) -> Result<
182        crate::datadogV2::model::CIAppPipelinesAnalyticsAggregateResponse,
183        datadog::Error<AggregateCIAppPipelineEventsError>,
184    > {
185        match self
186            .aggregate_ci_app_pipeline_events_with_http_info(body)
187            .await
188        {
189            Ok(response_content) => {
190                if let Some(e) = response_content.entity {
191                    Ok(e)
192                } else {
193                    Err(datadog::Error::Serde(serde::de::Error::custom(
194                        "response content was None",
195                    )))
196                }
197            }
198            Err(err) => Err(err),
199        }
200    }
201
202    /// Use this API endpoint to aggregate CI Visibility pipeline events into buckets of computed metrics and timeseries.
203    pub async fn aggregate_ci_app_pipeline_events_with_http_info(
204        &self,
205        body: crate::datadogV2::model::CIAppPipelinesAggregateRequest,
206    ) -> Result<
207        datadog::ResponseContent<crate::datadogV2::model::CIAppPipelinesAnalyticsAggregateResponse>,
208        datadog::Error<AggregateCIAppPipelineEventsError>,
209    > {
210        let local_configuration = &self.config;
211        let operation_id = "v2.aggregate_ci_app_pipeline_events";
212
213        let local_client = &self.client;
214
215        let local_uri_str = format!(
216            "{}/api/v2/ci/pipelines/analytics/aggregate",
217            local_configuration.get_operation_host(operation_id)
218        );
219        let mut local_req_builder =
220            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
221
222        // build headers
223        let mut headers = HeaderMap::new();
224        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
225        headers.insert("Accept", HeaderValue::from_static("application/json"));
226
227        // build user agent
228        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
229            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
230            Err(e) => {
231                log::warn!("Failed to parse user agent header: {e}, falling back to default");
232                headers.insert(
233                    reqwest::header::USER_AGENT,
234                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
235                )
236            }
237        };
238
239        // build auth
240        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
241            headers.insert(
242                "DD-API-KEY",
243                HeaderValue::from_str(local_key.key.as_str())
244                    .expect("failed to parse DD-API-KEY header"),
245            );
246        };
247        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
248            headers.insert(
249                "DD-APPLICATION-KEY",
250                HeaderValue::from_str(local_key.key.as_str())
251                    .expect("failed to parse DD-APPLICATION-KEY header"),
252            );
253        };
254
255        // build body parameters
256        let output = Vec::new();
257        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
258        if body.serialize(&mut ser).is_ok() {
259            if let Some(content_encoding) = headers.get("Content-Encoding") {
260                match content_encoding.to_str().unwrap_or_default() {
261                    "gzip" => {
262                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
263                        let _ = enc.write_all(ser.into_inner().as_slice());
264                        match enc.finish() {
265                            Ok(buf) => {
266                                local_req_builder = local_req_builder.body(buf);
267                            }
268                            Err(e) => return Err(datadog::Error::Io(e)),
269                        }
270                    }
271                    "deflate" => {
272                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
273                        let _ = enc.write_all(ser.into_inner().as_slice());
274                        match enc.finish() {
275                            Ok(buf) => {
276                                local_req_builder = local_req_builder.body(buf);
277                            }
278                            Err(e) => return Err(datadog::Error::Io(e)),
279                        }
280                    }
281                    "zstd1" => {
282                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
283                        let _ = enc.write_all(ser.into_inner().as_slice());
284                        match enc.finish() {
285                            Ok(buf) => {
286                                local_req_builder = local_req_builder.body(buf);
287                            }
288                            Err(e) => return Err(datadog::Error::Io(e)),
289                        }
290                    }
291                    _ => {
292                        local_req_builder = local_req_builder.body(ser.into_inner());
293                    }
294                }
295            } else {
296                local_req_builder = local_req_builder.body(ser.into_inner());
297            }
298        }
299
300        local_req_builder = local_req_builder.headers(headers);
301        let local_req = local_req_builder.build()?;
302        log::debug!("request content: {:?}", local_req.body());
303        let local_resp = local_client.execute(local_req).await?;
304
305        let local_status = local_resp.status();
306        let local_content = local_resp.text().await?;
307        log::debug!("response content: {}", local_content);
308
309        if !local_status.is_client_error() && !local_status.is_server_error() {
310            match serde_json::from_str::<
311                crate::datadogV2::model::CIAppPipelinesAnalyticsAggregateResponse,
312            >(&local_content)
313            {
314                Ok(e) => {
315                    return Ok(datadog::ResponseContent {
316                        status: local_status,
317                        content: local_content,
318                        entity: Some(e),
319                    })
320                }
321                Err(e) => return Err(datadog::Error::Serde(e)),
322            };
323        } else {
324            let local_entity: Option<AggregateCIAppPipelineEventsError> =
325                serde_json::from_str(&local_content).ok();
326            let local_error = datadog::ResponseContent {
327                status: local_status,
328                content: local_content,
329                entity: local_entity,
330            };
331            Err(datadog::Error::ResponseError(local_error))
332        }
333    }
334
335    /// Send your pipeline event to your Datadog platform over HTTP. For details about how pipeline executions are modeled and what execution types we support, see [Pipeline Data Model And Execution Types](<https://docs.datadoghq.com/continuous_integration/guides/pipeline_data_model/>).
336    ///
337    /// Pipeline events can be submitted with a timestamp that is up to 18 hours in the past.
338    pub async fn create_ci_app_pipeline_event(
339        &self,
340        body: crate::datadogV2::model::CIAppCreatePipelineEventRequest,
341    ) -> Result<
342        std::collections::BTreeMap<String, serde_json::Value>,
343        datadog::Error<CreateCIAppPipelineEventError>,
344    > {
345        match self.create_ci_app_pipeline_event_with_http_info(body).await {
346            Ok(response_content) => {
347                if let Some(e) = response_content.entity {
348                    Ok(e)
349                } else {
350                    Err(datadog::Error::Serde(serde::de::Error::custom(
351                        "response content was None",
352                    )))
353                }
354            }
355            Err(err) => Err(err),
356        }
357    }
358
359    /// Send your pipeline event to your Datadog platform over HTTP. For details about how pipeline executions are modeled and what execution types we support, see [Pipeline Data Model And Execution Types](<https://docs.datadoghq.com/continuous_integration/guides/pipeline_data_model/>).
360    ///
361    /// Pipeline events can be submitted with a timestamp that is up to 18 hours in the past.
362    pub async fn create_ci_app_pipeline_event_with_http_info(
363        &self,
364        body: crate::datadogV2::model::CIAppCreatePipelineEventRequest,
365    ) -> Result<
366        datadog::ResponseContent<std::collections::BTreeMap<String, serde_json::Value>>,
367        datadog::Error<CreateCIAppPipelineEventError>,
368    > {
369        let local_configuration = &self.config;
370        let operation_id = "v2.create_ci_app_pipeline_event";
371
372        let local_client = &self.client;
373
374        let local_uri_str = format!(
375            "{}/api/v2/ci/pipeline",
376            local_configuration.get_operation_host(operation_id)
377        );
378        let mut local_req_builder =
379            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
380
381        // build headers
382        let mut headers = HeaderMap::new();
383        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
384        headers.insert("Accept", HeaderValue::from_static("application/json"));
385
386        // build user agent
387        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
388            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
389            Err(e) => {
390                log::warn!("Failed to parse user agent header: {e}, falling back to default");
391                headers.insert(
392                    reqwest::header::USER_AGENT,
393                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
394                )
395            }
396        };
397
398        // build auth
399        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
400            headers.insert(
401                "DD-API-KEY",
402                HeaderValue::from_str(local_key.key.as_str())
403                    .expect("failed to parse DD-API-KEY header"),
404            );
405        };
406
407        // build body parameters
408        let output = Vec::new();
409        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
410        if body.serialize(&mut ser).is_ok() {
411            if let Some(content_encoding) = headers.get("Content-Encoding") {
412                match content_encoding.to_str().unwrap_or_default() {
413                    "gzip" => {
414                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
415                        let _ = enc.write_all(ser.into_inner().as_slice());
416                        match enc.finish() {
417                            Ok(buf) => {
418                                local_req_builder = local_req_builder.body(buf);
419                            }
420                            Err(e) => return Err(datadog::Error::Io(e)),
421                        }
422                    }
423                    "deflate" => {
424                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
425                        let _ = enc.write_all(ser.into_inner().as_slice());
426                        match enc.finish() {
427                            Ok(buf) => {
428                                local_req_builder = local_req_builder.body(buf);
429                            }
430                            Err(e) => return Err(datadog::Error::Io(e)),
431                        }
432                    }
433                    "zstd1" => {
434                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
435                        let _ = enc.write_all(ser.into_inner().as_slice());
436                        match enc.finish() {
437                            Ok(buf) => {
438                                local_req_builder = local_req_builder.body(buf);
439                            }
440                            Err(e) => return Err(datadog::Error::Io(e)),
441                        }
442                    }
443                    _ => {
444                        local_req_builder = local_req_builder.body(ser.into_inner());
445                    }
446                }
447            } else {
448                local_req_builder = local_req_builder.body(ser.into_inner());
449            }
450        }
451
452        local_req_builder = local_req_builder.headers(headers);
453        let local_req = local_req_builder.build()?;
454        log::debug!("request content: {:?}", local_req.body());
455        let local_resp = local_client.execute(local_req).await?;
456
457        let local_status = local_resp.status();
458        let local_content = local_resp.text().await?;
459        log::debug!("response content: {}", local_content);
460
461        if !local_status.is_client_error() && !local_status.is_server_error() {
462            match serde_json::from_str::<std::collections::BTreeMap<String, serde_json::Value>>(
463                &local_content,
464            ) {
465                Ok(e) => {
466                    return Ok(datadog::ResponseContent {
467                        status: local_status,
468                        content: local_content,
469                        entity: Some(e),
470                    })
471                }
472                Err(e) => return Err(datadog::Error::Serde(e)),
473            };
474        } else {
475            let local_entity: Option<CreateCIAppPipelineEventError> =
476                serde_json::from_str(&local_content).ok();
477            let local_error = datadog::ResponseContent {
478                status: local_status,
479                content: local_content,
480                entity: local_entity,
481            };
482            Err(datadog::Error::ResponseError(local_error))
483        }
484    }
485
486    /// List endpoint returns CI Visibility pipeline events that match a [search query](<https://docs.datadoghq.com/continuous_integration/explorer/search_syntax/>).
487    /// [Results are paginated similarly to logs](<https://docs.datadoghq.com/logs/guide/collect-multiple-logs-with-pagination>).
488    ///
489    /// Use this endpoint to see your latest pipeline events.
490    pub async fn list_ci_app_pipeline_events(
491        &self,
492        params: ListCIAppPipelineEventsOptionalParams,
493    ) -> Result<
494        crate::datadogV2::model::CIAppPipelineEventsResponse,
495        datadog::Error<ListCIAppPipelineEventsError>,
496    > {
497        match self
498            .list_ci_app_pipeline_events_with_http_info(params)
499            .await
500        {
501            Ok(response_content) => {
502                if let Some(e) = response_content.entity {
503                    Ok(e)
504                } else {
505                    Err(datadog::Error::Serde(serde::de::Error::custom(
506                        "response content was None",
507                    )))
508                }
509            }
510            Err(err) => Err(err),
511        }
512    }
513
514    pub fn list_ci_app_pipeline_events_with_pagination(
515        &self,
516        mut params: ListCIAppPipelineEventsOptionalParams,
517    ) -> impl Stream<
518        Item = Result<
519            crate::datadogV2::model::CIAppPipelineEvent,
520            datadog::Error<ListCIAppPipelineEventsError>,
521        >,
522    > + '_ {
523        try_stream! {
524            let mut page_size: i32 = 10;
525            if params.page_limit.is_none() {
526                params.page_limit = Some(page_size);
527            } else {
528                page_size = params.page_limit.unwrap().clone();
529            }
530            loop {
531                let resp = self.list_ci_app_pipeline_events(params.clone()).await?;
532                let Some(data) = resp.data else { break };
533
534                let r = data;
535                let count = r.len();
536                for team in r {
537                    yield team;
538                }
539
540                if count < page_size as usize {
541                    break;
542                }
543                let Some(meta) = resp.meta else { break };
544                let Some(page) = meta.page else { break };
545                let Some(after) = page.after else { break };
546
547                params.page_cursor = Some(after);
548            }
549        }
550    }
551
552    /// List endpoint returns CI Visibility pipeline events that match a [search query](<https://docs.datadoghq.com/continuous_integration/explorer/search_syntax/>).
553    /// [Results are paginated similarly to logs](<https://docs.datadoghq.com/logs/guide/collect-multiple-logs-with-pagination>).
554    ///
555    /// Use this endpoint to see your latest pipeline events.
556    pub async fn list_ci_app_pipeline_events_with_http_info(
557        &self,
558        params: ListCIAppPipelineEventsOptionalParams,
559    ) -> Result<
560        datadog::ResponseContent<crate::datadogV2::model::CIAppPipelineEventsResponse>,
561        datadog::Error<ListCIAppPipelineEventsError>,
562    > {
563        let local_configuration = &self.config;
564        let operation_id = "v2.list_ci_app_pipeline_events";
565
566        // unbox and build optional parameters
567        let filter_query = params.filter_query;
568        let filter_from = params.filter_from;
569        let filter_to = params.filter_to;
570        let sort = params.sort;
571        let page_cursor = params.page_cursor;
572        let page_limit = params.page_limit;
573
574        let local_client = &self.client;
575
576        let local_uri_str = format!(
577            "{}/api/v2/ci/pipelines/events",
578            local_configuration.get_operation_host(operation_id)
579        );
580        let mut local_req_builder =
581            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
582
583        if let Some(ref local_query_param) = filter_query {
584            local_req_builder =
585                local_req_builder.query(&[("filter[query]", &local_query_param.to_string())]);
586        };
587        if let Some(ref local_query_param) = filter_from {
588            local_req_builder = local_req_builder.query(&[(
589                "filter[from]",
590                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
591            )]);
592        };
593        if let Some(ref local_query_param) = filter_to {
594            local_req_builder = local_req_builder.query(&[(
595                "filter[to]",
596                &local_query_param.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
597            )]);
598        };
599        if let Some(ref local_query_param) = sort {
600            local_req_builder =
601                local_req_builder.query(&[("sort", &local_query_param.to_string())]);
602        };
603        if let Some(ref local_query_param) = page_cursor {
604            local_req_builder =
605                local_req_builder.query(&[("page[cursor]", &local_query_param.to_string())]);
606        };
607        if let Some(ref local_query_param) = page_limit {
608            local_req_builder =
609                local_req_builder.query(&[("page[limit]", &local_query_param.to_string())]);
610        };
611
612        // build headers
613        let mut headers = HeaderMap::new();
614        headers.insert("Accept", HeaderValue::from_static("application/json"));
615
616        // build user agent
617        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
618            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
619            Err(e) => {
620                log::warn!("Failed to parse user agent header: {e}, falling back to default");
621                headers.insert(
622                    reqwest::header::USER_AGENT,
623                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
624                )
625            }
626        };
627
628        // build auth
629        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
630            headers.insert(
631                "DD-API-KEY",
632                HeaderValue::from_str(local_key.key.as_str())
633                    .expect("failed to parse DD-API-KEY header"),
634            );
635        };
636        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
637            headers.insert(
638                "DD-APPLICATION-KEY",
639                HeaderValue::from_str(local_key.key.as_str())
640                    .expect("failed to parse DD-APPLICATION-KEY header"),
641            );
642        };
643
644        local_req_builder = local_req_builder.headers(headers);
645        let local_req = local_req_builder.build()?;
646        log::debug!("request content: {:?}", local_req.body());
647        let local_resp = local_client.execute(local_req).await?;
648
649        let local_status = local_resp.status();
650        let local_content = local_resp.text().await?;
651        log::debug!("response content: {}", local_content);
652
653        if !local_status.is_client_error() && !local_status.is_server_error() {
654            match serde_json::from_str::<crate::datadogV2::model::CIAppPipelineEventsResponse>(
655                &local_content,
656            ) {
657                Ok(e) => {
658                    return Ok(datadog::ResponseContent {
659                        status: local_status,
660                        content: local_content,
661                        entity: Some(e),
662                    })
663                }
664                Err(e) => return Err(datadog::Error::Serde(e)),
665            };
666        } else {
667            let local_entity: Option<ListCIAppPipelineEventsError> =
668                serde_json::from_str(&local_content).ok();
669            let local_error = datadog::ResponseContent {
670                status: local_status,
671                content: local_content,
672                entity: local_entity,
673            };
674            Err(datadog::Error::ResponseError(local_error))
675        }
676    }
677
678    /// List endpoint returns CI Visibility pipeline events that match a [search query](<https://docs.datadoghq.com/continuous_integration/explorer/search_syntax/>).
679    /// [Results are paginated similarly to logs](<https://docs.datadoghq.com/logs/guide/collect-multiple-logs-with-pagination>).
680    ///
681    /// Use this endpoint to build complex events filtering and search.
682    pub async fn search_ci_app_pipeline_events(
683        &self,
684        params: SearchCIAppPipelineEventsOptionalParams,
685    ) -> Result<
686        crate::datadogV2::model::CIAppPipelineEventsResponse,
687        datadog::Error<SearchCIAppPipelineEventsError>,
688    > {
689        match self
690            .search_ci_app_pipeline_events_with_http_info(params)
691            .await
692        {
693            Ok(response_content) => {
694                if let Some(e) = response_content.entity {
695                    Ok(e)
696                } else {
697                    Err(datadog::Error::Serde(serde::de::Error::custom(
698                        "response content was None",
699                    )))
700                }
701            }
702            Err(err) => Err(err),
703        }
704    }
705
706    pub fn search_ci_app_pipeline_events_with_pagination(
707        &self,
708        mut params: SearchCIAppPipelineEventsOptionalParams,
709    ) -> impl Stream<
710        Item = Result<
711            crate::datadogV2::model::CIAppPipelineEvent,
712            datadog::Error<SearchCIAppPipelineEventsError>,
713        >,
714    > + '_ {
715        try_stream! {
716            let mut page_size: i32 = 10;
717            if params.body.is_none() {
718                params.body = Some(crate::datadogV2::model::CIAppPipelineEventsRequest::new());
719            }
720            if params.body.as_ref().unwrap().page.is_none() {
721                params.body.as_mut().unwrap().page = Some(crate::datadogV2::model::CIAppQueryPageOptions::new());
722            }
723            if params.body.as_ref().unwrap().page.as_ref().unwrap().limit.is_none() {
724                params.body.as_mut().unwrap().page.as_mut().unwrap().limit = Some(page_size);
725            } else {
726                page_size = params.body.as_ref().unwrap().page.as_ref().unwrap().limit.unwrap().clone();
727            }
728            loop {
729                let resp = self.search_ci_app_pipeline_events(params.clone()).await?;
730                let Some(data) = resp.data else { break };
731
732                let r = data;
733                let count = r.len();
734                for team in r {
735                    yield team;
736                }
737
738                if count < page_size as usize {
739                    break;
740                }
741                let Some(meta) = resp.meta else { break };
742                let Some(page) = meta.page else { break };
743                let Some(after) = page.after else { break };
744
745                params.body.as_mut().unwrap().page.as_mut().unwrap().cursor = Some(after);
746            }
747        }
748    }
749
750    /// List endpoint returns CI Visibility pipeline events that match a [search query](<https://docs.datadoghq.com/continuous_integration/explorer/search_syntax/>).
751    /// [Results are paginated similarly to logs](<https://docs.datadoghq.com/logs/guide/collect-multiple-logs-with-pagination>).
752    ///
753    /// Use this endpoint to build complex events filtering and search.
754    pub async fn search_ci_app_pipeline_events_with_http_info(
755        &self,
756        params: SearchCIAppPipelineEventsOptionalParams,
757    ) -> Result<
758        datadog::ResponseContent<crate::datadogV2::model::CIAppPipelineEventsResponse>,
759        datadog::Error<SearchCIAppPipelineEventsError>,
760    > {
761        let local_configuration = &self.config;
762        let operation_id = "v2.search_ci_app_pipeline_events";
763
764        // unbox and build optional parameters
765        let body = params.body;
766
767        let local_client = &self.client;
768
769        let local_uri_str = format!(
770            "{}/api/v2/ci/pipelines/events/search",
771            local_configuration.get_operation_host(operation_id)
772        );
773        let mut local_req_builder =
774            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
775
776        // build headers
777        let mut headers = HeaderMap::new();
778        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
779        headers.insert("Accept", HeaderValue::from_static("application/json"));
780
781        // build user agent
782        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
783            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
784            Err(e) => {
785                log::warn!("Failed to parse user agent header: {e}, falling back to default");
786                headers.insert(
787                    reqwest::header::USER_AGENT,
788                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
789                )
790            }
791        };
792
793        // build auth
794        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
795            headers.insert(
796                "DD-API-KEY",
797                HeaderValue::from_str(local_key.key.as_str())
798                    .expect("failed to parse DD-API-KEY header"),
799            );
800        };
801        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
802            headers.insert(
803                "DD-APPLICATION-KEY",
804                HeaderValue::from_str(local_key.key.as_str())
805                    .expect("failed to parse DD-APPLICATION-KEY header"),
806            );
807        };
808
809        // build body parameters
810        let output = Vec::new();
811        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
812        if body.serialize(&mut ser).is_ok() {
813            if let Some(content_encoding) = headers.get("Content-Encoding") {
814                match content_encoding.to_str().unwrap_or_default() {
815                    "gzip" => {
816                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
817                        let _ = enc.write_all(ser.into_inner().as_slice());
818                        match enc.finish() {
819                            Ok(buf) => {
820                                local_req_builder = local_req_builder.body(buf);
821                            }
822                            Err(e) => return Err(datadog::Error::Io(e)),
823                        }
824                    }
825                    "deflate" => {
826                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
827                        let _ = enc.write_all(ser.into_inner().as_slice());
828                        match enc.finish() {
829                            Ok(buf) => {
830                                local_req_builder = local_req_builder.body(buf);
831                            }
832                            Err(e) => return Err(datadog::Error::Io(e)),
833                        }
834                    }
835                    "zstd1" => {
836                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
837                        let _ = enc.write_all(ser.into_inner().as_slice());
838                        match enc.finish() {
839                            Ok(buf) => {
840                                local_req_builder = local_req_builder.body(buf);
841                            }
842                            Err(e) => return Err(datadog::Error::Io(e)),
843                        }
844                    }
845                    _ => {
846                        local_req_builder = local_req_builder.body(ser.into_inner());
847                    }
848                }
849            } else {
850                local_req_builder = local_req_builder.body(ser.into_inner());
851            }
852        }
853
854        local_req_builder = local_req_builder.headers(headers);
855        let local_req = local_req_builder.build()?;
856        log::debug!("request content: {:?}", local_req.body());
857        let local_resp = local_client.execute(local_req).await?;
858
859        let local_status = local_resp.status();
860        let local_content = local_resp.text().await?;
861        log::debug!("response content: {}", local_content);
862
863        if !local_status.is_client_error() && !local_status.is_server_error() {
864            match serde_json::from_str::<crate::datadogV2::model::CIAppPipelineEventsResponse>(
865                &local_content,
866            ) {
867                Ok(e) => {
868                    return Ok(datadog::ResponseContent {
869                        status: local_status,
870                        content: local_content,
871                        entity: Some(e),
872                    })
873                }
874                Err(e) => return Err(datadog::Error::Serde(e)),
875            };
876        } else {
877            let local_entity: Option<SearchCIAppPipelineEventsError> =
878                serde_json::from_str(&local_content).ok();
879            let local_error = datadog::ResponseContent {
880                status: local_status,
881                content: local_content,
882                entity: local_entity,
883            };
884            Err(datadog::Error::ResponseError(local_error))
885        }
886    }
887}