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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

use async_trait::async_trait;
use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::error::Result;
use crate::models::{Task, TaskInProgress, TaskResult, TaskResultStatus};

/// Output type for worker execution.
#[derive(Debug, Clone)]
pub enum WorkerOutput {
    /// Task completed successfully with output.
    Completed(HashMap<String, Value>),

    /// Task failed with an error message — retried by the server per the task's retry policy.
    Failed(String),

    /// Task failed permanently and should not be retried (`FAILED_WITH_TERMINAL_ERROR`).
    ///
    /// Return this instead of [`WorkerOutput::Failed`] — or instead of a plain `Err` from
    /// [`Worker::execute`], which always maps to [`WorkerOutput::Failed`] in `task_runner.rs` —
    /// when the failure is definitively not worth retrying (a malformed input that will fail
    /// identically every time, a missing local dependency like an interpreter binary, etc.).
    /// There is currently no way to signal this from an `Err` return; a worker that needs it
    /// must construct this variant directly and return it via `Ok(...)`.
    FailedWithTerminalError(String),

    /// Task is still in progress (for long-running tasks).
    InProgress(TaskInProgress),
}

impl WorkerOutput {
    /// Create a completed output with a single result value.
    pub fn completed_with_result(result: impl serde::Serialize) -> Self {
        let mut output = HashMap::new();
        output.insert(
            "result".to_owned(),
            serde_json::to_value(result).unwrap_or(Value::Null),
        );
        WorkerOutput::Completed(output)
    }

    /// Create a completed output with a map.
    #[must_use]
    pub fn completed(output: HashMap<String, Value>) -> Self {
        WorkerOutput::Completed(output)
    }

    /// Create a completed output with no data.
    #[must_use]
    pub fn complete() -> Self {
        WorkerOutput::Completed(HashMap::new())
    }

    /// Create a failed output.
    pub fn failed(reason: impl Into<String>) -> Self {
        WorkerOutput::Failed(reason.into())
    }

    /// Create an in-progress output.
    #[must_use]
    pub fn in_progress(callback_after_seconds: i64) -> Self {
        WorkerOutput::InProgress(TaskInProgress::new(callback_after_seconds))
    }

    /// Convert to `TaskResult`.
    #[must_use]
    pub fn into_task_result(self, task: &Task, worker_id: &str) -> TaskResult {
        match self {
            WorkerOutput::Completed(output) => TaskResult {
                task_id: task.task_id.clone(),
                workflow_instance_id: task.workflow_instance_id.clone(),
                worker_id: Some(worker_id.to_owned()),
                status: TaskResultStatus::Completed,
                output_data: output,
                ..Default::default()
            },
            WorkerOutput::Failed(reason) => TaskResult {
                task_id: task.task_id.clone(),
                workflow_instance_id: task.workflow_instance_id.clone(),
                worker_id: Some(worker_id.to_owned()),
                status: TaskResultStatus::Failed,
                reason_for_incompletion: Some(reason),
                ..Default::default()
            },
            WorkerOutput::FailedWithTerminalError(reason) => TaskResult {
                task_id: task.task_id.clone(),
                workflow_instance_id: task.workflow_instance_id.clone(),
                worker_id: Some(worker_id.to_owned()),
                status: TaskResultStatus::FailedWithTerminalError,
                reason_for_incompletion: Some(reason),
                ..Default::default()
            },
            WorkerOutput::InProgress(tip) => TaskResult {
                task_id: task.task_id.clone(),
                workflow_instance_id: task.workflow_instance_id.clone(),
                worker_id: Some(worker_id.to_owned()),
                status: TaskResultStatus::InProgress,
                callback_after_seconds: tip.callback_after_seconds,
                output_data: tip.output,
                ..Default::default()
            },
        }
    }
}

/// Trait for implementing Conductor task workers
#[async_trait]
pub trait Worker: Send + Sync {
    /// Get the task definition name this worker handles
    fn task_definition_name(&self) -> &str;

    /// Execute the task and return the output
    async fn execute(&self, task: &Task) -> Result<WorkerOutput>;

