datadog_api_client/datadogV2/api/
api_workflow_automation.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use flate2::{
6    write::{GzEncoder, ZlibEncoder},
7    Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13/// ListWorkflowInstancesOptionalParams is a struct for passing parameters to the method [`WorkflowAutomationAPI::list_workflow_instances`]
14#[non_exhaustive]
15#[derive(Clone, Default, Debug)]
16pub struct ListWorkflowInstancesOptionalParams {
17    /// Size for a given page. The maximum allowed value is 100.
18    pub page_size: Option<i64>,
19    /// Specific page number to return.
20    pub page_number: Option<i64>,
21}
22
23impl ListWorkflowInstancesOptionalParams {
24    /// Size for a given page. The maximum allowed value is 100.
25    pub fn page_size(mut self, value: i64) -> Self {
26        self.page_size = Some(value);
27        self
28    }
29    /// Specific page number to return.
30    pub fn page_number(mut self, value: i64) -> Self {
31        self.page_number = Some(value);
32        self
33    }
34}
35
36/// CancelWorkflowInstanceError is a struct for typed errors of method [`WorkflowAutomationAPI::cancel_workflow_instance`]
37#[derive(Debug, Clone, Serialize, Deserialize)]
38#[serde(untagged)]
39pub enum CancelWorkflowInstanceError {
40    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
41    UnknownValue(serde_json::Value),
42}
43
44/// CreateWorkflowError is a struct for typed errors of method [`WorkflowAutomationAPI::create_workflow`]
45#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(untagged)]
47pub enum CreateWorkflowError {
48    JSONAPIErrorResponse(crate::datadogV2::model::JSONAPIErrorResponse),
49    UnknownValue(serde_json::Value),
50}
51
52/// CreateWorkflowInstanceError is a struct for typed errors of method [`WorkflowAutomationAPI::create_workflow_instance`]
53#[derive(Debug, Clone, Serialize, Deserialize)]
54#[serde(untagged)]
55pub enum CreateWorkflowInstanceError {
56    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
57    UnknownValue(serde_json::Value),
58}
59
60/// DeleteWorkflowError is a struct for typed errors of method [`WorkflowAutomationAPI::delete_workflow`]
61#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(untagged)]
63pub enum DeleteWorkflowError {
64    JSONAPIErrorResponse(crate::datadogV2::model::JSONAPIErrorResponse),
65    UnknownValue(serde_json::Value),
66}
67
68/// GetWorkflowError is a struct for typed errors of method [`WorkflowAutomationAPI::get_workflow`]
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(untagged)]
71pub enum GetWorkflowError {
72    JSONAPIErrorResponse(crate::datadogV2::model::JSONAPIErrorResponse),
73    UnknownValue(serde_json::Value),
74}
75
76/// GetWorkflowInstanceError is a struct for typed errors of method [`WorkflowAutomationAPI::get_workflow_instance`]
77#[derive(Debug, Clone, Serialize, Deserialize)]
78#[serde(untagged)]
79pub enum GetWorkflowInstanceError {
80    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
81    UnknownValue(serde_json::Value),
82}
83
84/// ListWorkflowInstancesError is a struct for typed errors of method [`WorkflowAutomationAPI::list_workflow_instances`]
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(untagged)]
87pub enum ListWorkflowInstancesError {
88    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
89    UnknownValue(serde_json::Value),
90}
91
92/// UpdateWorkflowError is a struct for typed errors of method [`WorkflowAutomationAPI::update_workflow`]
93#[derive(Debug, Clone, Serialize, Deserialize)]
94#[serde(untagged)]
95pub enum UpdateWorkflowError {
96    JSONAPIErrorResponse(crate::datadogV2::model::JSONAPIErrorResponse),
97    UnknownValue(serde_json::Value),
98}
99
100/// Datadog Workflow Automation allows you to automate your end-to-end processes by connecting Datadog with the rest of your tech stack. Build workflows to auto-remediate your alerts, streamline your incident and security processes, and reduce manual toil. Workflow Automation supports over 1,000+ OOTB actions, including AWS, JIRA, ServiceNow, GitHub, and OpenAI. Learn more in our Workflow Automation docs [here](<https://docs.datadoghq.com/service_management/workflows/>).
101#[derive(Debug, Clone)]
102pub struct WorkflowAutomationAPI {
103    config: datadog::Configuration,
104    client: reqwest_middleware::ClientWithMiddleware,
105}
106
107impl Default for WorkflowAutomationAPI {
108    fn default() -> Self {
109        Self::with_config(datadog::Configuration::default())
110    }
111}
112
113impl WorkflowAutomationAPI {
114    pub fn new() -> Self {
115        Self::default()
116    }
117    pub fn with_config(config: datadog::Configuration) -> Self {
118        let mut reqwest_client_builder = reqwest::Client::builder();
119
120        if let Some(proxy_url) = &config.proxy_url {
121            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
122            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
123        }
124
125        let mut middleware_client_builder =
126            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
127
128        if config.enable_retry {
129            struct RetryableStatus;
130            impl reqwest_retry::RetryableStrategy for RetryableStatus {
131                fn handle(
132                    &self,
133                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
134                ) -> Option<reqwest_retry::Retryable> {
135                    match res {
136                        Ok(success) => reqwest_retry::default_on_request_success(success),
137                        Err(_) => None,
138                    }
139                }
140            }
141            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
142                .build_with_max_retries(config.max_retries);
143
144            let retry_middleware =
145                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
146                    backoff_policy,
147                    RetryableStatus,
148                );
149
150            middleware_client_builder = middleware_client_builder.with(retry_middleware);
151        }
152
153        let client = middleware_client_builder.build();
154
155        Self { config, client }
156    }
157
158    pub fn with_client_and_config(
159        config: datadog::Configuration,
160        client: reqwest_middleware::ClientWithMiddleware,
161    ) -> Self {
162        Self { config, client }
163    }
164
165    /// Cancels a specific execution of a given workflow. This API requires an application key scoped with the workflows_run permission.
166    pub async fn cancel_workflow_instance(
167        &self,
168        workflow_id: String,
169        instance_id: String,
170    ) -> Result<
171        crate::datadogV2::model::WorklflowCancelInstanceResponse,
172        datadog::Error<CancelWorkflowInstanceError>,
173    > {
174        match self
175            .cancel_workflow_instance_with_http_info(workflow_id, instance_id)
176            .await
177        {
178            Ok(response_content) => {
179                if let Some(e) = response_content.entity {
180                    Ok(e)
181                } else {
182                    Err(datadog::Error::Serde(serde::de::Error::custom(
183                        "response content was None",
184                    )))
185                }
186            }
187            Err(err) => Err(err),
188        }
189    }
190
191    /// Cancels a specific execution of a given workflow. This API requires an application key scoped with the workflows_run permission.
192    pub async fn cancel_workflow_instance_with_http_info(
193        &self,
194        workflow_id: String,
195        instance_id: String,
196    ) -> Result<
197        datadog::ResponseContent<crate::datadogV2::model::WorklflowCancelInstanceResponse>,
198        datadog::Error<CancelWorkflowInstanceError>,
199    > {
200        let local_configuration = &self.config;
201        let operation_id = "v2.cancel_workflow_instance";
202
203        let local_client = &self.client;
204
205        let local_uri_str = format!(
206            "{}/api/v2/workflows/{workflow_id}/instances/{instance_id}/cancel",
207            local_configuration.get_operation_host(operation_id),
208            workflow_id = datadog::urlencode(workflow_id),
209            instance_id = datadog::urlencode(instance_id)
210        );
211        let mut local_req_builder =
212            local_client.request(reqwest::Method::PUT, local_uri_str.as_str());
213
214        // build headers
215        let mut headers = HeaderMap::new();
216        headers.insert("Accept", HeaderValue::from_static("application/json"));
217
218        // build user agent
219        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
220            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
221            Err(e) => {
222                log::warn!("Failed to parse user agent header: {e}, falling back to default");
223                headers.insert(
224                    reqwest::header::USER_AGENT,
225                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
226                )
227            }
228        };
229
230        // build auth
231        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
232            headers.insert(
233                "DD-API-KEY",
234                HeaderValue::from_str(local_key.key.as_str())
235                    .expect("failed to parse DD-API-KEY header"),
236            );
237        };
238        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
239            headers.insert(
240                "DD-APPLICATION-KEY",
241                HeaderValue::from_str(local_key.key.as_str())
242                    .expect("failed to parse DD-APPLICATION-KEY header"),
243            );
244        };
245
246        local_req_builder = local_req_builder.headers(headers);
247        let local_req = local_req_builder.build()?;
248        log::debug!("request content: {:?}", local_req.body());
249        let local_resp = local_client.execute(local_req).await?;
250
251        let local_status = local_resp.status();
252        let local_content = local_resp.text().await?;
253        log::debug!("response content: {}", local_content);
254
255        if !local_status.is_client_error() && !local_status.is_server_error() {
256            match serde_json::from_str::<crate::datadogV2::model::WorklflowCancelInstanceResponse>(
257                &local_content,
258            ) {
259                Ok(e) => {
260                    return Ok(datadog::ResponseContent {
261                        status: local_status,
262                        content: local_content,
263                        entity: Some(e),
264                    })
265                }
266                Err(e) => return Err(datadog::Error::Serde(e)),
267            };
268        } else {
269            let local_entity: Option<CancelWorkflowInstanceError> =
270                serde_json::from_str(&local_content).ok();
271            let local_error = datadog::ResponseContent {
272                status: local_status,
273                content: local_content,
274                entity: local_entity,
275            };
276            Err(datadog::Error::ResponseError(local_error))
277        }
278    }
279
280    /// Create a new workflow, returning the workflow ID. This API requires an application key scoped with the `workflows_write` permission.
281    pub async fn create_workflow(
282        &self,
283        body: crate::datadogV2::model::CreateWorkflowRequest,
284    ) -> Result<crate::datadogV2::model::CreateWorkflowResponse, datadog::Error<CreateWorkflowError>>
285    {
286        match self.create_workflow_with_http_info(body).await {
287            Ok(response_content) => {
288                if let Some(e) = response_content.entity {
289                    Ok(e)
290                } else {
291                    Err(datadog::Error::Serde(serde::de::Error::custom(
292                        "response content was None",
293                    )))
294                }
295            }
296            Err(err) => Err(err),
297        }
298    }
299
300    /// Create a new workflow, returning the workflow ID. This API requires an application key scoped with the `workflows_write` permission.
301    pub async fn create_workflow_with_http_info(
302        &self,
303        body: crate::datadogV2::model::CreateWorkflowRequest,
304    ) -> Result<
305        datadog::ResponseContent<crate::datadogV2::model::CreateWorkflowResponse>,
306        datadog::Error<CreateWorkflowError>,
307    > {
308        let local_configuration = &self.config;
309        let operation_id = "v2.create_workflow";
310
311        let local_client = &self.client;
312
313        let local_uri_str = format!(
314            "{}/api/v2/workflows",
315            local_configuration.get_operation_host(operation_id)
316        );
317        let mut local_req_builder =
318            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
319
320        // build headers
321        let mut headers = HeaderMap::new();
322        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
323        headers.insert("Accept", HeaderValue::from_static("application/json"));
324
325        // build user agent
326        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
327            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
328            Err(e) => {
329                log::warn!("Failed to parse user agent header: {e}, falling back to default");
330                headers.insert(
331                    reqwest::header::USER_AGENT,
332                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
333                )
334            }
335        };
336
337        // build auth
338        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
339            headers.insert(
340                "DD-API-KEY",
341                HeaderValue::from_str(local_key.key.as_str())
342                    .expect("failed to parse DD-API-KEY header"),
343            );
344        };
345        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
346            headers.insert(
347                "DD-APPLICATION-KEY",
348                HeaderValue::from_str(local_key.key.as_str())
349                    .expect("failed to parse DD-APPLICATION-KEY header"),
350            );
351        };
352
353        // build body parameters
354        let output = Vec::new();
355        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
356        if body.serialize(&mut ser).is_ok() {
357            if let Some(content_encoding) = headers.get("Content-Encoding") {
358                match content_encoding.to_str().unwrap_or_default() {
359                    "gzip" => {
360                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
361                        let _ = enc.write_all(ser.into_inner().as_slice());
362                        match enc.finish() {
363                            Ok(buf) => {
364                                local_req_builder = local_req_builder.body(buf);
365                            }
366                            Err(e) => return Err(datadog::Error::Io(e)),
367                        }
368                    }
369                    "deflate" => {
370                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
371                        let _ = enc.write_all(ser.into_inner().as_slice());
372                        match enc.finish() {
373                            Ok(buf) => {
374                                local_req_builder = local_req_builder.body(buf);
375                            }
376                            Err(e) => return Err(datadog::Error::Io(e)),
377                        }
378                    }
379                    "zstd1" => {
380                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
381                        let _ = enc.write_all(ser.into_inner().as_slice());
382                        match enc.finish() {
383                            Ok(buf) => {
384                                local_req_builder = local_req_builder.body(buf);
385                            }
386                            Err(e) => return Err(datadog::Error::Io(e)),
387                        }
388                    }
389                    _ => {
390                        local_req_builder = local_req_builder.body(ser.into_inner());
391                    }
392                }
393            } else {
394                local_req_builder = local_req_builder.body(ser.into_inner());
395            }
396        }
397
398        local_req_builder = local_req_builder.headers(headers);
399        let local_req = local_req_builder.build()?;
400        log::debug!("request content: {:?}", local_req.body());
401        let local_resp = local_client.execute(local_req).await?;
402
403        let local_status = local_resp.status();
404        let local_content = local_resp.text().await?;
405        log::debug!("response content: {}", local_content);
406
407        if !local_status.is_client_error() && !local_status.is_server_error() {
408            match serde_json::from_str::<crate::datadogV2::model::CreateWorkflowResponse>(
409                &local_content,
410            ) {
411                Ok(e) => {
412                    return Ok(datadog::ResponseContent {
413                        status: local_status,
414                        content: local_content,
415                        entity: Some(e),
416                    })
417                }
418                Err(e) => return Err(datadog::Error::Serde(e)),
419            };
420        } else {
421            let local_entity: Option<CreateWorkflowError> =
422                serde_json::from_str(&local_content).ok();
423            let local_error = datadog::ResponseContent {
424                status: local_status,
425                content: local_content,
426                entity: local_entity,
427            };
428            Err(datadog::Error::ResponseError(local_error))
429        }
430    }
431
432    /// Execute the given workflow. This API requires an application key scoped with the workflows_run permission.
433    pub async fn create_workflow_instance(
434        &self,
435        workflow_id: String,
436        body: crate::datadogV2::model::WorkflowInstanceCreateRequest,
437    ) -> Result<
438        crate::datadogV2::model::WorkflowInstanceCreateResponse,
439        datadog::Error<CreateWorkflowInstanceError>,
440    > {
441        match self
442            .create_workflow_instance_with_http_info(workflow_id, body)
443            .await
444        {
445            Ok(response_content) => {
446                if let Some(e) = response_content.entity {
447                    Ok(e)
448                } else {
449                    Err(datadog::Error::Serde(serde::de::Error::custom(
450                        "response content was None",
451                    )))
452                }
453            }
454            Err(err) => Err(err),
455        }
456    }
457
458    /// Execute the given workflow. This API requires an application key scoped with the workflows_run permission.
459    pub async fn create_workflow_instance_with_http_info(
460        &self,
461        workflow_id: String,
462        body: crate::datadogV2::model::WorkflowInstanceCreateRequest,
463    ) -> Result<
464        datadog::ResponseContent<crate::datadogV2::model::WorkflowInstanceCreateResponse>,
465        datadog::Error<CreateWorkflowInstanceError>,
466    > {
467        let local_configuration = &self.config;
468        let operation_id = "v2.create_workflow_instance";
469
470        let local_client = &self.client;
471
472        let local_uri_str = format!(
473            "{}/api/v2/workflows/{workflow_id}/instances",
474            local_configuration.get_operation_host(operation_id),
475            workflow_id = datadog::urlencode(workflow_id)
476        );
477        let mut local_req_builder =
478            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
479
480        // build headers
481        let mut headers = HeaderMap::new();
482        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
483        headers.insert("Accept", HeaderValue::from_static("application/json"));
484
485        // build user agent
486        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
487            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
488            Err(e) => {
489                log::warn!("Failed to parse user agent header: {e}, falling back to default");
490                headers.insert(
491                    reqwest::header::USER_AGENT,
492                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
493                )
494            }
495        };
496
497        // build auth
498        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
499            headers.insert(
500                "DD-API-KEY",
501                HeaderValue::from_str(local_key.key.as_str())
502                    .expect("failed to parse DD-API-KEY header"),
503            );
504        };
505        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
506            headers.insert(
507                "DD-APPLICATION-KEY",
508                HeaderValue::from_str(local_key.key.as_str())
509                    .expect("failed to parse DD-APPLICATION-KEY header"),
510            );
511        };
512
513        // build body parameters
514        let output = Vec::new();
515        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
516        if body.serialize(&mut ser).is_ok() {
517            if let Some(content_encoding) = headers.get("Content-Encoding") {
518                match content_encoding.to_str().unwrap_or_default() {
519                    "gzip" => {
520                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
521                        let _ = enc.write_all(ser.into_inner().as_slice());
522                        match enc.finish() {
523                            Ok(buf) => {
524                                local_req_builder = local_req_builder.body(buf);
525                            }
526                            Err(e) => return Err(datadog::Error::Io(e)),
527                        }
528                    }
529                    "deflate" => {
530                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
531                        let _ = enc.write_all(ser.into_inner().as_slice());
532                        match enc.finish() {
533                            Ok(buf) => {
534                                local_req_builder = local_req_builder.body(buf);
535                            }
536                            Err(e) => return Err(datadog::Error::Io(e)),
537                        }
538                    }
539                    "zstd1" => {
540                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
541                        let _ = enc.write_all(ser.into_inner().as_slice());
542                        match enc.finish() {
543                            Ok(buf) => {
544                                local_req_builder = local_req_builder.body(buf);
545                            }
546                            Err(e) => return Err(datadog::Error::Io(e)),
547                        }
548                    }
549                    _ => {
550                        local_req_builder = local_req_builder.body(ser.into_inner());
551                    }
552                }
553            } else {
554                local_req_builder = local_req_builder.body(ser.into_inner());
555            }
556        }
557
558        local_req_builder = local_req_builder.headers(headers);
559        let local_req = local_req_builder.build()?;
560        log::debug!("request content: {:?}", local_req.body());
561        let local_resp = local_client.execute(local_req).await?;
562
563        let local_status = local_resp.status();
564        let local_content = local_resp.text().await?;
565        log::debug!("response content: {}", local_content);
566
567        if !local_status.is_client_error() && !local_status.is_server_error() {
568            match serde_json::from_str::<crate::datadogV2::model::WorkflowInstanceCreateResponse>(
569                &local_content,
570            ) {
571                Ok(e) => {
572                    return Ok(datadog::ResponseContent {
573                        status: local_status,
574                        content: local_content,
575                        entity: Some(e),
576                    })
577                }
578                Err(e) => return Err(datadog::Error::Serde(e)),
579            };
580        } else {
581            let local_entity: Option<CreateWorkflowInstanceError> =
582                serde_json::from_str(&local_content).ok();
583            let local_error = datadog::ResponseContent {
584                status: local_status,
585                content: local_content,
586                entity: local_entity,
587            };
588            Err(datadog::Error::ResponseError(local_error))
589        }
590    }
591
592    /// Delete a workflow by ID. This API requires an application key scoped with the `workflows_write` permission.
593    pub async fn delete_workflow(
594        &self,
595        workflow_id: String,
596    ) -> Result<(), datadog::Error<DeleteWorkflowError>> {
597        match self.delete_workflow_with_http_info(workflow_id).await {
598            Ok(_) => Ok(()),
599            Err(err) => Err(err),
600        }
601    }
602
603    /// Delete a workflow by ID. This API requires an application key scoped with the `workflows_write` permission.
604    pub async fn delete_workflow_with_http_info(
605        &self,
606        workflow_id: String,
607    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteWorkflowError>> {
608        let local_configuration = &self.config;
609        let operation_id = "v2.delete_workflow";
610
611        let local_client = &self.client;
612
613        let local_uri_str = format!(
614            "{}/api/v2/workflows/{workflow_id}",
615            local_configuration.get_operation_host(operation_id),
616            workflow_id = datadog::urlencode(workflow_id)
617        );
618        let mut local_req_builder =
619            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
620
621        // build headers
622        let mut headers = HeaderMap::new();
623        headers.insert("Accept", HeaderValue::from_static("*/*"));
624
625        // build user agent
626        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
627            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
628            Err(e) => {
629                log::warn!("Failed to parse user agent header: {e}, falling back to default");
630                headers.insert(
631                    reqwest::header::USER_AGENT,
632                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
633                )
634            }
635        };
636
637        // build auth
638        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
639            headers.insert(
640                "DD-API-KEY",
641                HeaderValue::from_str(local_key.key.as_str())
642                    .expect("failed to parse DD-API-KEY header"),
643            );
644        };
645        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
646            headers.insert(
647                "DD-APPLICATION-KEY",
648                HeaderValue::from_str(local_key.key.as_str())
649                    .expect("failed to parse DD-APPLICATION-KEY header"),
650            );
651        };
652
653        local_req_builder = local_req_builder.headers(headers);
654        let local_req = local_req_builder.build()?;
655        log::debug!("request content: {:?}", local_req.body());
656        let local_resp = local_client.execute(local_req).await?;
657
658        let local_status = local_resp.status();
659        let local_content = local_resp.text().await?;
660        log::debug!("response content: {}", local_content);
661
662        if !local_status.is_client_error() && !local_status.is_server_error() {
663            Ok(datadog::ResponseContent {
664                status: local_status,
665                content: local_content,
666                entity: None,
667            })
668        } else {
669            let local_entity: Option<DeleteWorkflowError> =
670                serde_json::from_str(&local_content).ok();
671            let local_error = datadog::ResponseContent {
672                status: local_status,
673                content: local_content,
674                entity: local_entity,
675            };
676            Err(datadog::Error::ResponseError(local_error))
677        }
678    }
679
680    /// Get a workflow by ID.  This API requires an application key scoped with the `workflows_read` permission.
681    pub async fn get_workflow(
682        &self,
683        workflow_id: String,
684    ) -> Result<crate::datadogV2::model::GetWorkflowResponse, datadog::Error<GetWorkflowError>>
685    {
686        match self.get_workflow_with_http_info(workflow_id).await {
687            Ok(response_content) => {
688                if let Some(e) = response_content.entity {
689                    Ok(e)
690                } else {
691                    Err(datadog::Error::Serde(serde::de::Error::custom(
692                        "response content was None",
693                    )))
694                }
695            }
696            Err(err) => Err(err),
697        }
698    }
699
700    /// Get a workflow by ID.  This API requires an application key scoped with the `workflows_read` permission.
701    pub async fn get_workflow_with_http_info(
702        &self,
703        workflow_id: String,
704    ) -> Result<
705        datadog::ResponseContent<crate::datadogV2::model::GetWorkflowResponse>,
706        datadog::Error<GetWorkflowError>,
707    > {
708        let local_configuration = &self.config;
709        let operation_id = "v2.get_workflow";
710
711        let local_client = &self.client;
712
713        let local_uri_str = format!(
714            "{}/api/v2/workflows/{workflow_id}",
715            local_configuration.get_operation_host(operation_id),
716            workflow_id = datadog::urlencode(workflow_id)
717        );
718        let mut local_req_builder =
719            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
720
721        // build headers
722        let mut headers = HeaderMap::new();
723        headers.insert("Accept", HeaderValue::from_static("application/json"));
724
725        // build user agent
726        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
727            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
728            Err(e) => {
729                log::warn!("Failed to parse user agent header: {e}, falling back to default");
730                headers.insert(
731                    reqwest::header::USER_AGENT,
732                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
733                )
734            }
735        };
736
737        // build auth
738        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
739            headers.insert(
740                "DD-API-KEY",
741                HeaderValue::from_str(local_key.key.as_str())
742                    .expect("failed to parse DD-API-KEY header"),
743            );
744        };
745        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
746            headers.insert(
747                "DD-APPLICATION-KEY",
748                HeaderValue::from_str(local_key.key.as_str())
749                    .expect("failed to parse DD-APPLICATION-KEY header"),
750            );
751        };
752
753        local_req_builder = local_req_builder.headers(headers);
754        let local_req = local_req_builder.build()?;
755        log::debug!("request content: {:?}", local_req.body());
756        let local_resp = local_client.execute(local_req).await?;
757
758        let local_status = local_resp.status();
759        let local_content = local_resp.text().await?;
760        log::debug!("response content: {}", local_content);
761
762        if !local_status.is_client_error() && !local_status.is_server_error() {
763            match serde_json::from_str::<crate::datadogV2::model::GetWorkflowResponse>(
764                &local_content,
765            ) {
766                Ok(e) => {
767                    return Ok(datadog::ResponseContent {
768                        status: local_status,
769                        content: local_content,
770                        entity: Some(e),
771                    })
772                }
773                Err(e) => return Err(datadog::Error::Serde(e)),
774            };
775        } else {
776            let local_entity: Option<GetWorkflowError> = serde_json::from_str(&local_content).ok();
777            let local_error = datadog::ResponseContent {
778                status: local_status,
779                content: local_content,
780                entity: local_entity,
781            };
782            Err(datadog::Error::ResponseError(local_error))
783        }
784    }
785
786    /// Get a specific execution of a given workflow. This API requires an application key scoped with the workflows_read permission.
787    pub async fn get_workflow_instance(
788        &self,
789        workflow_id: String,
790        instance_id: String,
791    ) -> Result<
792        crate::datadogV2::model::WorklflowGetInstanceResponse,
793        datadog::Error<GetWorkflowInstanceError>,
794    > {
795        match self
796            .get_workflow_instance_with_http_info(workflow_id, instance_id)
797            .await
798        {
799            Ok(response_content) => {
800                if let Some(e) = response_content.entity {
801                    Ok(e)
802                } else {
803                    Err(datadog::Error::Serde(serde::de::Error::custom(
804                        "response content was None",
805                    )))
806                }
807            }
808            Err(err) => Err(err),
809        }
810    }
811
812    /// Get a specific execution of a given workflow. This API requires an application key scoped with the workflows_read permission.
813    pub async fn get_workflow_instance_with_http_info(
814        &self,
815        workflow_id: String,
816        instance_id: String,
817    ) -> Result<
818        datadog::ResponseContent<crate::datadogV2::model::WorklflowGetInstanceResponse>,
819        datadog::Error<GetWorkflowInstanceError>,
820    > {
821        let local_configuration = &self.config;
822        let operation_id = "v2.get_workflow_instance";
823
824        let local_client = &self.client;
825
826        let local_uri_str = format!(
827            "{}/api/v2/workflows/{workflow_id}/instances/{instance_id}",
828            local_configuration.get_operation_host(operation_id),
829            workflow_id = datadog::urlencode(workflow_id),
830            instance_id = datadog::urlencode(instance_id)
831        );
832        let mut local_req_builder =
833            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
834
835        // build headers
836        let mut headers = HeaderMap::new();
837        headers.insert("Accept", HeaderValue::from_static("application/json"));
838
839        // build user agent
840        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
841            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
842            Err(e) => {
843                log::warn!("Failed to parse user agent header: {e}, falling back to default");
844                headers.insert(
845                    reqwest::header::USER_AGENT,
846                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
847                )
848            }
849        };
850
851        // build auth
852        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
853            headers.insert(
854                "DD-API-KEY",
855                HeaderValue::from_str(local_key.key.as_str())
856                    .expect("failed to parse DD-API-KEY header"),
857            );
858        };
859        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
860            headers.insert(
861                "DD-APPLICATION-KEY",
862                HeaderValue::from_str(local_key.key.as_str())
863                    .expect("failed to parse DD-APPLICATION-KEY header"),
864            );
865        };
866
867        local_req_builder = local_req_builder.headers(headers);
868        let local_req = local_req_builder.build()?;
869        log::debug!("request content: {:?}", local_req.body());
870        let local_resp = local_client.execute(local_req).await?;
871
872        let local_status = local_resp.status();
873        let local_content = local_resp.text().await?;
874        log::debug!("response content: {}", local_content);
875
876        if !local_status.is_client_error() && !local_status.is_server_error() {
877            match serde_json::from_str::<crate::datadogV2::model::WorklflowGetInstanceResponse>(
878                &local_content,
879            ) {
880                Ok(e) => {
881                    return Ok(datadog::ResponseContent {
882                        status: local_status,
883                        content: local_content,
884                        entity: Some(e),
885                    })
886                }
887                Err(e) => return Err(datadog::Error::Serde(e)),
888            };
889        } else {
890            let local_entity: Option<GetWorkflowInstanceError> =
891                serde_json::from_str(&local_content).ok();
892            let local_error = datadog::ResponseContent {
893                status: local_status,
894                content: local_content,
895                entity: local_entity,
896            };
897            Err(datadog::Error::ResponseError(local_error))
898        }
899    }
900
901    /// List all instances of a given workflow. This API requires an application key scoped with the workflows_read permission.
902    pub async fn list_workflow_instances(
903        &self,
904        workflow_id: String,
905        params: ListWorkflowInstancesOptionalParams,
906    ) -> Result<
907        crate::datadogV2::model::WorkflowListInstancesResponse,
908        datadog::Error<ListWorkflowInstancesError>,
909    > {
910        match self
911            .list_workflow_instances_with_http_info(workflow_id, params)
912            .await
913        {
914            Ok(response_content) => {
915                if let Some(e) = response_content.entity {
916                    Ok(e)
917                } else {
918                    Err(datadog::Error::Serde(serde::de::Error::custom(
919                        "response content was None",
920                    )))
921                }
922            }
923            Err(err) => Err(err),
924        }
925    }
926
927    /// List all instances of a given workflow. This API requires an application key scoped with the workflows_read permission.
928    pub async fn list_workflow_instances_with_http_info(
929        &self,
930        workflow_id: String,
931        params: ListWorkflowInstancesOptionalParams,
932    ) -> Result<
933        datadog::ResponseContent<crate::datadogV2::model::WorkflowListInstancesResponse>,
934        datadog::Error<ListWorkflowInstancesError>,
935    > {
936        let local_configuration = &self.config;
937        let operation_id = "v2.list_workflow_instances";
938
939        // unbox and build optional parameters
940        let page_size = params.page_size;
941        let page_number = params.page_number;
942
943        let local_client = &self.client;
944
945        let local_uri_str = format!(
946            "{}/api/v2/workflows/{workflow_id}/instances",
947            local_configuration.get_operation_host(operation_id),
948            workflow_id = datadog::urlencode(workflow_id)
949        );
950        let mut local_req_builder =
951            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
952
953        if let Some(ref local_query_param) = page_size {
954            local_req_builder =
955                local_req_builder.query(&[("page[size]", &local_query_param.to_string())]);
956        };
957        if let Some(ref local_query_param) = page_number {
958            local_req_builder =
959                local_req_builder.query(&[("page[number]", &local_query_param.to_string())]);
960        };
961
962        // build headers
963        let mut headers = HeaderMap::new();
964        headers.insert("Accept", HeaderValue::from_static("application/json"));
965
966        // build user agent
967        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
968            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
969            Err(e) => {
970                log::warn!("Failed to parse user agent header: {e}, falling back to default");
971                headers.insert(
972                    reqwest::header::USER_AGENT,
973                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
974                )
975            }
976        };
977
978        // build auth
979        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
980            headers.insert(
981                "DD-API-KEY",
982                HeaderValue::from_str(local_key.key.as_str())
983                    .expect("failed to parse DD-API-KEY header"),
984            );
985        };
986        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
987            headers.insert(
988                "DD-APPLICATION-KEY",
989                HeaderValue::from_str(local_key.key.as_str())
990                    .expect("failed to parse DD-APPLICATION-KEY header"),
991            );
992        };
993
994        local_req_builder = local_req_builder.headers(headers);
995        let local_req = local_req_builder.build()?;
996        log::debug!("request content: {:?}", local_req.body());
997        let local_resp = local_client.execute(local_req).await?;
998
999        let local_status = local_resp.status();
1000        let local_content = local_resp.text().await?;
1001        log::debug!("response content: {}", local_content);
1002
1003        if !local_status.is_client_error() && !local_status.is_server_error() {
1004            match serde_json::from_str::<crate::datadogV2::model::WorkflowListInstancesResponse>(
1005                &local_content,
1006            ) {
1007                Ok(e) => {
1008                    return Ok(datadog::ResponseContent {
1009                        status: local_status,
1010                        content: local_content,
1011                        entity: Some(e),
1012                    })
1013                }
1014                Err(e) => return Err(datadog::Error::Serde(e)),
1015            };
1016        } else {
1017            let local_entity: Option<ListWorkflowInstancesError> =
1018                serde_json::from_str(&local_content).ok();
1019            let local_error = datadog::ResponseContent {
1020                status: local_status,
1021                content: local_content,
1022                entity: local_entity,
1023            };
1024            Err(datadog::Error::ResponseError(local_error))
1025        }
1026    }
1027
1028    /// Update a workflow by ID. This API requires an application key scoped with the `workflows_write` permission.
1029    pub async fn update_workflow(
1030        &self,
1031        workflow_id: String,
1032        body: crate::datadogV2::model::UpdateWorkflowRequest,
1033    ) -> Result<crate::datadogV2::model::UpdateWorkflowResponse, datadog::Error<UpdateWorkflowError>>
1034    {
1035        match self.update_workflow_with_http_info(workflow_id, body).await {
1036            Ok(response_content) => {
1037                if let Some(e) = response_content.entity {
1038                    Ok(e)
1039                } else {
1040                    Err(datadog::Error::Serde(serde::de::Error::custom(
1041                        "response content was None",
1042                    )))
1043                }
1044            }
1045            Err(err) => Err(err),
1046        }
1047    }
1048
1049    /// Update a workflow by ID. This API requires an application key scoped with the `workflows_write` permission.
1050    pub async fn update_workflow_with_http_info(
1051        &self,
1052        workflow_id: String,
1053        body: crate::datadogV2::model::UpdateWorkflowRequest,
1054    ) -> Result<
1055        datadog::ResponseContent<crate::datadogV2::model::UpdateWorkflowResponse>,
1056        datadog::Error<UpdateWorkflowError>,
1057    > {
1058        let local_configuration = &self.config;
1059        let operation_id = "v2.update_workflow";
1060
1061        let local_client = &self.client;
1062
1063        let local_uri_str = format!(
1064            "{}/api/v2/workflows/{workflow_id}",
1065            local_configuration.get_operation_host(operation_id),
1066            workflow_id = datadog::urlencode(workflow_id)
1067        );
1068        let mut local_req_builder =
1069            local_client.request(reqwest::Method::PATCH, local_uri_str.as_str());
1070
1071        // build headers
1072        let mut headers = HeaderMap::new();
1073        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
1074        headers.insert("Accept", HeaderValue::from_static("application/json"));
1075
1076        // build user agent
1077        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
1078            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
1079            Err(e) => {
1080                log::warn!("Failed to parse user agent header: {e}, falling back to default");
1081                headers.insert(
1082                    reqwest::header::USER_AGENT,
1083                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
1084                )
1085            }
1086        };
1087
1088        // build auth
1089        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
1090            headers.insert(
1091                "DD-API-KEY",
1092                HeaderValue::from_str(local_key.key.as_str())
1093                    .expect("failed to parse DD-API-KEY header"),
1094            );
1095        };
1096        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
1097            headers.insert(
1098                "DD-APPLICATION-KEY",
1099                HeaderValue::from_str(local_key.key.as_str())
1100                    .expect("failed to parse DD-APPLICATION-KEY header"),
1101            );
1102        };
1103
1104        // build body parameters
1105        let output = Vec::new();
1106        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
1107        if body.serialize(&mut ser).is_ok() {
1108            if let Some(content_encoding) = headers.get("Content-Encoding") {
1109                match content_encoding.to_str().unwrap_or_default() {
1110                    "gzip" => {
1111                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
1112                        let _ = enc.write_all(ser.into_inner().as_slice());
1113                        match enc.finish() {
1114                            Ok(buf) => {
1115                                local_req_builder = local_req_builder.body(buf);
1116                            }
1117                            Err(e) => return Err(datadog::Error::Io(e)),
1118                        }
1119                    }
1120                    "deflate" => {
1121                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
1122                        let _ = enc.write_all(ser.into_inner().as_slice());
1123                        match enc.finish() {
1124                            Ok(buf) => {
1125                                local_req_builder = local_req_builder.body(buf);
1126                            }
1127                            Err(e) => return Err(datadog::Error::Io(e)),
1128                        }
1129                    }
1130                    "zstd1" => {
1131                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
1132                        let _ = enc.write_all(ser.into_inner().as_slice());
1133                        match enc.finish() {
1134                            Ok(buf) => {
1135                                local_req_builder = local_req_builder.body(buf);
1136                            }
1137                            Err(e) => return Err(datadog::Error::Io(e)),
1138                        }
1139                    }
1140                    _ => {
1141                        local_req_builder = local_req_builder.body(ser.into_inner());
1142                    }
1143                }
1144            } else {
1145                local_req_builder = local_req_builder.body(ser.into_inner());
1146            }
1147        }
1148
1149        local_req_builder = local_req_builder.headers(headers);
1150        let local_req = local_req_builder.build()?;
1151        log::debug!("request content: {:?}", local_req.body());
1152        let local_resp = local_client.execute(local_req).await?;
1153
1154        let local_status = local_resp.status();
1155        let local_content = local_resp.text().await?;
1156        log::debug!("response content: {}", local_content);
1157
1158        if !local_status.is_client_error() && !local_status.is_server_error() {
1159            match serde_json::from_str::<crate::datadogV2::model::UpdateWorkflowResponse>(
1160                &local_content,
1161            ) {
1162                Ok(e) => {
1163                    return Ok(datadog::ResponseContent {
1164                        status: local_status,
1165                        content: local_content,
1166                        entity: Some(e),
1167                    })
1168                }
1169                Err(e) => return Err(datadog::Error::Serde(e)),
1170            };
1171        } else {
1172            let local_entity: Option<UpdateWorkflowError> =
1173                serde_json::from_str(&local_content).ok();
1174            let local_error = datadog::ResponseContent {
1175                status: local_status,
1176                content: local_content,
1177                entity: local_entity,
1178            };
1179            Err(datadog::Error::ResponseError(local_error))
1180        }
1181    }
1182}