Skip to main content

conductor/models/
task_def.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/// Task definition timeout policy.
8#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
10pub enum TimeoutPolicy {
11    /// Retry the task.
12    Retry,
13    /// Timeout the workflow.
14    #[default]
15    TimeOutWf,
16    /// Alert only.
17    AlertOnly,
18}
19
20/// Task retry logic.
21#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
23pub enum RetryLogic {
24    /// Fixed delay between retries.
25    #[default]
26    Fixed,
27    /// Exponential backoff.
28    ExponentialBackoff,
29    /// Linear backoff.
30    LinearBackoff,
31}
32
33/// Task definition describing a task type.
34#[derive(Debug, Clone, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct TaskDef {
37    /// Task name (unique identifier).
38    pub name: String,
39
40    /// Task description.
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub description: Option<String>,
43
44    /// Number of retry attempts.
45    #[serde(default)]
46    pub retry_count: i32,
47
48    /// Retry logic.
49    #[serde(default)]
50    pub retry_logic: RetryLogic,
51
52    /// Delay between retries in seconds.
53    #[serde(default)]
54    pub retry_delay_seconds: i32,
55
56    /// Backoff scale factor for exponential backoff.
57    #[serde(default = "default_backoff_factor")]
58    pub backoff_scale_factor: i32,
59
60    /// Timeout in seconds.
61    #[serde(default = "default_timeout")]
62    pub timeout_seconds: i64,
63
64    /// Response timeout in seconds.
65    #[serde(default = "default_response_timeout")]
66    pub response_timeout_seconds: i64,
67
68    /// Poll timeout in seconds.
69    #[serde(default)]
70    pub poll_timeout_seconds: i64,
71
72    /// Timeout policy.
73    #[serde(default)]
74    pub timeout_policy: TimeoutPolicy,
75
76    /// Maximum concurrent executions (0 = unlimited).
77    #[serde(default)]
78    pub concurrent_exec_limit: i32,
79
80    /// Rate limit per frequency.
81    #[serde(default)]
82    pub rate_limit_per_frequency: i32,
83
84    /// Rate limit frequency in seconds.
85    #[serde(default = "default_rate_limit_frequency")]
86    pub rate_limit_frequency_in_seconds: i32,
87
88    /// Owner email.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub owner_email: Option<String>,
91
92    /// Input keys (expected input parameters).
93    #[serde(default)]
94    pub input_keys: Vec<String>,
95
96    /// Output keys (expected output parameters).
97    #[serde(default)]
98    pub output_keys: Vec<String>,
99
100    /// Input template (default input values).
101    #[serde(default)]
102    pub input_template: HashMap<String, serde_json::Value>,
103
104    /// Created by.
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub created_by: Option<String>,
107
108    /// Created time.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub create_time: Option<i64>,
111
112    /// Updated by.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub updated_by: Option<String>,
115
116    /// Update time.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub update_time: Option<i64>,
119
120    /// Input schema (JSON Schema for input validation).
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub input_schema: Option<serde_json::Value>,
123
124    /// Output schema (JSON Schema for output validation).
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub output_schema: Option<serde_json::Value>,
127
128    /// Runtime metadata (e.g. declared credential names required to dispatch this task).
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub runtime_metadata: Vec<String>,
131}
132
133fn default_backoff_factor() -> i32 {
134    1
135}
136
137fn default_timeout() -> i64 {
138    3600
139}
140
141fn default_response_timeout() -> i64 {
142    600
143}
144
145fn default_rate_limit_frequency() -> i32 {
146    1
147}
148
149impl Default for TaskDef {
150    fn default() -> Self {
151        Self {
152            name: String::new(),
153            description: None,
154            retry_count: 0,
155            retry_logic: RetryLogic::default(),
156            retry_delay_seconds: 0,
157            backoff_scale_factor: default_backoff_factor(),
158            timeout_seconds: default_timeout(),
159            response_timeout_seconds: default_response_timeout(),
160            poll_timeout_seconds: 0,
161            timeout_policy: TimeoutPolicy::default(),
162            concurrent_exec_limit: 0,
163            rate_limit_per_frequency: 0,
164            rate_limit_frequency_in_seconds: default_rate_limit_frequency(),
165            owner_email: None,
166            input_keys: Vec::new(),
167            output_keys: Vec::new(),
168            input_template: HashMap::new(),
169            created_by: None,
170            create_time: None,
171            updated_by: None,
172            update_time: None,
173            input_schema: None,
174            output_schema: None,
175            runtime_metadata: Vec::new(),
176        }
177    }
178}
179
180impl TaskDef {
181    /// Create a new task definition with the given name.
182    pub fn new(name: impl Into<String>) -> Self {
183        Self {
184            name: name.into(),
185            ..Default::default()
186        }
187    }
188
189    /// Set description.
190    #[must_use]
191    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
192        self.description = Some(desc.into());
193        self
194    }
195
196    /// Set retry configuration.
197    #[must_use]
198    pub fn with_retry(mut self, count: i32, logic: RetryLogic, delay_seconds: i32) -> Self {
199        self.retry_count = count;
200        self.retry_logic = logic;
201        self.retry_delay_seconds = delay_seconds;
202        self
203    }
204
205    /// Set timeout configuration.
206    ///
207    /// Note: This also sets `response_timeout_seconds` to the same value to ensure
208    /// `response_timeout_seconds` <= `timeout_seconds` (required by Conductor validation).
209    #[must_use]
210    pub fn with_timeout(mut self, timeout_seconds: i64, policy: TimeoutPolicy) -> Self {
211        self.timeout_seconds = timeout_seconds;
212        self.timeout_policy = policy;
213        // response_timeout must be <= timeout_seconds
214        if self.response_timeout_seconds > timeout_seconds {
215            self.response_timeout_seconds = timeout_seconds;
216        }
217        self
218    }
219
220    /// Set response timeout.
221    #[must_use]
222    pub fn with_response_timeout(mut self, seconds: i64) -> Self {
223        self.response_timeout_seconds = seconds;
224        self
225    }
226
227    /// Set rate limit.
228    #[must_use]
229    pub fn with_rate_limit(mut self, limit: i32, frequency_seconds: i32) -> Self {
230        self.rate_limit_per_frequency = limit;
231        self.rate_limit_frequency_in_seconds = frequency_seconds;
232        self
233    }
234
235    /// Set concurrent execution limit.
236    #[must_use]
237    pub fn with_concurrent_limit(mut self, limit: i32) -> Self {
238        self.concurrent_exec_limit = limit;
239        self
240    }
241
242    /// Set owner email.
243    #[must_use]
244    pub fn with_owner(mut self, email: impl Into<String>) -> Self {
245        self.owner_email = Some(email.into());
246        self
247    }
248
249    /// Set input keys.
250    #[must_use]
251    pub fn with_input_keys(mut self, keys: Vec<String>) -> Self {
252        self.input_keys = keys;
253        self
254    }
255
256    /// Set output keys.
257    #[must_use]
258    pub fn with_output_keys(mut self, keys: Vec<String>) -> Self {
259        self.output_keys = keys;
260        self
261    }
262
263    /// Set runtime metadata (e.g. declared credential names required to dispatch this task).
264    #[must_use]
265    pub fn with_runtime_metadata(mut self, runtime_metadata: Vec<String>) -> Self {
266        self.runtime_metadata = runtime_metadata;
267        self
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn test_task_def_builder() {
277        let task_def = TaskDef::new("my_task")
278            .with_description("A test task")
279            .with_retry(3, RetryLogic::LinearBackoff, 5)
280            .with_timeout(120, TimeoutPolicy::Retry)
281            .with_rate_limit(100, 10);
282
283        assert_eq!(task_def.name, "my_task");
284        assert_eq!(task_def.description, Some("A test task".to_owned()));
285        assert_eq!(task_def.retry_count, 3);
286        assert_eq!(task_def.retry_logic, RetryLogic::LinearBackoff);
287        assert_eq!(task_def.retry_delay_seconds, 5);
288        assert_eq!(task_def.timeout_seconds, 120);
289        assert_eq!(task_def.timeout_policy, TimeoutPolicy::Retry);
290        assert_eq!(task_def.rate_limit_per_frequency, 100);
291        assert_eq!(task_def.rate_limit_frequency_in_seconds, 10);
292    }
293
294    #[test]
295    fn test_task_def_serialization() {
296        let task_def = TaskDef::new("test");
297        let json = serde_json::to_string(&task_def).unwrap();
298        assert!(json.contains("\"name\":\"test\""));
299    }
300
301    #[test]
302    fn test_task_def_runtime_metadata_default_empty() {
303        let task_def = TaskDef::new("test");
304        assert!(task_def.runtime_metadata.is_empty());
305    }
306
307    #[test]
308    fn test_task_def_with_runtime_metadata() {
309        let task_def = TaskDef::new("test").with_runtime_metadata(vec!["openai_key".to_owned()]);
310        assert_eq!(task_def.runtime_metadata, vec!["openai_key".to_owned()]);
311    }
312
313    #[test]
314    fn test_task_def_runtime_metadata_skipped_when_empty() {
315        let task_def = TaskDef::new("test");
316        let json = serde_json::to_string(&task_def).unwrap();
317        assert!(!json.contains("runtimeMetadata"));
318    }
319
320    #[test]
321    fn test_task_def_runtime_metadata_serialized_when_present() {
322        let task_def = TaskDef::new("test").with_runtime_metadata(vec!["openai_key".to_owned()]);
323        let json = serde_json::to_string(&task_def).unwrap();
324        assert!(json.contains("\"runtimeMetadata\":[\"openai_key\"]"));
325
326        let deserialized: TaskDef = serde_json::from_str(&json).unwrap();
327        assert_eq!(deserialized.runtime_metadata, vec!["openai_key".to_owned()]);
328    }
329}