    /// Get the worker identity (optional, defaults to hostname-pid)
    fn identity(&self) -> String {
        let hostname = hostname::get().map_or_else(
            |_| "unknown".to_owned(),
            |h| h.to_string_lossy().into_owned(),
        );
        format!("{}-{}", hostname, std::process::id())
    }

    /// Get the domain for this worker (optional)
    fn domain(&self) -> Option<&str> {
        None
    }

    /// Get the poll interval in milliseconds
    fn poll_interval_millis(&self) -> u64 {
        100
    }

    /// Get the maximum concurrent task executions
    fn thread_count(&self) -> usize {
        1
    }

    /// Get the input JSON Schema for this worker (optional)
    ///
    /// Return a JSON Schema that describes the expected input format.
    /// Used when `register_task_def` is enabled to register input schema.
    fn input_schema(&self) -> Option<serde_json::Value> {
        None
    }

    /// Get the output JSON Schema for this worker (optional)
    ///
    /// Return a JSON Schema that describes the output format.
    /// Used when `register_task_def` is enabled to register output schema.
    fn output_schema(&self) -> Option<serde_json::Value> {
        None
    }

    /// Get the names of credentials this worker declares as required (optional)
    ///
    /// Used when `register_task_def` is enabled to stamp `TaskDef::runtime_metadata`
    /// so the server can resolve credentials before dispatching the task.
    fn declared_credentials(&self) -> Vec<String> {
        Vec::new()
    }
}

/// Type alias for async worker functions.
pub type WorkerFn =
    Arc<dyn Fn(Task) -> Pin<Box<dyn Future<Output = Result<WorkerOutput>> + Send>> + Send + Sync>;

/// Simple function-based worker implementation.
pub struct FnWorker {
    task_name: String,
    execute_fn: WorkerFn,
    identity: String,
    domain: Option<String>,
    poll_interval_millis: u64,
    thread_count: usize,
    input_schema: Option<serde_json::Value>,
    output_schema: Option<serde_json::Value>,
}

impl FnWorker {
    /// Create a new function-based worker.
    pub fn new<F, Fut>(task_name: impl Into<String>, f: F) -> Self
    where
        F: Fn(Task) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<WorkerOutput>> + Send + 'static,
    {
        let task_name = task_name.into();
        let identity = format!(
            "{}-{}",
            hostname::get().map_or_else(
                |_| "unknown".to_owned(),
                |h| h.to_string_lossy().into_owned()
            ),
            std::process::id()
        );

        Self {
            task_name,
            execute_fn: Arc::new(move |task| Box::pin(f(task))),
            identity,
            domain: None,
            poll_interval_millis: 100,
            thread_count: 1,
            input_schema: None,
            output_schema: None,
        }
    }

    /// Set the worker domain.
    #[must_use]
    pub fn with_domain(mut self, domain: impl Into<String>) -> Self {
        self.domain = Some(domain.into());
        self
    }

    /// Set the poll interval.
    #[must_use]
    pub fn with_poll_interval_millis(mut self, millis: u64) -> Self {
        self.poll_interval_millis = millis;
        self
    }

    /// Set the thread count.
    #[must_use]
    pub fn with_thread_count(mut self, count: usize) -> Self {
        self.thread_count = count;
        self
    }

    /// Set the worker identity.
    #[must_use]
    pub fn with_identity(mut self, identity: impl Into<String>) -> Self {
        self.identity = identity.into();
        self
    }

