Skip to main content

conductor/models/
task.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
7/// Module for flexible timestamp deserialization (handles both i64 and ISO date strings).
8mod timestamp_deserializer {
9    use chrono::{DateTime, Utc};
10    use serde::{self, Deserialize, Deserializer};
11
12    /// Deserialize a timestamp that may be either i64 (epoch ms) or ISO 8601 string.
13    pub fn deserialize<'de, D>(deserializer: D) -> Result<i64, D::Error>
14    where
15        D: Deserializer<'de>,
16    {
17        #[derive(Deserialize)]
18        #[serde(untagged)]
19        enum TimestampOrString {
20            Timestamp(i64),
21            String(String),
22        }
23
24        match TimestampOrString::deserialize(deserializer)? {
25            TimestampOrString::Timestamp(ts) => Ok(ts),
26            TimestampOrString::String(s) => {
27                // Try to parse as ISO 8601 date string
28                DateTime::parse_from_rfc3339(&s)
29                    .map(|dt| dt.with_timezone(&Utc).timestamp_millis())
30                    .or_else(|_| {
31                        // Try alternative formats
32                        s.parse::<i64>()
33                    })
34                    .map_err(serde::de::Error::custom)
35            }
36        }
37    }
38}
39
40/// Status of a task.
41#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
43pub enum TaskStatus {
44    /// Task is scheduled but not yet picked up.
45    #[default]
46    Scheduled,
47    /// Task is currently being executed.
48    InProgress,
49    /// Task completed successfully.
50    Completed,
51    /// Task failed.
52    Failed,
53    /// Task failed with terminal error (no retry).
54    FailedWithTerminalError,
55    /// Task was canceled.
56    Canceled,
57    /// Task was skipped.
58    Skipped,
59    /// Task timed out.
60    TimedOut,
61}
62
63/// A task in a Conductor workflow.
64#[derive(Clone, Default, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct Task {
67    /// Unique task ID.
68    #[serde(default)]
69    pub task_id: String,
70
71    /// Task type/definition name.
72    #[serde(default)]
73    pub task_type: String,
74
75    /// Reference name within the workflow.
76    #[serde(default)]
77    pub reference_task_name: String,
78
79    /// Task status.
80    #[serde(default)]
81    pub status: TaskStatus,
82
83    /// Input data for the task.
84    #[serde(default)]
85    pub input_data: HashMap<String, serde_json::Value>,
86
87    /// Output data from the task.
88    #[serde(default)]
89    pub output_data: HashMap<String, serde_json::Value>,
90
91    /// Workflow instance ID this task belongs to.
92    #[serde(default)]
93    pub workflow_instance_id: String,
94
95    /// Workflow type/name.
96    #[serde(default)]
97    pub workflow_type: String,
98
99    /// Task definition name.
100    #[serde(default)]
101    pub task_def_name: String,
102
103    /// Current retry count.
104    #[serde(default)]
105    pub retry_count: i32,
106
107    /// Poll count (for long-running tasks).
108    #[serde(default)]
109    pub poll_count: i32,
110
111    /// Worker that picked up this task.
112    #[serde(default)]
113    pub worker_id: Option<String>,
114
115    /// Domain the task is running in.
116    #[serde(default)]
117    pub domain: Option<String>,
118
119    /// Scheduled time (epoch ms or ISO 8601 string).
120    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
121    pub scheduled_time: i64,
122
123    /// Start time (epoch ms or ISO 8601 string).
124    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
125    pub start_time: i64,
126
127    /// End time (epoch ms or ISO 8601 string).
128    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
129    pub end_time: i64,
130
131    /// Update time (epoch ms or ISO 8601 string).
132    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
133    pub update_time: i64,
134
135    /// Queue wait time (ms).
136    #[serde(default)]
137    pub queue_wait_time: i64,
138
139    /// Callback after seconds (for `IN_PROGRESS` tasks).
140    #[serde(default)]
141    pub callback_after_seconds: i64,
142
143    /// Response timeout seconds.
144    #[serde(default)]
145    pub response_timeout_seconds: i64,
146
147    /// Execution namespace ID.
148    #[serde(default)]
149    pub execution_name_space: Option<String>,
150
151    /// Isolation group ID.
152    #[serde(default)]
153    pub isolation_group_id: Option<String>,
154
155    /// Correlation ID.
156    #[serde(default)]
157    pub correlation_id: Option<String>,
158
159    /// Reason for failure (if failed).
160    #[serde(default)]
161    pub reason_for_incompletion: Option<String>,
162
163    /// External input payload storage path.
164    #[serde(default)]
165    pub external_input_payload_storage_path: Option<String>,
166
167    /// External output payload storage path.
168    #[serde(default)]
169    pub external_output_payload_storage_path: Option<String>,
170
171    /// Task execution logs.
172    #[serde(default)]
173    pub logs: Vec<TaskExecLog>,
174
175    /// Subworkflow ID (if this is a subworkflow task).
176    #[serde(default)]
177    pub sub_workflow_id: Option<String>,
178
179    /// Iteration count (for loop tasks).
180    #[serde(default)]
181    pub iteration: i32,
182
183    /// Server-resolved credential values for this poll, keyed by declared name. Read via
184    /// [`crate::agents::Credentials::from_task`] rather than directly. May contain secrets --
185    /// see the manual [`std::fmt::Debug`] impl below, which redacts values.
186    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
187    pub runtime_metadata: HashMap<String, String>,
188}
189
190impl std::fmt::Debug for Task {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        let mut runtime_metadata_keys: Vec<&str> =
193            self.runtime_metadata.keys().map(String::as_str).collect();
194        runtime_metadata_keys.sort_unstable();
195        f.debug_struct("Task")
196            .field("task_id", &self.task_id)
197            .field("task_type", &self.task_type)
198            .field("reference_task_name", &self.reference_task_name)
199            .field("status", &self.status)
200            .field("input_data", &self.input_data)
201            .field("output_data", &self.output_data)
202            .field("workflow_instance_id", &self.workflow_instance_id)
203            .field("workflow_type", &self.workflow_type)
204            .field("task_def_name", &self.task_def_name)
205            .field("retry_count", &self.retry_count)
206            .field("poll_count", &self.poll_count)
207            .field("worker_id", &self.worker_id)
208            .field("domain", &self.domain)
209            .field("scheduled_time", &self.scheduled_time)
210            .field("start_time", &self.start_time)
211            .field("end_time", &self.end_time)
212            .field("update_time", &self.update_time)
213            .field("queue_wait_time", &self.queue_wait_time)
214            .field("callback_after_seconds", &self.callback_after_seconds)
215            .field("response_timeout_seconds", &self.response_timeout_seconds)
216            .field("execution_name_space", &self.execution_name_space)
217            .field("isolation_group_id", &self.isolation_group_id)
218            .field("correlation_id", &self.correlation_id)
219            .field("reason_for_incompletion", &self.reason_for_incompletion)
220            .field(
221                "external_input_payload_storage_path",
222                &self.external_input_payload_storage_path,
223            )
224            .field(
225                "external_output_payload_storage_path",
226                &self.external_output_payload_storage_path,
227            )
228            .field("logs", &self.logs)
229            .field("sub_workflow_id", &self.sub_workflow_id)
230            .field("iteration", &self.iteration)
231            // Names only -- never the resolved values, which may be secrets.
232            .field("runtime_metadata_keys", &runtime_metadata_keys)
233            .finish()
234    }
235}
236
237impl Task {
238    /// Get a typed input value.
239    #[must_use]
240    pub fn get_input<T>(&self, key: &str) -> Option<T>
241    where
242        T: serde::de::DeserializeOwned,
243    {
244        let v = self.input_data.get(key)?;
245        serde_json::from_value(v.clone()).ok()
246    }
247
248    /// Get input as string.
249    #[must_use]
250    pub fn get_input_string(&self, key: &str) -> Option<String> {
251        self.input_data.get(key).map(|v| {
252            if let serde_json::Value::String(s) = v {
253                s.clone()
254            } else {
255                v.to_string()
256            }
257        })
258    }
259
260    /// Check if task is terminal (completed, failed, etc.)
261    #[must_use]
262    pub fn is_terminal(&self) -> bool {
263        matches!(
264            self.status,
265            TaskStatus::Completed
266                | TaskStatus::Failed
267                | TaskStatus::FailedWithTerminalError
268                | TaskStatus::Canceled
269                | TaskStatus::Skipped
270                | TaskStatus::TimedOut
271        )
272    }
273
274    /// Get task context for accessing task metadata.
275    ///
276    /// Provides convenient access to task ID, workflow ID, poll count, etc.
277    ///
278    /// # Example
279    ///
280    /// ```rust
281    /// use conductor::models::Task;
282    ///
283    /// fn process_task(task: &Task) {
284    ///     let ctx = task.context();
285    ///     
286    ///     println!("Task ID: {}", ctx.task_id());
287    ///     println!("Workflow ID: {}", ctx.workflow_instance_id());
288    ///     println!("Poll count: {}", ctx.poll_count());
289    ///     
290    ///     if ctx.is_first_poll() {
291    ///         println!("This is the first poll");
292    ///     }
293    /// }
294    /// ```
295    #[must_use]
296    pub fn context(&self) -> crate::worker::TaskContext {
297        crate::worker::TaskContext::from_task(self)
298    }
299
300    /// Get the task ID.
301    #[must_use]
302    pub fn task_id(&self) -> &str {
303        &self.task_id
304    }
305
306    /// Get the workflow instance ID.
307    #[must_use]
308    pub fn workflow_instance_id(&self) -> &str {
309        &self.workflow_instance_id
310    }
311
312    /// Get the poll count.
313    #[must_use]
314    pub fn poll_count(&self) -> i32 {
315        self.poll_count
316    }
317
318    /// Get the retry count.
319    #[must_use]
320    pub fn retry_count(&self) -> i32 {
321        self.retry_count
322    }
323
324    /// Check if this is the first poll (`poll_count` == 0).
325    #[must_use]
326    pub fn is_first_poll(&self) -> bool {
327        self.poll_count == 0
328    }
329
330    /// Check if this is a retry (`retry_count` > 0).
331    #[must_use]
332    pub fn is_retry(&self) -> bool {
333        self.retry_count > 0
334    }
335}
336
337/// Task execution log entry.
338#[derive(Debug, Clone, Default, Serialize, Deserialize)]
339#[serde(rename_all = "camelCase")]
340pub struct TaskExecLog {
341    /// Log message.
342    pub log: String,
343
344    /// Task ID.
345    pub task_id: String,
346
347    /// Created time (epoch ms).
348    pub created_time: i64,
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn test_task_deserialization() {
357        let json = r#"{
358            "taskId": "task-123",
359            "taskType": "simple_task",
360            "status": "IN_PROGRESS",
361            "inputData": {"name": "test"},
362            "workflowInstanceId": "wf-456"
363        }"#;
364
365        let task: Task = serde_json::from_str(json).unwrap();
366        assert_eq!(task.task_id, "task-123");
367        assert_eq!(task.task_type, "simple_task");
368        assert_eq!(task.status, TaskStatus::InProgress);
369        assert_eq!(task.get_input_string("name"), Some("test".to_owned()));
370    }
371
372    #[test]
373    fn test_task_debug_redacts_runtime_metadata_values() {
374        let task = Task {
375            runtime_metadata: HashMap::from([(
376                "GH_TOKEN".to_owned(),
377                "ghp_super_secret".to_owned(),
378            )]),
379            ..Default::default()
380        };
381
382        let debug = format!("{task:?}");
383        assert!(debug.contains("GH_TOKEN"));
384        assert!(!debug.contains("ghp_super_secret"));
385    }
386
387    #[test]
388    fn test_task_is_terminal() {
389        let task = Task {
390            status: TaskStatus::InProgress,
391            ..Default::default()
392        };
393        assert!(!task.is_terminal());
394
395        let task = Task {
396            status: TaskStatus::Completed,
397            ..Default::default()
398        };
399        assert!(task.is_terminal());
400
401        let task = Task {
402            status: TaskStatus::Failed,
403            ..Default::default()
404        };
405        assert!(task.is_terminal());
406    }
407}