1use 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#[derive(Clone)]
16pub struct WorkflowClient {
17 api: ApiClient,
18 events: EventDispatcher,
22}
23
24impl WorkflowClient {
25 #[must_use]
33 pub fn new(api: ApiClient) -> Self {
34 Self {
35 api,
36 events: EventDispatcher::default(),
37 }
38 }
39
40 #[must_use]
42 pub fn new_with_events(api: ApiClient, events: EventDispatcher) -> Self {
43 Self { api, events }
44 }
45
46 pub async fn start_workflow(&self, request: &StartWorkflowRequest) -> Result<String> {
52 debug!(
53 workflow_name = %request.name,
54 "Starting workflow"
55 );
56
57 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 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 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 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 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 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 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 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 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 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 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 pub async fn skip_task(&self, workflow_id: &str, task_reference_name: &str) -> Result<()> {
343 #[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 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", ¶ms).await
385 }
386
387 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", ¶ms)
412 .await
413 }
414
415 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 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 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 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 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 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 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 ¶ms
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 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 pub async fn test_workflow(&self, request: &TestWorkflowRequest) -> Result<Workflow> {
574 self.api.post("/workflow/test", request).await
575 }
576
577 pub async fn remove_workflow(&self, workflow_id: &str) -> Result<()> {
583 self.delete_workflow(workflow_id, false).await
584 }
585
586 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 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 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(¶ms.join("&"));
658 }
659
660 self.api
661 .post(
662 ApiPath::templated(&path, "/workflow/{workflowId}/state"),
663 update_request,
664 )
665 .await
666 }
667
668 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(¶ms.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#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
723#[serde(rename_all = "camelCase")]
724pub struct CorrelationIdsSearchRequest {
725 #[serde(default)]
727 pub correlation_ids: Vec<String>,
728
729 #[serde(default)]
731 pub workflow_names: Vec<String>,
732}
733
734impl CorrelationIdsSearchRequest {
735 #[must_use]
737 pub fn new() -> Self {
738 Self::default()
739 }
740
741 #[must_use]
743 pub fn with_correlation_ids(mut self, ids: Vec<String>) -> Self {
744 self.correlation_ids = ids;
745 self
746 }
747
748 #[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#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
758#[serde(rename_all = "camelCase")]
759pub struct WorkflowStateUpdate {
760 #[serde(skip_serializing_if = "Option::is_none")]
762 pub task_reference_name: Option<String>,
763
764 #[serde(default)]
766 pub variables: HashMap<String, serde_json::Value>,
767
768 #[serde(default)]
770 pub task_result: Option<crate::models::TaskResult>,
771}
772
773#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
775#[serde(rename_all = "camelCase")]
776pub struct WorkflowRun {
777 #[serde(default)]
779 pub workflow_id: String,
780
781 #[serde(default)]
783 pub status: crate::models::WorkflowStatus,
784
785 #[serde(default)]
787 pub output: HashMap<String, serde_json::Value>,
788
789 #[serde(default)]
791 pub variables: HashMap<String, serde_json::Value>,
792
793 #[serde(default)]
795 pub tasks: Vec<crate::models::Task>,
796}
797
798#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
800#[serde(rename_all = "camelCase")]
801pub struct SignalResponse {
802 #[serde(default)]
804 pub workflow_id: String,
805
806 #[serde(default)]
808 pub status: crate::models::WorkflowStatus,
809
810 #[serde(default)]
812 pub output: HashMap<String, serde_json::Value>,
813}
814
815#[derive(Debug, Clone, serde::Deserialize)]
817#[serde(rename_all = "camelCase")]
818pub struct SearchResult<T> {
819 pub total_hits: i64,
821
822 pub results: Vec<T>,
824}
825
826#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
831#[serde(rename_all = "camelCase")]
832pub struct TaskMock {
833 pub status: TaskResultStatus,
835
836 #[serde(skip_serializing_if = "Option::is_none")]
838 pub output: Option<HashMap<String, serde_json::Value>>,
839
840 #[serde(default)]
842 pub execution_time: i64,
843
844 #[serde(default)]
846 pub queue_wait_time: i64,
847}
848
849impl TaskMock {
850 #[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 #[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 #[must_use]
875 pub fn with_execution_time(mut self, millis: i64) -> Self {
876 self.execution_time = millis;
877 self
878 }
879
880 #[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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
893#[serde(rename_all = "camelCase")]
894pub struct TestWorkflowRequest {
895 pub name: String,
897
898 #[serde(skip_serializing_if = "Option::is_none")]
900 pub version: Option<i32>,
901
902 #[serde(default)]
904 pub input: HashMap<String, serde_json::Value>,
905
906 #[serde(skip_serializing_if = "Option::is_none")]
908 pub correlation_id: Option<String>,
909
910 #[serde(default)]
912 pub task_to_domain: HashMap<String, String>,
913
914 #[serde(skip_serializing_if = "Option::is_none")]
916 pub workflow_def: Option<WorkflowDef>,
917
918 #[serde(skip_serializing_if = "Option::is_none")]
920 pub external_input_payload_storage_path: Option<String>,
921
922 #[serde(default)]
924 pub priority: i32,
925
926 #[serde(default)]
930 pub task_ref_to_mock_output: HashMap<String, Vec<TaskMock>>,
931
932 #[serde(default)]
935 pub sub_workflow_test_request: HashMap<String, TestWorkflowRequest>,
936}
937
938impl TestWorkflowRequest {
939 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 #[must_use]
957 pub fn with_version(mut self, version: i32) -> Self {
958 self.version = Some(version);
959 self
960 }
961
962 #[must_use]
964 pub fn with_workflow_def(mut self, def: WorkflowDef) -> Self {
965 self.workflow_def = Some(def);
966 self
967 }
968
969 #[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 #[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 #[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 #[must_use]
992 pub fn with_priority(mut self, priority: i32) -> Self {
993 self.priority = priority;
994 self
995 }
996
997 #[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 #[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 #[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 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}