conductor-sdk 0.2.0

Rust SDK for Netflix Conductor workflow orchestration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::Task;

/// Module for flexible timestamp deserialization (handles both i64 and ISO date strings).
mod timestamp_deserializer {
    use chrono::{DateTime, Utc};
    use serde::{self, Deserialize, Deserializer};

    /// Deserialize a timestamp that may be either i64 (epoch ms) or ISO 8601 string.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<i64, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum TimestampOrString {
            Timestamp(i64),
            String(String),
        }

        match TimestampOrString::deserialize(deserializer)? {
            TimestampOrString::Timestamp(ts) => Ok(ts),
            TimestampOrString::String(s) => {
                // Try to parse as ISO 8601 date string
                DateTime::parse_from_rfc3339(&s)
                    .map(|dt| dt.with_timezone(&Utc).timestamp_millis())
                    .or_else(|_| {
                        // Try alternative formats
                        s.parse::<i64>()
                    })
                    .map_err(serde::de::Error::custom)
            }
        }
    }
}

/// Module for flexible map deserialization (handles both maps and string representations).
mod flexible_map_deserializer {
    use serde::{self, Deserialize, Deserializer};
    use std::collections::HashMap;

    /// Deserialize a map that may be either a proper JSON map or a string representation.
    pub fn deserialize<'de, D>(
        deserializer: D,
    ) -> Result<HashMap<String, serde_json::Value>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum MapOrString {
            Map(HashMap<String, serde_json::Value>),
            #[expect(dead_code)]
            String(String),
        }

        match MapOrString::deserialize(deserializer)? {
            MapOrString::Map(map) => Ok(map),
            MapOrString::String(_) => {
                // Return empty map if it's a string representation
                // The string is usually something like "{input=test_value}" which is not valid JSON
                Ok(HashMap::new())
            }
        }
    }
}

/// Module for flexible `Vec<Task>` deserialization (handles both arrays and string representations).
mod flexible_tasks_deserializer {
    use super::Task;
    use serde::{self, Deserialize, Deserializer};

    /// Deserialize tasks that may be either a proper array or a string representation.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Task>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum VecOrString {
            Vec(Vec<Task>),
            #[expect(dead_code)]
            String(String),
        }

        match VecOrString::deserialize(deserializer)? {
            VecOrString::Vec(vec) => Ok(vec),
            VecOrString::String(_) => {
                // Return empty vec if it's a string representation from search API
                Ok(Vec::new())
            }
        }
    }
}

/// Module for flexible `Vec<String>` deserialization (handles both arrays and string representations).
mod flexible_string_vec_deserializer {
    use serde::{self, Deserialize, Deserializer};

    /// Deserialize string vec that may be either a proper array or a string representation.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum VecOrString {
            Vec(Vec<String>),
            Single(String),
        }

        match VecOrString::deserialize(deserializer)? {
            VecOrString::Vec(vec) => Ok(vec),
            VecOrString::Single(s) => {
                // Return single-element vec if it's a string from search API
                if s.is_empty() {
                    Ok(Vec::new())
                } else {
                    Ok(vec![s])
                }
            }
        }
    }
}

/// Module for flexible `HashMap`<String, String> deserialization.
mod flexible_string_map_deserializer {
    use serde::{self, Deserialize, Deserializer};
    use std::collections::HashMap;

    /// Deserialize string map that may be either a proper map or a string representation.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<HashMap<String, String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum MapOrString {
            Map(HashMap<String, String>),
            #[expect(dead_code)]
            String(String),
        }

        match MapOrString::deserialize(deserializer)? {
            MapOrString::Map(map) => Ok(map),
            MapOrString::String(_) => {
                // Return empty map if it's a string representation from search API
                Ok(HashMap::new())
            }
        }
    }
}

