Skip to main content

conductor/client/
workflow_client.rs

1// Copyright {{.Year}} Conductor OSS
2// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
3
4use std::collections::HashMap;
5use std::fmt::Write as _;
6use std::time::Duration;
7use tracing::{debug, info};
8
9use crate::error::Result;
10use crate::events::{exception_label, EventDispatcher, WorkflowStartFailure, WorkflowStarted};
11use crate::http::{ApiClient, ApiPath};
12use crate::models::{StartWorkflowRequest, TaskResultStatus, Workflow, WorkflowDef};
13
14/// Client for workflow operations.
15#[derive(Clone)]
16pub struct WorkflowClient {
17    api: ApiClient,
18    /// Event dispatcher used to publish `WorkflowStarted` /
19    /// `WorkflowStartFailure`. Defaults to an empty dispatcher (no-op);
20    /// construct via [`WorkflowClient::new_with_events`] to hook metrics in.
21    events: EventDispatcher,
22}
23
24impl WorkflowClient {
25    /// Create a new workflow client without an event dispatcher.
26    ///
27    /// The `WorkflowStarted` / `WorkflowStartFailure` events will still be
28    /// published, but no listeners will see them. Use
29    /// [`WorkflowClient::new_with_events`] to wire a shared dispatcher (e.g.
30    /// one owned by [`TaskHandler`](crate::worker::TaskHandler)) so the
31    /// `MetricsCollector` can observe workflow-start metrics.
32    #[must_use]
33    pub fn new(api: ApiClient) -> Self {
34        Self {
35            api,
36            events: EventDispatcher::default(),
37        }
38    }
39
40    /// Create a new workflow client wired to an existing [`EventDispatcher`].
41    #[must_use]
42    pub fn new_with_events(api: ApiClient, events: EventDispatcher) -> Self {
43        Self { api, events }
44    }
45
46    /// Start a workflow asynchronously.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
51    pub async fn start_workflow(&self, request: &StartWorkflowRequest) -> Result<String> {
52        debug!(
53            workflow_name = %request.name,
54            "Starting workflow"
55        );
56
57        // Compute input byte size up-front so it is available for both the
58        // success-path gauge and for the failure-path tracing. Uses the same
59        // JSON serialization that the transport will perform, so the reported
60        // bytes match what actually leaves this process.
61        let input_size_bytes = serde_json::to_vec(&request.input).map_or(0, |v| v.len());
62
63        match self
64            .api
65            .post_text::<StartWorkflowRequest>("/workflow", request)
66            .await
67        {
68            Ok(workflow_id) => {
69                info!(
70                    workflow_name = %request.name,
71                    workflow_id = %workflow_id,
72                    "Workflow started"
73                );
74
75                self.events.publish_workflow_started(&WorkflowStarted::new(
76                    &request.name,
77                    request.version,
78                    input_size_bytes,
79                ));
80
81                Ok(workflow_id)
82            }
83            Err(e) => {
84                let exception = exception_label(&e);
85                self.events
86                    .publish_workflow_start_failure(&WorkflowStartFailure::new(
87                        &request.name,
88                        exception,
89                    ));
90                Err(e)
91            }
92        }
93    }
94
95    /// Execute a workflow synchronously and wait for completion.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
100    pub async fn execute_workflow(
101        &self,
102        request: &StartWorkflowRequest,
103        wait_for: Duration,
104    ) -> Result<Workflow> {
105        #[derive(serde::Serialize)]
106        #[serde(rename_all = "camelCase")]
107        struct ExecuteRequest<'a> {
108            #[serde(flatten)]
109            request: &'a StartWorkflowRequest,
110            request_id: String,
111        }
112
113        let wait_secs = wait_for.as_secs().to_string();
114        let request_id = uuid::Uuid::new_v4().to_string();
115
116        let path = format!(
117            "/workflow/execute/{}/{}?waitForSeconds={}",
118            request.name,
119            request.version.unwrap_or(1),
120            wait_secs
121        );
122
123        debug!(
124            workflow_name = %request.name,
125            wait_secs = %wait_secs,
126            "Executing workflow synchronously"
127        );
128
129        let exec_request = ExecuteRequest {
130            request,
131            request_id,
132        };
133
134        let workflow: Workflow = self
135            .api
136            .post(
137                ApiPath::templated(&path, "/workflow/execute/{name}/{version}"),
138                &exec_request,
139            )
140            .await?;
141
142        info!(
143            workflow_name = %request.name,
144            workflow_id = %workflow.workflow_id,
145            status = ?workflow.status,
146            "Workflow executed"
147        );
148
149        Ok(workflow)
150    }
151
152    /// Get workflow by ID.
153    ///
154    /// # Errors
155    ///
156    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
157    pub async fn get_workflow(&self, workflow_id: &str, include_tasks: bool) -> Result<Workflow> {
158        let path = format!("/workflow/{workflow_id}?includeTasks={include_tasks}");
159        self.api
160            .get(ApiPath::templated(&path, "/workflow/{workflowId}"))
161            .await
162    }
163
164    /// Get workflow status.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
169    pub async fn get_workflow_status(
170        &self,
171        workflow_id: &str,
172        include_output: bool,
173        include_variables: bool,
174    ) -> Result<Workflow> {
175        let path = format!(
176            "/workflow/{workflow_id}/status?includeOutput={include_output}&includeVariables={include_variables}"
177        );
178        self.api
179            .get(ApiPath::templated(&path, "/workflow/{workflowId}/status"))
180            .await
181    }
182
183    /// Terminate a running workflow.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
188    pub async fn terminate_workflow(
189        &self,
190        workflow_id: &str,
191        reason: Option<&str>,
192        trigger_failure_workflow: bool,
193    ) -> Result<()> {
194        let mut path =
195            format!("/workflow/{workflow_id}?triggerFailureWorkflow={trigger_failure_workflow}");
196
197        if let Some(r) = reason {
198            let _ = write!(path, "&reason={}", urlencoding::encode(r));
199        }
200
201        self.api
202            .delete_no_content(ApiPath::templated(&path, "/workflow/{workflowId}"))
203            .await
204    }
205
206    /// Pause a running workflow.
207    ///
208    /// # Errors
209    ///
210    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
211    pub async fn pause_workflow(&self, workflow_id: &str) -> Result<()> {
212        let path = format!("/workflow/{workflow_id}/pause");
213        let _: serde_json::Value = self
214            .api
215            .put(
216                ApiPath::templated(&path, "/workflow/{workflowId}/pause"),
217                &serde_json::Value::Null,
218            )
219            .await?;
220        Ok(())
221    }
222
223    /// Resume a paused workflow.
224    ///
225    /// # Errors
226    ///
227    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
228    pub async fn resume_workflow(&self, workflow_id: &str) -> Result<()> {
229        let path = format!("/workflow/{workflow_id}/resume");
230        let _: serde_json::Value = self
231            .api
232            .put(
233                ApiPath::templated(&path, "/workflow/{workflowId}/resume"),
234                &serde_json::Value::Null,
235            )
236            .await?;
237        Ok(())
238    }
239
240    /// Retry a failed workflow.
241    ///
242    /// # Errors
243    ///
244    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
245    pub async fn retry_workflow(
246        &self,
247        workflow_id: &str,
248        resume_subworkflow_tasks: bool,
249    ) -> Result<()> {
250        let path = format!(
251            "/workflow/{workflow_id}/retry?resumeSubworkflowTasks={resume_subworkflow_tasks}"
252        );
253        let _: serde_json::Value = self
254            .api
255            .post(
256                ApiPath::templated(&path, "/workflow/{workflowId}/retry"),
257                &serde_json::Value::Null,
258            )
259            .await?;
260        Ok(())
261    }
262
263    /// Restart a workflow from the beginning.
264    ///
265    /// # Errors
266    ///
267    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
268    pub async fn restart_workflow(&self, workflow_id: &str, use_latest_def: bool) -> Result<()> {
269        let path = format!("/workflow/{workflow_id}/restart?useLatestDefinitions={use_latest_def}");
270        let _: serde_json::Value = self
271            .api
272            .post(
273                ApiPath::templated(&path, "/workflow/{workflowId}/restart"),
274                &serde_json::Value::Null,
275            )
276            .await?;
277        Ok(())
278    }
279
280    /// Rerun a workflow from a specific task.
281    ///
282    /// # Errors
283    ///
284    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
285    pub async fn rerun_workflow(
286        &self,
287        workflow_id: &str,
288        rerun_from_task_id: &str,
289        task_input: Option<HashMap<String, serde_json::Value>>,
290        workflow_input: Option<HashMap<String, serde_json::Value>>,
291    ) -> Result<String> {
292        #[derive(serde::Serialize)]
293        #[serde(rename_all = "camelCase")]
294        struct RerunRequest {
295            re_run_from_task_id: String,
296            #[serde(skip_serializing_if = "Option::is_none")]
297            task_input: Option<HashMap<String, serde_json::Value>>,
298            #[serde(skip_serializing_if = "Option::is_none")]
299            workflow_input: Option<HashMap<String, serde_json::Value>>,
300        }
301
302        let path = format!("/workflow/{workflow_id}/rerun");
303
304        let request = RerunRequest {
305            re_run_from_task_id: rerun_from_task_id.to_owned(),
306            task_input,
307            workflow_input,
308        };
309
310        self.api
311            .post(
312                ApiPath::templated(&path, "/workflow/{workflowId}/rerun"),
313                &request,
314            )
315            .await
316    }
317
318    /// Update workflow variables.
319    ///
320    /// # Errors
321    ///
322    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
323    pub async fn update_variables(
324        &self,
325        workflow_id: &str,
326        variables: HashMap<String, serde_json::Value>,
327    ) -> Result<Workflow> {
328        let path = format!("/workflow/{workflow_id}/variables");
329        self.api
330            .post(
331                ApiPath::templated(&path, "/workflow/{workflowId}/variables"),
332                &variables,
333            )
334            .await
335    }
336
337    /// Skip a task in a running workflow.
338    ///
339    /// # Errors
340    ///
341    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
342    pub async fn skip_task(&self, workflow_id: &str, task_reference_name: &str) -> Result<()> {
343        // Kept as `{}` rather than a unit struct: serde serializes a unit struct as JSON `null`,
344        // but the server expects an empty JSON object body here.
345        #[expect(clippy::empty_structs_with_brackets)]
346        #[derive(serde::Serialize)]
347        struct SkipRequest {}
348
349        let path = format!("/workflow/{workflow_id}/skiptask/{task_reference_name}");
350
351        let _: serde_json::Value = self
352            .api
353            .put(
354                ApiPath::templated(&path, "/workflow/{workflowId}/skiptask/{taskRefName}"),
355                &SkipRequest {},
356            )
357            .await?;
358        Ok(())
359    }
360
361    /// Search for workflows.
362    ///
363    /// # Errors
364    ///
365    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
366    pub async fn search_workflows(
367        &self,
368        query: Option<&str>,
369        free_text: Option<&str>,
370        start: i32,
371        size: i32,
372    ) -> Result<SearchResult<Workflow>> {
373        let mut params = vec![("start", start.to_string()), ("size", size.to_string())];
374
375        if let Some(q) = query {
376            params.push(("query", q.to_owned()));
377        }
378        if let Some(ft) = free_text {
379            params.push(("freeText", ft.to_owned()));
380        }
381
382        let params: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
383
384        self.api.get_with_params("/workflow/search", &params).await
385    }
386
387    /// Search for workflows V2 (returns full workflow objects).
388    ///
389    /// # Errors
390    ///
391    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
392    pub async fn search_workflows_v2(
393        &self,
394        query: Option<&str>,
395        free_text: Option<&str>,
396        start: i32,
397        size: i32,
398    ) -> Result<SearchResult<Workflow>> {
399        let mut params = vec![("start", start.to_string()), ("size", size.to_string())];
400
401        if let Some(q) = query {
402            params.push(("query", q.to_owned()));
403        }
404        if let Some(ft) = free_text {
405            params.push(("freeText", ft.to_owned()));
406        }
407
408        let params: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
409
410        self.api
411            .get_with_params("/workflow/search-v2", &params)
412            .await
413    }
414
415    /// Skip a task from workflow (alias for `skip_task`).
416    ///
417    /// # Errors
418    ///
419    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
420    pub async fn skip_task_from_workflow(
421        &self,
422        workflow_id: &str,
423        task_reference_name: &str,
424    ) -> Result<()> {
425        self.skip_task(workflow_id, task_reference_name).await
426    }
427
428    /// Bulk pause workflows.
429    ///
430    /// # Errors
431    ///
432    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
433    pub async fn pause_workflows(
434        &self,
435        workflow_ids: &[String],
436    ) -> Result<HashMap<String, serde_json::Value>> {
437        self.api.put("/workflow/bulk/pause", workflow_ids).await
438    }
439
440    /// Bulk resume workflows.
441    ///
442    /// # Errors
443    ///
444    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
445    pub async fn resume_workflows(
446        &self,
447        workflow_ids: &[String],
448    ) -> Result<HashMap<String, serde_json::Value>> {
449        self.api.put("/workflow/bulk/resume", workflow_ids).await
450    }
451
452    /// Bulk restart workflows.
453    ///
454    /// # Errors
455    ///
456    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
457    pub async fn restart_workflows(
458        &self,
459        workflow_ids: &[String],
460        use_latest_def: bool,
461    ) -> Result<HashMap<String, serde_json::Value>> {
462        let path = format!("/workflow/bulk/restart?useLatestDefinitions={use_latest_def}");
463        self.api
464            .post(
465                ApiPath::templated(&path, "/workflow/bulk/restart"),
466                workflow_ids,
467            )
468            .await
469    }
470
471    /// Bulk retry workflows.
472    ///
473    /// # Errors
474    ///
475    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
476    pub async fn retry_workflows(
477        &self,
478        workflow_ids: &[String],
479    ) -> Result<HashMap<String, serde_json::Value>> {
480        self.api.post("/workflow/bulk/retry", workflow_ids).await
481    }
482
483    /// Bulk terminate workflows.
484    ///
485    /// # Errors
486    ///
487    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
488    pub async fn terminate_workflows(
489        &self,
490        workflow_ids: &[String],
491        reason: Option<&str>,
492    ) -> Result<HashMap<String, serde_json::Value>> {
493        let mut path = "/workflow/bulk/terminate".to_owned();
494        if let Some(r) = reason {
495            let _ = write!(path, "?reason={}", urlencoding::encode(r));
496        }
497        self.api
498            .post(
499                ApiPath::templated(&path, "/workflow/bulk/terminate"),
500                workflow_ids,
501            )
502            .await
503    }
504
505    /// Get running workflows by name.
506    ///
507    /// # Errors
508    ///
509    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
510    pub async fn get_running_workflows(
511        &self,
512        workflow_name: &str,
513        version: Option<i32>,
514        start_time: Option<i64>,
515        end_time: Option<i64>,
516    ) -> Result<Vec<String>> {
517        let mut path = format!("/workflow/running/{workflow_name}");
518
519        let mut params = vec![];
520        let version_str;
521        let start_str;
522        let end_str;
523
524        if let Some(v) = version {
525            version_str = v.to_string();
526            params.push(("version", version_str.as_str()));
527        }
528        if let Some(s) = start_time {
529            start_str = s.to_string();
530            params.push(("startTime", start_str.as_str()));
531        }
532        if let Some(e) = end_time {
533            end_str = e.to_string();
534            params.push(("endTime", end_str.as_str()));
535        }
536
537        if !params.is_empty() {
538            path.push('?');
539            path.push_str(
540                &params
541                    .into_iter()
542                    .map(|(k, v)| format!("{k}={v}"))
543                    .collect::<Vec<_>>()
544                    .join("&"),
545            );
546        }
547
548        self.api
549            .get(ApiPath::templated(
550                &path,
551                "/workflow/running/{workflowName}",
552            ))
553            .await
554    }
555
556    /// Delete a workflow execution.
557    ///
558    /// # Errors
559    ///
560    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
561    pub async fn delete_workflow(&self, workflow_id: &str, archive: bool) -> Result<()> {
562        let path = format!("/workflow/{workflow_id}?archiveWorkflow={archive}");
563        self.api
564            .delete_no_content(ApiPath::templated(&path, "/workflow/{workflowId}"))
565            .await
566    }
567
568    /// Test a workflow (dry run).
569    ///
570    /// # Errors
571    ///
572    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
573    pub async fn test_workflow(&self, request: &TestWorkflowRequest) -> Result<Workflow> {
574        self.api.post("/workflow/test", request).await
575    }
576
577    /// Remove/delete a workflow.
578    ///
579    /// # Errors
580    ///
581    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
582    pub async fn remove_workflow(&self, workflow_id: &str) -> Result<()> {
583        self.delete_workflow(workflow_id, false).await
584    }
585
586    /// Get workflows by correlation IDs.
587    ///
588    /// # Errors
589    ///
590    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
591    pub async fn get_by_correlation_ids(
592        &self,
593        workflow_name: &str,
594        correlation_ids: &[String],
595        include_completed: bool,
596        include_tasks: bool,
597    ) -> Result<HashMap<String, Vec<Workflow>>> {
598        let path = format!(
599            "/workflow/{workflow_name}/correlated?includeClosed={include_completed}&includeTasks={include_tasks}"
600        );
601        self.api
602            .post(
603                ApiPath::templated(&path, "/workflow/{workflowName}/correlated"),
604                correlation_ids,
605            )
606            .await
607    }
608
609    /// Get workflows by correlation IDs in batch.
610    ///
611    /// # Errors
612    ///
613    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
614    pub async fn get_by_correlation_ids_in_batch(
615        &self,
616        batch_request: &CorrelationIdsSearchRequest,
617        include_completed: bool,
618        include_tasks: bool,
619    ) -> Result<HashMap<String, Vec<Workflow>>> {
620        let path = format!(
621            "/workflow/correlated/batch?includeClosed={include_completed}&includeTasks={include_tasks}"
622        );
623        self.api
624            .post(
625                ApiPath::templated(&path, "/workflow/correlated/batch"),
626                batch_request,
627            )
628            .await
629    }
630
631    /// Update workflow state.
632    ///
633    /// # Errors
634    ///
635    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
636    pub async fn update_state(
637        &self,
638        workflow_id: &str,
639        update_request: &WorkflowStateUpdate,
640        wait_until_task_ref_names: Option<&[String]>,
641        wait_for_seconds: Option<i32>,
642    ) -> Result<WorkflowRun> {
643        let mut path = format!("/workflow/{workflow_id}/state");
644        let mut params: Vec<String> = vec![];
645
646        if let Some(refs) = wait_until_task_ref_names {
647            for r in refs {
648                params.push(format!("waitUntilTaskRefNames={}", urlencoding::encode(r)));
649            }
650        }
651        if let Some(secs) = wait_for_seconds {
652            params.push(format!("waitForSeconds={secs}"));
653        }
654
655        if !params.is_empty() {
656            path.push('?');
657            path.push_str(&params.join("&"));
658        }
659
660        self.api
661            .post(
662                ApiPath::templated(&path, "/workflow/{workflowId}/state"),
663                update_request,
664            )
665            .await
666    }
667
668    /// Execute workflow with return strategy.
669    ///
670    /// # Errors
671    ///
672    /// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
673    pub async fn execute_workflow_with_return_strategy(
674        &self,
675        request: &StartWorkflowRequest,
676        request_id: Option<&str>,
677        wait_until_task_ref: Option<&str>,
678        wait_for_seconds: i32,
679        consistency: Option<&str>,
680        return_strategy: Option<&str>,
681    ) -> Result<SignalResponse> {
682        let mut path = format!(
683            "/workflow/execute/{}/{}",
684            request.name,
685            request.version.unwrap_or(1)
686        );
687
688        let mut params: Vec<String> = vec![];
689        params.push(format!("waitForSeconds={wait_for_seconds}"));
690
691        if let Some(rid) = request_id {
692            params.push(format!("requestId={}", urlencoding::encode(rid)));
693        }
694        if let Some(task_ref) = wait_until_task_ref {
695            params.push(format!(
696                "waitUntilTaskRef={}",
697                urlencoding::encode(task_ref)
698            ));
699        }
700        if let Some(c) = consistency {
701            params.push(format!("consistency={c}"));
702        }
703        if let Some(rs) = return_strategy {
704            params.push(format!("returnStrategy={rs}"));
705        }
706
707        if !params.is_empty() {
708            path.push('?');
709            path.push_str(&params.join("&"));
710        }
711
712        self.api
713            .post(
714                ApiPath::templated(&path, "/workflow/execute/{name}/{version}"),
715                request,
716            )
717            .await
718    }
719}
720
721/// Correlation IDs search request.
722#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
723#[serde(rename_all = "camelCase")]
724pub struct CorrelationIdsSearchRequest {
725    /// Correlation IDs to search for.
726    #[serde(default)]
727    pub correlation_ids: Vec<String>,
728
729    /// Workflow names to search in.
730    #[serde(default)]
731    pub workflow_names: Vec<String>,
732}
733
734impl CorrelationIdsSearchRequest {
735    /// Create a new request.
736    #[must_use]
737    pub fn new() -> Self {
738        Self::default()
739    }
740
741    /// Add correlation IDs.
742    #[must_use]
743    pub fn with_correlation_ids(mut self, ids: Vec<String>) -> Self {
744        self.correlation_ids = ids;
745        self
746    }
747
748    /// Add workflow names.
749    #[must_use]
750    pub fn with_workflow_names(mut self, names: Vec<String>) -> Self {
751        self.workflow_names = names;
752        self
753    }
754}
755
756/// Workflow state update request.
757#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
758#[serde(rename_all = "camelCase")]
759pub struct WorkflowStateUpdate {
760    /// Task reference name to update.
761    #[serde(skip_serializing_if = "Option::is_none")]
762    pub task_reference_name: Option<String>,
763
764    /// Variables to update.
765    #[serde(default)]
766    pub variables: HashMap<String, serde_json::Value>,
767
768    /// Task output.
769    #[serde(default)]
770    pub task_result: Option<crate::models::TaskResult>,
771}
772
773/// Workflow run result.
774#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
775#[serde(rename_all = "camelCase")]
776pub struct WorkflowRun {
777    /// Workflow ID.
778    #[serde(default)]
779    pub workflow_id: String,
780
781    /// Workflow status.
782    #[serde(default)]
783    pub status: crate::models::WorkflowStatus,
784
785    /// Output.
786    #[serde(default)]
787    pub output: HashMap<String, serde_json::Value>,
788
789    /// Variables.
790    #[serde(default)]
791    pub variables: HashMap<String, serde_json::Value>,
792
793    /// Tasks.
794    #[serde(default)]
795    pub tasks: Vec<crate::models::Task>,
796}
797
798/// Signal response.
799#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
800#[serde(rename_all = "camelCase")]
801pub struct SignalResponse {
802    /// Workflow ID.
803    #[serde(default)]
804    pub workflow_id: String,
805
806    /// Status.
807    #[serde(default)]
808    pub status: crate::models::WorkflowStatus,
809
810    /// Output.
811    #[serde(default)]
812    pub output: HashMap<String, serde_json::Value>,
813}
814
815/// Search result with pagination.
816#[derive(Debug, Clone, serde::Deserialize)]
817#[serde(rename_all = "camelCase")]
818pub struct SearchResult<T> {
819    /// Total number of hits.
820    pub total_hits: i64,
821
822    /// Results in this page.
823    pub results: Vec<T>,
824}
825
826/// One simulated task attempt for [`TestWorkflowRequest::with_mock_outputs`], matching the
827/// server's `WorkflowTestRequest.TaskMock` exactly (`status`/`output`/`executionTime`/
828/// `queueWaitTime`). Multiple entries for the same task reference simulate a retry sequence:
829/// the first entry is attempt 1, the second is attempt 2 if the workflow retries, and so on.
830#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
831#[serde(rename_all = "camelCase")]
832pub struct TaskMock {
833    /// Simulated task status for this attempt.
834    pub status: TaskResultStatus,
835
836    /// Simulated task output for this attempt.
837    #[serde(skip_serializing_if = "Option::is_none")]
838    pub output: Option<HashMap<String, serde_json::Value>>,
839
840    /// Simulated execution time in milliseconds -- useful for testing timeout handling.
841    #[serde(default)]
842    pub execution_time: i64,
843
844    /// Simulated queue wait time in milliseconds.
845    #[serde(default)]
846    pub queue_wait_time: i64,
847}
848
849impl TaskMock {
850    /// A mock `COMPLETED` attempt with the given output -- the common case.
851    #[must_use]
852    pub fn completed(output: HashMap<String, serde_json::Value>) -> Self {
853        Self {
854            status: TaskResultStatus::Completed,
855            output: Some(output),
856            execution_time: 0,
857            queue_wait_time: 0,
858        }
859    }
860
861    /// A mock attempt with an explicit status (e.g. to simulate a retryable failure before a
862    /// later `completed()` attempt succeeds).
863    #[must_use]
864    pub fn new(status: TaskResultStatus, output: HashMap<String, serde_json::Value>) -> Self {
865        Self {
866            status,
867            output: Some(output),
868            execution_time: 0,
869            queue_wait_time: 0,
870        }
871    }
872
873    /// Set the simulated execution time, for testing timeout-handling logic.
874    #[must_use]
875    pub fn with_execution_time(mut self, millis: i64) -> Self {
876        self.execution_time = millis;
877        self
878    }
879
880    /// Set the simulated queue wait time.
881    #[must_use]
882    pub fn with_queue_wait_time(mut self, millis: i64) -> Self {
883        self.queue_wait_time = millis;
884        self
885    }
886}
887
888/// Request for testing a workflow. Extends [`StartWorkflowRequest`]'s field set with test-only
889/// fields (`task_ref_to_mock_output`/`sub_workflow_test_request`), matching the server's
890/// `WorkflowTestRequest extends StartWorkflowRequest` exactly -- this crate doesn't have struct
891/// inheritance, so the shared fields are simply duplicated here rather than composed.
892#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
893#[serde(rename_all = "camelCase")]
894pub struct TestWorkflowRequest {
895    /// Workflow name.
896    pub name: String,
897
898    /// Workflow version.
899    #[serde(skip_serializing_if = "Option::is_none")]
900    pub version: Option<i32>,
901
902    /// Workflow input.
903    #[serde(default)]
904    pub input: HashMap<String, serde_json::Value>,
905
906    /// Correlation ID.
907    #[serde(skip_serializing_if = "Option::is_none")]
908    pub correlation_id: Option<String>,
909
910    /// Task to domain mapping.
911    #[serde(default)]
912    pub task_to_domain: HashMap<String, String>,
913
914    /// Workflow definition (optional, uses registered if not provided).
915    #[serde(skip_serializing_if = "Option::is_none")]
916    pub workflow_def: Option<WorkflowDef>,
917
918    /// External input payload storage path.
919    #[serde(skip_serializing_if = "Option::is_none")]
920    pub external_input_payload_storage_path: Option<String>,
921
922    /// Priority.
923    #[serde(default)]
924    pub priority: i32,
925
926    /// Task reference to mocked-attempt-sequence mapping. Each entry is a [`TaskMock`] list, not
927    /// a single output -- see [`TestWorkflowRequest::with_mock_output`]/
928    /// [`TestWorkflowRequest::with_mock_outputs`].
929    #[serde(default)]
930    pub task_ref_to_mock_output: HashMap<String, Vec<TaskMock>>,
931
932    /// Per-sub-workflow-task-reference test request, for mocking task outputs inside a
933    /// sub-workflow the same way as the top-level workflow.
934    #[serde(default)]
935    pub sub_workflow_test_request: HashMap<String, TestWorkflowRequest>,
936}
937
938impl TestWorkflowRequest {
939    /// Create a new test workflow request.
940    pub fn new(name: impl Into<String>) -> Self {
941        Self {
942            name: name.into(),
943            version: None,
944            input: HashMap::new(),
945            correlation_id: None,
946            task_to_domain: HashMap::new(),
947            workflow_def: None,
948            external_input_payload_storage_path: None,
949            priority: 0,
950            task_ref_to_mock_output: HashMap::new(),
951            sub_workflow_test_request: HashMap::new(),
952        }
953    }
954
955    /// Set version.
956    #[must_use]
957    pub fn with_version(mut self, version: i32) -> Self {
958        self.version = Some(version);
959        self
960    }
961
962    /// Set workflow definition.
963    #[must_use]
964    pub fn with_workflow_def(mut self, def: WorkflowDef) -> Self {
965        self.workflow_def = Some(def);
966        self
967    }
968
969    /// Set workflow input.
970    #[must_use]
971    pub fn with_input(mut self, input: HashMap<String, serde_json::Value>) -> Self {
972        self.input = input;
973        self
974    }
975
976    /// Set correlation ID.
977    #[must_use]
978    pub fn with_correlation_id(mut self, correlation_id: impl Into<String>) -> Self {
979        self.correlation_id = Some(correlation_id.into());
980        self
981    }
982
983    /// Set task-to-domain routing.
984    #[must_use]
985    pub fn with_task_to_domain(mut self, task_to_domain: HashMap<String, String>) -> Self {
986        self.task_to_domain = task_to_domain;
987        self
988    }
989
990    /// Set priority.
991    #[must_use]
992    pub fn with_priority(mut self, priority: i32) -> Self {
993        self.priority = priority;
994        self
995    }
996
997    /// Append a single `COMPLETED` mock attempt with `output` for `task_ref`. Calling this
998    /// multiple times for the same `task_ref` builds a retry sequence -- the attempt from the
999    /// first call runs first. For non-`COMPLETED` attempts (simulating a failure before a
1000    /// retry succeeds) or execution/queue-time simulation, use
1001    /// [`TestWorkflowRequest::with_mock_outputs`] with [`TaskMock`] directly.
1002    #[must_use]
1003    pub fn with_mock_output(
1004        mut self,
1005        task_ref: impl Into<String>,
1006        output: HashMap<String, serde_json::Value>,
1007    ) -> Self {
1008        self.task_ref_to_mock_output
1009            .entry(task_ref.into())
1010            .or_default()
1011            .push(TaskMock::completed(output));
1012        self
1013    }
1014
1015    /// Set the full mocked-attempt sequence for `task_ref`, replacing any previous mocks for it.
1016    #[must_use]
1017    pub fn with_mock_outputs(mut self, task_ref: impl Into<String>, mocks: Vec<TaskMock>) -> Self {
1018        self.task_ref_to_mock_output.insert(task_ref.into(), mocks);
1019        self
1020    }
1021
1022    /// Add a mock test request for the sub-workflow spawned at `task_ref`.
1023    #[must_use]
1024    pub fn with_sub_workflow_test_request(
1025        mut self,
1026        task_ref: impl Into<String>,
1027        request: TestWorkflowRequest,
1028    ) -> Self {
1029        self.sub_workflow_test_request
1030            .insert(task_ref.into(), request);
1031        self
1032    }
1033}
1034
1035#[cfg(test)]
1036mod tests {
1037    use super::*;
1038
1039    #[test]
1040    fn test_start_workflow_request() {
1041        let request = StartWorkflowRequest::new("test_workflow")
1042            .with_version(1)
1043            .with_input_value("key", "value");
1044
1045        assert_eq!(request.name, "test_workflow");
1046        assert_eq!(request.version, Some(1));
1047    }
1048
1049    #[test]
1050    fn test_test_workflow_request() {
1051        let mut mock_output = HashMap::new();
1052        mock_output.insert("result".to_owned(), serde_json::json!("success"));
1053
1054        let request = TestWorkflowRequest::new("test_workflow")
1055            .with_version(1)
1056            .with_mock_output("task_ref", mock_output);
1057
1058        assert_eq!(request.name, "test_workflow");
1059        assert!(request.task_ref_to_mock_output.contains_key("task_ref"));
1060        assert_eq!(request.task_ref_to_mock_output["task_ref"].len(), 1);
1061        assert_eq!(
1062            request.task_ref_to_mock_output["task_ref"][0].status,
1063            TaskResultStatus::Completed
1064        );
1065    }
1066
1067    #[test]
1068    fn test_mock_output_appends_a_retry_sequence() {
1069        let mut first_attempt = HashMap::new();
1070        first_attempt.insert("attempt".to_owned(), serde_json::json!(1));
1071        let mut second_attempt = HashMap::new();
1072        second_attempt.insert("attempt".to_owned(), serde_json::json!(2));
1073
1074        let request = TestWorkflowRequest::new("test_workflow")
1075            .with_mock_outputs(
1076                "flaky_ref",
1077                vec![TaskMock::new(TaskResultStatus::Failed, first_attempt)],
1078            )
1079            .with_mock_output("flaky_ref", second_attempt);
1080
1081        let mocks = &request.task_ref_to_mock_output["flaky_ref"];
1082        assert_eq!(mocks.len(), 2);
1083        assert_eq!(mocks[0].status, TaskResultStatus::Failed);
1084        assert_eq!(mocks[1].status, TaskResultStatus::Completed);
1085    }
1086
1087    #[test]
1088    fn test_test_workflow_request_serializes_with_correct_wire_keys() {
1089        let mut output = HashMap::new();
1090        output.insert("ok".to_owned(), serde_json::json!(true));
1091
1092        let request = TestWorkflowRequest::new("test_workflow")
1093            .with_input(HashMap::from([(
1094                "orderId".to_owned(),
1095                serde_json::json!("ORD-1"),
1096            )]))
1097            .with_mock_output("task_ref", output);
1098
1099        let json = serde_json::to_value(&request).unwrap();
1100        // `input`, not `workflowInput`; `taskRefToMockOutput` values are arrays, not objects.
1101        assert_eq!(json["input"]["orderId"], serde_json::json!("ORD-1"));
1102        assert!(json["taskRefToMockOutput"]["task_ref"].is_array());
1103        assert_eq!(
1104            json["taskRefToMockOutput"]["task_ref"][0]["status"],
1105            serde_json::json!("COMPLETED")
1106        );
1107    }
1108}