Skip to main content

conductor/models/
workflow.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 serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7use super::Task;
8
9/// Module for flexible timestamp deserialization (handles both i64 and ISO date strings).
10mod timestamp_deserializer {
11    use chrono::{DateTime, Utc};
12    use serde::{self, Deserialize, Deserializer};
13
14    /// Deserialize a timestamp that may be either i64 (epoch ms) or ISO 8601 string.
15    pub fn deserialize<'de, D>(deserializer: D) -> Result<i64, D::Error>
16    where
17        D: Deserializer<'de>,
18    {
19        #[derive(Deserialize)]
20        #[serde(untagged)]
21        enum TimestampOrString {
22            Timestamp(i64),
23            String(String),
24        }
25
26        match TimestampOrString::deserialize(deserializer)? {
27            TimestampOrString::Timestamp(ts) => Ok(ts),
28            TimestampOrString::String(s) => {
29                // Try to parse as ISO 8601 date string
30                DateTime::parse_from_rfc3339(&s)
31                    .map(|dt| dt.with_timezone(&Utc).timestamp_millis())
32                    .or_else(|_| {
33                        // Try alternative formats
34                        s.parse::<i64>()
35                    })
36                    .map_err(serde::de::Error::custom)
37            }
38        }
39    }
40}
41
42/// Module for flexible map deserialization (handles both maps and string representations).
43mod flexible_map_deserializer {
44    use serde::{self, Deserialize, Deserializer};
45    use std::collections::HashMap;
46
47    /// Deserialize a map that may be either a proper JSON map or a string representation.
48    pub fn deserialize<'de, D>(
49        deserializer: D,
50    ) -> Result<HashMap<String, serde_json::Value>, D::Error>
51    where
52        D: Deserializer<'de>,
53    {
54        #[derive(Deserialize)]
55        #[serde(untagged)]
56        enum MapOrString {
57            Map(HashMap<String, serde_json::Value>),
58            #[expect(dead_code)]
59            String(String),
60        }
61
62        match MapOrString::deserialize(deserializer)? {
63            MapOrString::Map(map) => Ok(map),
64            MapOrString::String(_) => {
65                // Return empty map if it's a string representation
66                // The string is usually something like "{input=test_value}" which is not valid JSON
67                Ok(HashMap::new())
68            }
69        }
70    }
71}
72
73/// Module for flexible `Vec<Task>` deserialization (handles both arrays and string representations).
74mod flexible_tasks_deserializer {
75    use super::Task;
76    use serde::{self, Deserialize, Deserializer};
77
78    /// Deserialize tasks that may be either a proper array or a string representation.
79    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Task>, D::Error>
80    where
81        D: Deserializer<'de>,
82    {
83        #[derive(Deserialize)]
84        #[serde(untagged)]
85        enum VecOrString {
86            Vec(Vec<Task>),
87            #[expect(dead_code)]
88            String(String),
89        }
90
91        match VecOrString::deserialize(deserializer)? {
92            VecOrString::Vec(vec) => Ok(vec),
93            VecOrString::String(_) => {
94                // Return empty vec if it's a string representation from search API
95                Ok(Vec::new())
96            }
97        }
98    }
99}
100
101/// Module for flexible `Vec<String>` deserialization (handles both arrays and string representations).
102mod flexible_string_vec_deserializer {
103    use serde::{self, Deserialize, Deserializer};
104
105    /// Deserialize string vec that may be either a proper array or a string representation.
106    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
107    where
108        D: Deserializer<'de>,
109    {
110        #[derive(Deserialize)]
111        #[serde(untagged)]
112        enum VecOrString {
113            Vec(Vec<String>),
114            Single(String),
115        }
116
117        match VecOrString::deserialize(deserializer)? {
118            VecOrString::Vec(vec) => Ok(vec),
119            VecOrString::Single(s) => {
120                // Return single-element vec if it's a string from search API
121                if s.is_empty() {
122                    Ok(Vec::new())
123                } else {
124                    Ok(vec![s])
125                }
126            }
127        }
128    }
129}
130
131/// Module for flexible `HashMap`<String, String> deserialization.
132mod flexible_string_map_deserializer {
133    use serde::{self, Deserialize, Deserializer};
134    use std::collections::HashMap;
135
136    /// Deserialize string map that may be either a proper map or a string representation.
137    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error>
138    where
139        D: Deserializer<'de>,
140    {
141        #[derive(Deserialize)]
142        #[serde(untagged)]
143        enum MapOrString {
144            Map(HashMap<String, String>),
145            #[expect(dead_code)]
146            String(String),
147        }
148
149        match MapOrString::deserialize(deserializer)? {
150            MapOrString::Map(map) => Ok(map),
151            MapOrString::String(_) => {
152                // Return empty map if it's a string representation from search API
153                Ok(HashMap::new())
154            }
155        }
156    }
157}
158
159/// Workflow execution status.
160#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
162pub enum WorkflowStatus {
163    /// Workflow is running.
164    #[default]
165    Running,
166    /// Workflow completed successfully.
167    Completed,
168    /// Workflow failed.
169    Failed,
170    /// Workflow timed out.
171    TimedOut,
172    /// Workflow was terminated.
173    Terminated,
174    /// Workflow is paused.
175    Paused,
176}
177
178/// A workflow execution instance.
179#[derive(Debug, Clone, Default, Serialize, Deserialize)]
180#[serde(rename_all = "camelCase")]
181pub struct Workflow {
182    /// Unique workflow ID.
183    #[serde(default)]
184    pub workflow_id: String,
185
186    /// Workflow type/name.
187    #[serde(default)]
188    pub workflow_name: String,
189
190    /// Workflow version.
191    #[serde(default)]
192    pub workflow_version: i32,
193
194    /// Workflow status.
195    #[serde(default)]
196    pub status: WorkflowStatus,
197
198    /// Workflow input (may be empty if returned as string from search API).
199    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
200    pub input: HashMap<String, serde_json::Value>,
201
202    /// Workflow output (may be empty if returned as string from search API).
203    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
204    pub output: HashMap<String, serde_json::Value>,
205
206    /// Correlation ID.
207    #[serde(skip_serializing_if = "Option::is_none")]
208    pub correlation_id: Option<String>,
209
210    /// Tasks in this workflow execution (may be empty from search API).
211    #[serde(default, deserialize_with = "flexible_tasks_deserializer::deserialize")]
212    pub tasks: Vec<Task>,
213
214    /// Parent workflow ID (if this is a subworkflow).
215    #[serde(skip_serializing_if = "Option::is_none")]
216    pub parent_workflow_id: Option<String>,
217
218    /// Parent workflow task ID.
219    #[serde(skip_serializing_if = "Option::is_none")]
220    pub parent_workflow_task_id: Option<String>,
221
222    /// Start time (epoch ms or ISO 8601 string).
223    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
224    pub start_time: i64,
225
226    /// End time (epoch ms or ISO 8601 string).
227    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
228    pub end_time: i64,
229
230    /// Update time (epoch ms or ISO 8601 string).
231    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
232    pub update_time: i64,
233
234    /// Created time (epoch ms or ISO 8601 string).
235    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
236    pub create_time: i64,
237
238    /// Created by.
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub created_by: Option<String>,
241
242    /// Updated by.
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub updated_by: Option<String>,
245
246    /// Reason for incompletion (if failed/terminated).
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub reason_for_incompletion: Option<String>,
249
250    /// Workflow variables.
251    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
252    pub variables: HashMap<String, serde_json::Value>,
253
254    /// External input payload storage path.
255    #[serde(skip_serializing_if = "Option::is_none")]
256    pub external_input_payload_storage_path: Option<String>,
257
258    /// External output payload storage path.
259    #[serde(skip_serializing_if = "Option::is_none")]
260    pub external_output_payload_storage_path: Option<String>,
261
262    /// Priority.
263    #[serde(default)]
264    pub priority: i32,
265
266    /// Owner app.
267    #[serde(skip_serializing_if = "Option::is_none")]
268    pub owner_app: Option<String>,
269
270    /// Task to domain mapping.
271    #[serde(
272        default,
273        deserialize_with = "flexible_string_map_deserializer::deserialize"
274    )]
275    pub task_to_domain: HashMap<String, String>,
276
277    /// Workflow definition.
278    #[serde(skip_serializing_if = "Option::is_none")]
279    pub workflow_definition: Option<super::WorkflowDef>,
280
281    /// Failed reference task names.
282    #[serde(
283        default,
284        deserialize_with = "flexible_string_vec_deserializer::deserialize"
285    )]
286    pub failed_reference_task_names: Vec<String>,
287
288    /// Failed task names.
289    #[serde(
290        default,
291        deserialize_with = "flexible_string_vec_deserializer::deserialize"
292    )]
293    pub failed_task_names: Vec<String>,
294
295    /// Last retried time (epoch ms or ISO 8601 string).
296    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
297    pub last_retried_time: i64,
298
299    /// Event.
300    #[serde(skip_serializing_if = "Option::is_none")]
301    pub event: Option<String>,
302}
303
304impl Workflow {
305    /// Check if workflow is terminal (completed, failed, terminated, timed out).
306    #[must_use]
307    pub fn is_terminal(&self) -> bool {
308        matches!(
309            self.status,
310            WorkflowStatus::Completed
311                | WorkflowStatus::Failed
312                | WorkflowStatus::Terminated
313                | WorkflowStatus::TimedOut
314        )
315    }
316
317    /// Check if workflow is running (not terminal).
318    #[must_use]
319    pub fn is_running(&self) -> bool {
320        !self.is_terminal()
321    }
322
323    /// Check if workflow succeeded.
324    #[must_use]
325    pub fn is_successful(&self) -> bool {
326        self.status == WorkflowStatus::Completed
327    }
328
329    /// Get an output value.
330    #[must_use]
331    pub fn get_output<T>(&self, key: &str) -> Option<T>
332    where
333        T: serde::de::DeserializeOwned,
334    {
335        let v = self.output.get(key)?;
336        serde_json::from_value(v.clone()).ok()
337    }
338
339    /// Get output as string.
340    #[must_use]
341    pub fn get_output_string(&self, key: &str) -> Option<String> {
342        self.output.get(key).map(|v| {
343            if let serde_json::Value::String(s) = v {
344                s.clone()
345            } else {
346                v.to_string()
347            }
348        })
349    }
350
351    /// Get a variable value.
352    #[must_use]
353    pub fn get_variable<T>(&self, key: &str) -> Option<T>
354    where
355        T: serde::de::DeserializeOwned,
356    {
357        let v = self.variables.get(key)?;
358        serde_json::from_value(v.clone()).ok()
359    }
360}
361
362/// Request to start a workflow.
363#[derive(Debug, Clone, Default, Serialize, Deserialize)]
364#[serde(rename_all = "camelCase")]
365pub struct StartWorkflowRequest {
366    /// Workflow name.
367    pub name: String,
368
369    /// Workflow version (optional, uses latest if not specified).
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub version: Option<i32>,
372
373    /// Workflow input.
374    #[serde(default)]
375    pub input: HashMap<String, serde_json::Value>,
376
377    /// Correlation ID.
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub correlation_id: Option<String>,
380
381    /// Task to domain mapping.
382    #[serde(default)]
383    pub task_to_domain: HashMap<String, String>,
384
385    /// Workflow definition (for dynamic workflows).
386    #[serde(skip_serializing_if = "Option::is_none")]
387    pub workflow_def: Option<super::WorkflowDef>,
388
389    /// External input payload storage path.
390    #[serde(skip_serializing_if = "Option::is_none")]
391    pub external_input_payload_storage_path: Option<String>,
392
393    /// Priority.
394    #[serde(default)]
395    pub priority: i32,
396}
397
398impl StartWorkflowRequest {
399    /// Create a new start workflow request.
400    pub fn new(name: impl Into<String>) -> Self {
401        Self {
402            name: name.into(),
403            ..Default::default()
404        }
405    }
406
407    /// Set workflow version.
408    #[must_use]
409    pub fn with_version(mut self, version: i32) -> Self {
410        self.version = Some(version);
411        self
412    }
413
414    /// Set workflow input.
415    #[must_use]
416    pub fn with_input(mut self, input: HashMap<String, serde_json::Value>) -> Self {
417        self.input = input;
418        self
419    }
420
421    /// Add a single input value.
422    #[must_use]
423    pub fn with_input_value(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
424        self.input.insert(
425            key.into(),
426            serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
427        );
428        self
429    }
430
431    /// Set correlation ID.
432    #[must_use]
433    pub fn with_correlation_id(mut self, id: impl Into<String>) -> Self {
434        self.correlation_id = Some(id.into());
435        self
436    }
437
438    /// Set priority.
439    #[must_use]
440    pub fn with_priority(mut self, priority: i32) -> Self {
441        self.priority = priority;
442        self
443    }
444
445    /// Set task to domain mapping.
446    #[must_use]
447    pub fn with_task_to_domain(mut self, mapping: HashMap<String, String>) -> Self {
448        self.task_to_domain = mapping;
449        self
450    }
451
452    /// Set workflow definition (for dynamic workflows).
453    #[must_use]
454    pub fn with_workflow_def(mut self, def: super::WorkflowDef) -> Self {
455        self.workflow_def = Some(def);
456        self
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    #[test]
465    fn test_workflow_deserialization() {
466        let json = r#"{
467            "workflowId": "wf-123",
468            "workflowName": "test_workflow",
469            "status": "RUNNING",
470            "input": {"key": "value"}
471        }"#;
472
473        let wf: Workflow = serde_json::from_str(json).unwrap();
474        assert_eq!(wf.workflow_id, "wf-123");
475        assert_eq!(wf.workflow_name, "test_workflow");
476        assert_eq!(wf.status, WorkflowStatus::Running);
477    }
478
479    #[test]
480    fn test_workflow_is_terminal() {
481        let wf = Workflow {
482            status: WorkflowStatus::Running,
483            ..Default::default()
484        };
485        assert!(!wf.is_terminal());
486
487        let wf = Workflow {
488            status: WorkflowStatus::Completed,
489            ..Default::default()
490        };
491        assert!(wf.is_terminal());
492        assert!(wf.is_successful());
493
494        let wf = Workflow {
495            status: WorkflowStatus::Failed,
496            ..Default::default()
497        };
498        assert!(wf.is_terminal());
499        assert!(!wf.is_successful());
500    }
501
502    #[test]
503    fn test_start_workflow_request() {
504        let req = StartWorkflowRequest::new("my_workflow")
505            .with_version(1)
506            .with_input_value("name", "test")
507            .with_correlation_id("corr-123");
508
509        assert_eq!(req.name, "my_workflow");
510        assert_eq!(req.version, Some(1));
511        assert!(req.input.contains_key("name"));
512        assert_eq!(req.correlation_id, Some("corr-123".to_owned()));
513    }
514}