/// Workflow execution status.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WorkflowStatus {
    /// Workflow is running.
    #[default]
    Running,
    /// Workflow completed successfully.
    Completed,
    /// Workflow failed.
    Failed,
    /// Workflow timed out.
    TimedOut,
    /// Workflow was terminated.
    Terminated,
    /// Workflow is paused.
    Paused,
}

/// A workflow execution instance.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Workflow {
    /// Unique workflow ID.
    #[serde(default)]
    pub workflow_id: String,

    /// Workflow type/name.
    #[serde(default)]
    pub workflow_name: String,

    /// Workflow version.
    #[serde(default)]
    pub workflow_version: i32,

    /// Workflow status.
    #[serde(default)]
    pub status: WorkflowStatus,

    /// Workflow input (may be empty if returned as string from search API).
    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
    pub input: HashMap<String, serde_json::Value>,

    /// Workflow output (may be empty if returned as string from search API).
    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
    pub output: HashMap<String, serde_json::Value>,

    /// Correlation ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,

    /// Tasks in this workflow execution (may be empty from search API).
    #[serde(default, deserialize_with = "flexible_tasks_deserializer::deserialize")]
    pub tasks: Vec<Task>,

    /// Parent workflow ID (if this is a subworkflow).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_workflow_id: Option<String>,

    /// Parent workflow task ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_workflow_task_id: Option<String>,

    /// Start time (epoch ms or ISO 8601 string).
    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
    pub start_time: i64,

    /// End time (epoch ms or ISO 8601 string).
    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
    pub end_time: i64,

    /// Update time (epoch ms or ISO 8601 string).
    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
    pub update_time: i64,

    /// Created time (epoch ms or ISO 8601 string).
    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
    pub create_time: i64,

    /// Created by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,

    /// Updated by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_by: Option<String>,

    /// Reason for incompletion (if failed/terminated).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_for_incompletion: Option<String>,

    /// Workflow variables.
    #[serde(default, deserialize_with = "flexible_map_deserializer::deserialize")]
    pub variables: HashMap<String, serde_json::Value>,

    /// External input payload storage path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_input_payload_storage_path: Option<String>,

    /// External output payload storage path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_output_payload_storage_path: Option<String>,

    /// Priority.
    #[serde(default)]
    pub priority: i32,

    /// Owner app.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_app: Option<String>,

    /// Task to domain mapping.
    #[serde(
        default,
        deserialize_with = "flexible_string_map_deserializer::deserialize"
    )]
    pub task_to_domain: HashMap<String, String>,

    /// Workflow definition.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_definition: Option<super::WorkflowDef>,

    /// Failed reference task names.
    #[serde(
        default,
        deserialize_with = "flexible_string_vec_deserializer::deserialize"
    )]
    pub failed_reference_task_names: Vec<String>,

    /// Failed task names.
    #[serde(
        default,
        deserialize_with = "flexible_string_vec_deserializer::deserialize"
    )]
    pub failed_task_names: Vec<String>,

    /// Last retried time (epoch ms or ISO 8601 string).
    #[serde(default, deserialize_with = "timestamp_deserializer::deserialize")]
    pub last_retried_time: i64,

    /// Event.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<String>,
}

impl Workflow {
    /// Check if workflow is terminal (completed, failed, terminated, timed out).
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        matches!(
            self.status,
            WorkflowStatus::Completed
                | WorkflowStatus::Failed
                | WorkflowStatus::Terminated
                | WorkflowStatus::TimedOut
        )
    }

    /// Check if workflow is running (not terminal).
    #[must_use]
    pub fn is_running(&self) -> bool {
        !self.is_terminal()
    }

    /// Check if workflow succeeded.
    #[must_use]
    pub fn is_successful(&self) -> bool {
        self.status == WorkflowStatus::Completed
    }

    /// Get an output value.
    #[must_use]
    pub fn get_output<T>(&self, key: &str) -> Option<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let v = self.output.get(key)?;
        serde_json::from_value(v.clone()).ok()
    }

    /// Get output as string.
    #[must_use]
    pub fn get_output_string(&self, key: &str) -> Option<String> {
        self.output.get(key).map(|v| {
            if let serde_json::Value::String(s) = v {
                s.clone()
            } else {
                v.to_string()
            }
        })
    }

    /// Get a variable value.
    #[must_use]
    pub fn get_variable<T>(&self, key: &str) -> Option<T>
    where
        T: serde::de::DeserializeOwned,
    {
        let v = self.variables.get(key)?;
        serde_json::from_value(v.clone()).ok()
    }
}

