conductor/worker/task_context.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 crate::models::Task;
5
6/// Context for the currently executing task.
7///
8/// This provides convenient access to task metadata and execution state.
9///
10/// # Example
11///
12/// ```rust,no_run
13/// use conductor::worker::{Worker, WorkerOutput, TaskContext};
14/// use conductor::models::Task;
15///
16/// async fn process_long_task(task: &Task) -> WorkerOutput {
17/// let ctx = TaskContext::from_task(task);
18///
19/// // Check how many times this task has been polled
20/// let poll_count = ctx.poll_count();
21///
22/// if poll_count > 10 {
23/// // Too many iterations, fail
24/// return WorkerOutput::failed("Max iterations exceeded");
25/// }
26///
27/// // Process work based on poll_count
28/// let processed = process_chunk(poll_count);
29///
30/// if is_complete() {
31/// WorkerOutput::completed_with_result(processed)
32/// } else {
33/// // More work to do
34/// WorkerOutput::in_progress(30)
35/// }
36/// }
37/// # fn process_chunk(_: i32) -> String { String::new() }
38/// # fn is_complete() -> bool { true }
39/// ```
40#[derive(Debug, Clone)]
41pub struct TaskContext {
42 task_id: String,
43 workflow_instance_id: String,
44 task_type: String,
45 reference_task_name: String,
46 poll_count: i32,
47 retry_count: i32,
48 correlation_id: Option<String>,
49 domain: Option<String>,
50 scheduled_time: i64,
51 start_time: i64,
52 iteration: i32,
53}
54
55impl TaskContext {
56 /// Create a `TaskContext` from a Task.
57 #[must_use]
58 pub fn from_task(task: &Task) -> Self {
59 Self {
60 task_id: task.task_id.clone(),
61 workflow_instance_id: task.workflow_instance_id.clone(),
62 task_type: task.task_type.clone(),
63 reference_task_name: task.reference_task_name.clone(),
64 poll_count: task.poll_count,
65 retry_count: task.retry_count,
66 correlation_id: task.correlation_id.clone(),
67 domain: task.domain.clone(),
68 scheduled_time: task.scheduled_time,
69 start_time: task.start_time,
70 iteration: task.iteration,
71 }
72 }
73
74 /// Get the unique task ID.
75 #[must_use]
76 pub fn task_id(&self) -> &str {
77 &self.task_id
78 }
79
80 /// Get the workflow instance ID.
81 #[must_use]
82 pub fn workflow_instance_id(&self) -> &str {
83 &self.workflow_instance_id
84 }
85
86 /// Get the task type (definition name).
87 #[must_use]
88 pub fn task_type(&self) -> &str {
89 &self.task_type
90 }
91
92 /// Get the reference task name within the workflow.
93 #[must_use]
94 pub fn reference_task_name(&self) -> &str {
95 &self.reference_task_name
96 }
97
98 /// Get the poll count for long-running tasks.
99 ///
100 /// This increments each time the task is polled after returning
101 /// `TaskInProgress`. Use this to track progress or implement
102 /// pagination in long-running tasks.
103 ///
104 /// # Example
105 ///
106 /// ```rust,no_run
107 /// # use conductor::worker::TaskContext;
108 /// # use conductor::models::Task;
109 /// let task = Task::default();
110 /// let ctx = TaskContext::from_task(&task);
111 ///
112 /// // Process different chunks based on poll count
113 /// let offset = ctx.poll_count() * 100;
114 /// // process_items(offset, 100);
115 /// ```
116 #[must_use]
117 pub fn poll_count(&self) -> i32 {
118 self.poll_count
119 }
120
121 /// Get the current retry count.
122 ///
123 /// Indicates how many times this task has been retried after failures.
124 #[must_use]
125 pub fn retry_count(&self) -> i32 {
126 self.retry_count
127 }
128
129 /// Get the correlation ID (if set).
130 #[must_use]
131 pub fn correlation_id(&self) -> Option<&str> {
132 self.correlation_id.as_deref()
133 }
134
135 /// Get the domain (if set).
136 #[must_use]
137 pub fn domain(&self) -> Option<&str> {
138 self.domain.as_deref()
139 }
140
141 /// Get the scheduled time (epoch milliseconds).
142 #[must_use]
143 pub fn scheduled_time(&self) -> i64 {
144 self.scheduled_time
145 }
146
147 /// Get the start time (epoch milliseconds).
148 #[must_use]
149 pub fn start_time(&self) -> i64 {
150 self.start_time
151 }
152
153 /// Get the iteration count (for loop tasks).
154 #[must_use]
155 pub fn iteration(&self) -> i32 {
156 self.iteration
157 }
158
159 /// Check if this is the first poll (`poll_count` == 0).
160 #[must_use]
161 pub fn is_first_poll(&self) -> bool {
162 self.poll_count == 0
163 }
164
165 /// Check if this is a retry (`retry_count` > 0).
166 #[must_use]
167 pub fn is_retry(&self) -> bool {
168 self.retry_count > 0
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 #[test]
177 fn test_task_context_from_task() {
178 let task = Task {
179 task_id: "task-123".to_owned(),
180 workflow_instance_id: "wf-456".to_owned(),
181 task_type: "my_task".to_owned(),
182 reference_task_name: "my_task_ref".to_owned(),
183 poll_count: 5,
184 retry_count: 1,
185 correlation_id: Some("corr-789".to_owned()),
186 domain: Some("production".to_owned()),
187 ..Default::default()
188 };
189
190 let ctx = TaskContext::from_task(&task);
191
192 assert_eq!(ctx.task_id(), "task-123");
193 assert_eq!(ctx.workflow_instance_id(), "wf-456");
194 assert_eq!(ctx.task_type(), "my_task");
195 assert_eq!(ctx.reference_task_name(), "my_task_ref");
196 assert_eq!(ctx.poll_count(), 5);
197 assert_eq!(ctx.retry_count(), 1);
198 assert_eq!(ctx.correlation_id(), Some("corr-789"));
199 assert_eq!(ctx.domain(), Some("production"));
200 assert!(!ctx.is_first_poll());
201 assert!(ctx.is_retry());
202 }
203
204 #[test]
205 fn test_first_poll() {
206 let task = Task {
207 poll_count: 0,
208 retry_count: 0,
209 ..Default::default()
210 };
211
212 let ctx = TaskContext::from_task(&task);
213
214 assert!(ctx.is_first_poll());
215 assert!(!ctx.is_retry());
216 }
217}