    /// Set the input JSON Schema.
    #[must_use]
    pub fn with_input_schema(mut self, schema: serde_json::Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Set the output JSON Schema.
    #[must_use]
    pub fn with_output_schema(mut self, schema: serde_json::Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Set input schema from a `JsonSchema` type.
    #[must_use]
    pub fn with_input_schema_from<T>(mut self, strict: bool) -> Self
    where
        T: schemars::JsonSchema,
    {
        self.input_schema = Some(crate::schema::generate_schema::<T>(strict));
        self
    }

    /// Set output schema from a `JsonSchema` type.
    #[must_use]
    pub fn with_output_schema_from<T>(mut self, strict: bool) -> Self
    where
        T: schemars::JsonSchema,
    {
        self.output_schema = Some(crate::schema::generate_schema::<T>(strict));
        self
    }
}

#[async_trait]
impl Worker for FnWorker {
    fn task_definition_name(&self) -> &str {
        &self.task_name
    }

    async fn execute(&self, task: &Task) -> Result<WorkerOutput> {
        (self.execute_fn)(task.clone()).await
    }

    fn identity(&self) -> String {
        self.identity.clone()
    }

    fn domain(&self) -> Option<&str> {
        self.domain.as_deref()
    }

    fn poll_interval_millis(&self) -> u64 {
        self.poll_interval_millis
    }

    fn thread_count(&self) -> usize {
        self.thread_count
    }

    fn input_schema(&self) -> Option<serde_json::Value> {
        self.input_schema.clone()
    }

    fn output_schema(&self) -> Option<serde_json::Value> {
        self.output_schema.clone()
    }
}

/// Type alias for async worker functions that use `Arc<Task>` (zero-copy).
pub type WorkerFnArc = Arc<
    dyn Fn(Arc<Task>) -> Pin<Box<dyn Future<Output = Result<WorkerOutput>> + Send>> + Send + Sync,
>;

/// High-performance function-based worker that uses `Arc<Task>` to avoid cloning.
///
/// Use this instead of `FnWorker` for high-throughput scenarios where task
/// cloning overhead is significant.
///
/// # Example
/// ```rust,ignore
/// let worker = FnWorkerArc::new("my_task", |task: Arc<Task>| async move {
///     let name = task.get_input_string("name").unwrap_or_default();
///     Ok(WorkerOutput::completed_with_result(format!("Hello, {}!", name)))
/// });
/// ```
pub struct FnWorkerArc {
    task_name: String,
    execute_fn: WorkerFnArc,
    identity: String,
    domain: Option<String>,
    poll_interval_millis: u64,
    thread_count: usize,
    input_schema: Option<serde_json::Value>,
    output_schema: Option<serde_json::Value>,
}

impl FnWorkerArc {
    /// Create a new high-performance function-based worker.
    pub fn new<F, Fut>(task_name: impl Into<String>, f: F) -> Self
    where
        F: Fn(Arc<Task>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<WorkerOutput>> + Send + 'static,
    {
        let task_name = task_name.into();
        let identity = format!(
            "{}-{}",
            hostname::get().map_or_else(
                |_| "unknown".to_owned(),
                |h| h.to_string_lossy().into_owned()
            ),
            std::process::id()
        );

        Self {
            task_name,
            execute_fn: Arc::new(move |task| Box::pin(f(task))),
            identity,
            domain: None,
            poll_interval_millis: 100,
            thread_count: 1,
            input_schema: None,
            output_schema: None,
        }
    }

    /// Set the worker domain.
    #[must_use]
    pub fn with_domain(mut self, domain: impl Into<String>) -> Self {
        self.domain = Some(domain.into());
        self
    }

    /// Set the poll interval.
    #[must_use]
    pub fn with_poll_interval_millis(mut self, millis: u64) -> Self {
        self.poll_interval_millis = millis;
        self
    }

    /// Set the thread count.
    #[must_use]
    pub fn with_thread_count(mut self, count: usize) -> Self {
        self.thread_count = count;
        self
    }

    /// Set the worker identity.
    #[must_use]
    pub fn with_identity(mut self, identity: impl Into<String>) -> Self {
        self.identity = identity.into();
        self
    }

    /// Set the input JSON Schema.
    #[must_use]
    pub fn with_input_schema(mut self, schema: serde_json::Value) -> Self {
        self.input_schema = Some(schema);
        self
    }

    /// Set the output JSON Schema.
    #[must_use]
    pub fn with_output_schema(mut self, schema: serde_json::Value) -> Self {
        self.output_schema = Some(schema);
        self
    }

    /// Set input schema from a `JsonSchema` type.
    #[must_use]
    pub fn with_input_schema_from<T>(mut self, strict: bool) -> Self
    where
        T: schemars::JsonSchema,
    {
        self.input_schema = Some(crate::schema::generate_schema::<T>(strict));
        self
    }

    /// Set output schema from a `JsonSchema` type.
    #[must_use]
    pub fn with_output_schema_from<T>(mut self, strict: bool) -> Self
    where
        T: schemars::JsonSchema,
    {
        self.output_schema = Some(crate::schema::generate_schema::<T>(strict));
        self
    }

    /// Execute with `Arc<Task>` directly (internal use).
    ///
    /// # Errors
    ///
    /// Propagates whatever error the worker's `execute_fn` returns.
    pub async fn execute_arc(&self, task: Arc<Task>) -> Result<WorkerOutput> {
        (self.execute_fn)(task).await
    }
}

#[async_trait]
impl Worker for FnWorkerArc {
    fn task_definition_name(&self) -> &str {
        &self.task_name
    }

    async fn execute(&self, task: &Task) -> Result<WorkerOutput> {
        // Still need to clone for the trait interface, but users can use execute_arc directly
        (self.execute_fn)(Arc::new(task.clone())).await
    }

    fn identity(&self) -> String {
        self.identity.clone()
    }

    fn domain(&self) -> Option<&str> {
        self.domain.as_deref()
    }

    fn poll_interval_millis(&self) -> u64 {
        self.poll_interval_millis
    }

    fn thread_count(&self) -> usize {
        self.thread_count
    }

    fn input_schema(&self) -> Option<serde_json::Value> {
        self.input_schema.clone()
    }

    fn output_schema(&self) -> Option<serde_json::Value> {
        self.output_schema.clone()
    }
}

/// Macro to simplify worker creation from closures.
///
/// # Example
/// ```rust,ignore
/// let worker = worker_fn!("my_task", |task| async move {
///     Ok(WorkerOutput::completed_with_result("done"))
/// });
/// ```
#[macro_export]
macro_rules! worker_fn {
    ($task_name:expr, $handler:expr) => {
        $crate::worker::FnWorker::new($task_name, $handler)
    };
}

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

    #[tokio::test]
    async fn test_fn_worker() {
        let worker = FnWorker::new("test_task", |task: Task| async move {
            let name = task
                .get_input_string("name")
                .unwrap_or_else(|| "World".to_owned());
            Ok(WorkerOutput::completed_with_result(format!(
                "Hello, {name}!"
            )))
        })
        .with_thread_count(5)
        .with_poll_interval_millis(500);

        assert_eq!(worker.task_definition_name(), "test_task");
        assert_eq!(worker.thread_count(), 5);
        assert_eq!(worker.poll_interval_millis(), 500);

        let mut task = Task::default();
        task.input_data
            .insert("name".to_owned(), serde_json::json!("Rust"));

        let result = worker.execute(&task).await.unwrap();
        match result {
            WorkerOutput::Completed(output) => {
                assert!(output.contains_key("result"));
            }
            _ => panic!("Expected completed output"),
        }
    }

    #[test]
    fn test_worker_output_conversion() {
        let task = Task {
            task_id: "task-1".to_owned(),
            workflow_instance_id: "wf-1".to_owned(),
            ..Default::default()
        };

        let output = WorkerOutput::completed_with_result("success");
        let result = output.into_task_result(&task, "worker-1");

        assert_eq!(result.task_id, "task-1");
        assert_eq!(result.status, TaskResultStatus::Completed);
        assert_eq!(result.worker_id, Some("worker-1".to_owned()));
    }

    #[test]
    fn test_worker_output_failed_is_retryable_status() {
        let task = Task::default();
        let result =
            WorkerOutput::Failed("transient error".to_owned()).into_task_result(&task, "worker-1");
        assert_eq!(result.status, TaskResultStatus::Failed);
        assert_eq!(
            result.reason_for_incompletion,
            Some("transient error".to_owned())
        );
    }

    #[test]
    fn test_worker_output_failed_with_terminal_error_conversion() {
        let task = Task {
            task_id: "task-1".to_owned(),
            workflow_instance_id: "wf-1".to_owned(),
            ..Default::default()
        };

        let output = WorkerOutput::FailedWithTerminalError("not retryable".to_owned());
        let result = output.into_task_result(&task, "worker-1");

        assert_eq!(result.task_id, "task-1");
        assert_eq!(result.status, TaskResultStatus::FailedWithTerminalError);
        assert_eq!(
            result.reason_for_incompletion,
            Some("not retryable".to_owned())
        );
        assert_eq!(result.worker_id, Some("worker-1".to_owned()));
    }
}