/// Request to start a workflow.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartWorkflowRequest {
    /// Workflow name.
    pub name: String,

    /// Workflow version (optional, uses latest if not specified).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<i32>,

    /// Workflow input.
    #[serde(default)]
    pub input: HashMap<String, serde_json::Value>,

    /// Correlation ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,

    /// Task to domain mapping.
    #[serde(default)]
    pub task_to_domain: HashMap<String, String>,

    /// Workflow definition (for dynamic workflows).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_def: Option<super::WorkflowDef>,

    /// External input payload storage path.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_input_payload_storage_path: Option<String>,

    /// Priority.
    #[serde(default)]
    pub priority: i32,
}

impl StartWorkflowRequest {
    /// Create a new start workflow request.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

    /// Set workflow version.
    #[must_use]
    pub fn with_version(mut self, version: i32) -> Self {
        self.version = Some(version);
        self
    }

    /// Set workflow input.
    #[must_use]
    pub fn with_input(mut self, input: HashMap<String, serde_json::Value>) -> Self {
        self.input = input;
        self
    }

    /// Add a single input value.
    #[must_use]
    pub fn with_input_value(mut self, key: impl Into<String>, value: impl Serialize) -> Self {
        self.input.insert(
            key.into(),
            serde_json::to_value(value).unwrap_or(serde_json::Value::Null),
        );
        self
    }

    /// Set correlation ID.
    #[must_use]
    pub fn with_correlation_id(mut self, id: impl Into<String>) -> Self {
        self.correlation_id = Some(id.into());
        self
    }

    /// Set priority.
    #[must_use]
    pub fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    /// Set task to domain mapping.
    #[must_use]
    pub fn with_task_to_domain(mut self, mapping: HashMap<String, String>) -> Self {
        self.task_to_domain = mapping;
        self
    }

    /// Set workflow definition (for dynamic workflows).
    #[must_use]
    pub fn with_workflow_def(mut self, def: super::WorkflowDef) -> Self {
        self.workflow_def = Some(def);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_workflow_deserialization() {
        let json = r#"{
            "workflowId": "wf-123",
            "workflowName": "test_workflow",
            "status": "RUNNING",
            "input": {"key": "value"}
        }"#;

        let wf: Workflow = serde_json::from_str(json).unwrap();
        assert_eq!(wf.workflow_id, "wf-123");
        assert_eq!(wf.workflow_name, "test_workflow");
        assert_eq!(wf.status, WorkflowStatus::Running);
    }

    #[test]
    fn test_workflow_is_terminal() {
        let wf = Workflow {
            status: WorkflowStatus::Running,
            ..Default::default()
        };
        assert!(!wf.is_terminal());

        let wf = Workflow {
            status: WorkflowStatus::Completed,
            ..Default::default()
        };
        assert!(wf.is_terminal());
        assert!(wf.is_successful());

        let wf = Workflow {
            status: WorkflowStatus::Failed,
            ..Default::default()
        };
        assert!(wf.is_terminal());
        assert!(!wf.is_successful());
    }

    #[test]
    fn test_start_workflow_request() {
        let req = StartWorkflowRequest::new("my_workflow")
            .with_version(1)
            .with_input_value("name", "test")
            .with_correlation_id("corr-123");

        assert_eq!(req.name, "my_workflow");
        assert_eq!(req.version, Some(1));
        assert!(req.input.contains_key("name"));
        assert_eq!(req.correlation_id, Some("corr-123".to_owned()));
    }
}