Skip to main content

conductor/models/
task_result.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/// Status of a task result.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
10pub enum TaskResultStatus {
11    /// Task completed successfully.
12    #[default]
13    Completed,
14    /// Task failed (may be retried).
15    Failed,
16    /// Task failed with terminal error (no retry).
17    FailedWithTerminalError,
18    /// Task is still in progress.
19    InProgress,
20    /// Task was canceled.
21    Canceled,
22}
23
24/// Result of a task execution.
25#[derive(Debug, Clone, Default, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27pub struct TaskResult {
28    /// Task ID.
29    pub task_id: String,
30
31    /// Workflow instance ID.
32    pub workflow_instance_id: String,
33
34    /// Worker ID that executed the task.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub worker_id: Option<String>,
37
38    /// Task execution status.
39    pub status: TaskResultStatus,
40
41    /// Output data from the task.
42    #[serde(default)]
43    pub output_data: HashMap<String, serde_json::Value>,
44
45    /// Reason for failure (if failed).
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub reason_for_incompletion: Option<String>,
48
49    /// Callback after seconds (for `IN_PROGRESS` tasks).
50    #[serde(default)]
51    pub callback_after_seconds: i64,
52
53    /// Logs from task execution.
54    #[serde(default)]
55    pub logs: Vec<TaskExecLog>,
56
57    /// External output payload storage path.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub external_output_payload_storage_path: Option<String>,
60
61    /// Subworkflow ID (for subworkflow tasks).
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub sub_workflow_id: Option<String>,
64
65    /// Extend lease (keep-alive for long-running tasks).
66    #[serde(default)]
67    pub extend_lease: bool,
68}
69
70/// Task execution log entry.
71#[derive(Debug, Clone, Default, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub struct TaskExecLog {
74    /// Log message.
75    pub log: String,
76
77    /// Task ID.
78    #[serde(default)]
79    pub task_id: String,
80
81    /// Created time.
82    #[serde(default)]
83    pub created_time: i64,
84}
85
86impl TaskResult {
87    /// Create a new completed task result.
88    pub fn completed(task_id: impl Into<String>, workflow_instance_id: impl Into<String>) -> Self {
89        Self {
90            task_id: task_id.into(),
91            workflow_instance_id: workflow_instance_id.into(),
92            status: TaskResultStatus::Completed,
93            ..Default::default()
94        }
95    }
96
97    /// Create a new failed task result.
98    pub fn failed(
99        task_id: impl Into<String>,
100        workflow_instance_id: impl Into<String>,
101        reason: impl Into<String>,
102    ) -> Self {
103        Self {
104            task_id: task_id.into(),
105            workflow_instance_id: workflow_instance_id.into(),
106            status: TaskResultStatus::Failed,
107            reason_for_incompletion: Some(reason.into()),
108            ..Default::default()
109        }
110    }
111
112    /// Create an in-progress task result (for long-running tasks).
113    pub fn in_progress(
114        task_id: impl Into<String>,
115        workflow_instance_id: impl Into<String>,
116        callback_after_seconds: i64,
117    ) -> Self {
118        Self {
119            task_id: task_id.into(),
120            workflow_instance_id: workflow_instance_id.into(),
121            status: TaskResultStatus::InProgress,
122            callback_after_seconds,
123            ..Default::default()
124        }
125    }
126
127    /// Set worker ID.
128    #[must_use]
129    pub fn with_worker_id(mut self, worker_id: impl Into<String>) -> Self {
130        self.worker_id = Some(worker_id.into());
131        self
132    }
133
134    /// Set output data.
135    #[must_use]
136    pub fn with_output(mut self, output: HashMap<String, serde_json::Value>) -> Self {
137        self.output_data = output;
138        self
139    }
140
141    /// Set a single output value.
142    #[must_use]
143    pub fn with_output_value(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
144        self.output_data.insert(
145            key.into(),
146            serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
147        );
148        self
149    }
150
151    /// Add a log entry.
152    #[must_use]
153    pub fn with_log(mut self, log: impl Into<String>) -> Self {
154        self.logs.push(TaskExecLog {
155            log: log.into(),
156            task_id: self.task_id.clone(),
157            created_time: chrono::Utc::now().timestamp_millis(),
158        });
159        self
160    }
161
162    /// Set failure reason.
163    #[must_use]
164    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
165        self.reason_for_incompletion = Some(reason.into());
166        self
167    }
168
169    /// Extend the lease (for long-running tasks).
170    #[must_use]
171    pub fn with_extend_lease(mut self, extend: bool) -> Self {
172        self.extend_lease = extend;
173        self
174    }
175}
176
177/// Task in progress marker for long-running tasks.
178///
179/// Return this from a worker to indicate the task is still processing
180/// and should be polled again after `callback_after_seconds`.
181#[derive(Debug, Clone)]
182pub struct TaskInProgress {
183    /// Seconds until the task should be polled again.
184    pub callback_after_seconds: i64,
185
186    /// Intermediate output data.
187    pub output: HashMap<String, serde_json::Value>,
188}
189
190impl TaskInProgress {
191    /// Create a new task in progress marker.
192    #[must_use]
193    pub fn new(callback_after_seconds: i64) -> Self {
194        Self {
195            callback_after_seconds,
196            output: HashMap::new(),
197        }
198    }
199
200    /// Add intermediate output data.
201    #[must_use]
202    pub fn with_output(mut self, output: HashMap<String, serde_json::Value>) -> Self {
203        self.output = output;
204        self
205    }
206
207    /// Add a single output value.
208    #[must_use]
209    pub fn with_output_value(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
210        self.output.insert(
211            key.into(),
212            serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
213        );
214        self
215    }
216}
217
218impl Default for TaskInProgress {
219    fn default() -> Self {
220        Self {
221            callback_after_seconds: 60,
222            output: HashMap::new(),
223        }
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn test_completed_result() {
233        let result = TaskResult::completed("task-1", "wf-1")
234            .with_worker_id("worker-1")
235            .with_output_value("result", "success");
236
237        assert_eq!(result.task_id, "task-1");
238        assert_eq!(result.status, TaskResultStatus::Completed);
239        assert_eq!(result.worker_id, Some("worker-1".to_owned()));
240        assert!(result.output_data.contains_key("result"));
241    }
242
243    #[test]
244    fn test_failed_result() {
245        let result = TaskResult::failed("task-1", "wf-1", "Something went wrong");
246
247        assert_eq!(result.status, TaskResultStatus::Failed);
248        assert_eq!(
249            result.reason_for_incompletion,
250            Some("Something went wrong".to_owned())
251        );
252    }
253
254    #[test]
255    fn test_in_progress_result() {
256        let result = TaskResult::in_progress("task-1", "wf-1", 30);
257
258        assert_eq!(result.status, TaskResultStatus::InProgress);
259        assert_eq!(result.callback_after_seconds, 30);
260    }
261
262    #[test]
263    fn test_task_in_progress() {
264        let tip = TaskInProgress::new(60).with_output_value("progress", 50);
265
266        assert_eq!(tip.callback_after_seconds, 60);
267        assert!(tip.output.contains_key("progress"));
268    }
269}