sayiir-core 1.0.0

Core types and traits for the Sayiir durable workflow engine
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
//! Shared continuation builder for binding crates (Node.js, Python).
//!
//! Provides a binding-agnostic [`BuilderTask`] enum and [`build_continuation`]
//! function that both `sayiir-node` and `sayiir-py` delegate to, eliminating
//! ~135 lines of duplicated logic per binding.

use std::collections::HashMap;
use std::sync::Arc;

use crate::error::BuildError;
use crate::priority::Priority;
use crate::task::TaskMetadata;
use crate::workflow::WorkflowContinuation;

/// Validate that a duration value is finite and non-negative.
fn validate_duration(secs: f64, label: &str) -> Result<(), BuildError> {
    if !secs.is_finite() || secs < 0.0 {
        return Err(BuildError::InvalidDuration(label.to_string()));
    }
    Ok(())
}

/// A binding-agnostic builder task.
///
/// Binding crates collect these from their language-specific APIs, then pass
/// them to [`build_continuation`] to produce the [`WorkflowContinuation`] tree.
#[derive(Clone)]
pub enum BuilderTask {
    /// A single sequential task.
    Sequential {
        /// Unique task identifier.
        task_id: String,
        /// Task configuration (timeout, retries, display name, etc.).
        metadata: TaskMetadata,
    },
    /// A fork with parallel branches and a join task.
    Fork {
        /// Each branch is a chain of `(task_id, metadata)` pairs.
        branches: Vec<Vec<(String, TaskMetadata)>>,
        /// Identifier of the join task that combines branch results.
        join_id: String,
        /// Configuration for the join task.
        join_metadata: TaskMetadata,
    },
    /// A durable delay.
    Delay {
        /// Unique delay node identifier.
        delay_id: String,
        /// Duration in seconds.
        duration_secs: f64,
    },
    /// Wait for an external signal.
    AwaitSignal {
        /// Unique signal node identifier.
        signal_id: String,
        /// Name of the signal to wait for.
        signal_name: String,
        /// Optional timeout in seconds; `None` waits indefinitely.
        timeout_secs: Option<f64>,
    },
    /// A conditional branch node.
    Branch {
        /// Unique branch node identifier.
        branch_id: String,
        /// Each named branch is a chain of `(task_id, metadata)` pairs.
        branches: Vec<(String, Vec<(String, TaskMetadata)>)>,
        /// Optional default branch if no routing key matches.
        default: Option<Vec<(String, TaskMetadata)>>,
    },
    /// A loop node whose body repeats until the task returns `LoopResult::Done`.
    Loop {
        /// Unique loop node identifier.
        loop_id: String,
        /// The body task identifier.
        body_task_id: String,
        /// Configuration for the body task.
        body_metadata: TaskMetadata,
        /// Maximum number of iterations before applying `on_max`.
        max_iterations: u32,
        /// What to do when `max_iterations` is reached.
        on_max: crate::workflow::MaxIterationsPolicy,
    },
    /// A child workflow node (inline composition).
    ChildWorkflow {
        /// Unique child workflow identifier.
        child_id: String,
        /// The child's builder tasks (built separately).
        child_tasks: Vec<BuilderTask>,
    },
}

/// Build a task chain from a slice of `(id, metadata)` pairs.
///
/// Returns the chain head boxed, or an error if the chain is empty.
fn build_chain(chain: &[(String, TaskMetadata)]) -> Result<Box<WorkflowContinuation>, BuildError> {
    let mut current: Option<WorkflowContinuation> = None;
    for (id, metadata) in chain.iter().rev() {
        current = Some(WorkflowContinuation::Task {
            id: id.clone(),
            func: None,
            timeout: metadata.timeout,
            retry_policy: metadata.retries.clone(),
            version: metadata.version.clone(),
            priority: metadata.priority.map(Priority::as_u8),
            tags: metadata.tags.clone(),
            next: current.map(Box::new),
        });
    }
    current.map(Box::new).ok_or(BuildError::EmptyBranch)
}

/// High-level builder that both binding crates (`sayiir-node`, `sayiir-py`)
/// delegate to. Manages auto-incrementing counters for lambda / loop / branch
/// IDs and collects [`BuilderTask`]s.
pub struct FlowBuilder {
    tasks: Vec<BuilderTask>,
    lambda_counter: usize,
    loop_counter: usize,
    branch_counter: usize,
}

impl FlowBuilder {
    /// Create an empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tasks: Vec::new(),
            lambda_counter: 0,
            loop_counter: 0,
            branch_counter: 0,
        }
    }

    /// Generate the next lambda ID (`lambda_0`, `lambda_1`, …).
    pub fn next_lambda_id(&mut self) -> String {
        let id = format!("lambda_{}", self.lambda_counter);
        self.lambda_counter += 1;
        id
    }

    /// Add a sequential task.
    pub fn add_sequential(&mut self, task_id: String, metadata: TaskMetadata) {
        self.tasks
            .push(BuilderTask::Sequential { task_id, metadata });
    }

    /// Add a fork. Validates non-empty branches.
    ///
    /// # Errors
    ///
    /// Returns an error if branches is empty or any branch has no tasks.
    pub fn add_fork(
        &mut self,
        branches: Vec<Vec<(String, TaskMetadata)>>,
        join_id: String,
        join_metadata: TaskMetadata,
    ) -> Result<(), BuildError> {
        if branches.is_empty() {
            return Err(BuildError::EmptyFork);
        }
        for branch in &branches {
            if branch.is_empty() {
                return Err(BuildError::EmptyBranch);
            }
        }
        self.tasks.push(BuilderTask::Fork {
            branches,
            join_id,
            join_metadata,
        });
        Ok(())
    }

    /// Add a durable delay.
    ///
    /// # Errors
    ///
    /// Returns an error if `duration_secs` is negative or non-finite.
    pub fn add_delay(&mut self, delay_id: String, duration_secs: f64) -> Result<(), BuildError> {
        validate_duration(duration_secs, "delay duration")?;
        self.tasks.push(BuilderTask::Delay {
            delay_id,
            duration_secs,
        });
        Ok(())
    }

    /// Add a signal wait.
    ///
    /// # Errors
    ///
    /// Returns an error if `timeout_secs` is negative or non-finite.
    pub fn add_signal(
        &mut self,
        signal_id: String,
        signal_name: String,
        timeout_secs: Option<f64>,
    ) -> Result<(), BuildError> {
        if let Some(t) = timeout_secs {
            validate_duration(t, "timeout")?;
        }
        self.tasks.push(BuilderTask::AwaitSignal {
            signal_id,
            signal_name,
            timeout_secs,
        });
        Ok(())
    }

    /// Add a loop. Returns the generated loop ID.
    ///
    /// # Errors
    ///
    /// Returns an error if `max_iterations` is 0.
    pub fn add_loop(
        &mut self,
        body_task_id: String,
        body_metadata: TaskMetadata,
        max_iterations: u32,
        on_max: crate::workflow::MaxIterationsPolicy,
    ) -> Result<String, BuildError> {
        if max_iterations == 0 {
            let loop_id = format!("loop_{}", self.loop_counter);
            return Err(BuildError::InvalidMaxIterations(loop_id));
        }
        let loop_id = format!("loop_{}", self.loop_counter);
        self.loop_counter += 1;
        self.tasks.push(BuilderTask::Loop {
            loop_id: loop_id.clone(),
            body_task_id,
            body_metadata,
            max_iterations,
            on_max,
        });
        Ok(loop_id)
    }

    /// Add a branch. Returns the generated branch ID.
    ///
    /// # Errors
    ///
    /// Returns an error if branches is empty or any branch has no tasks.
    pub fn add_branch(
        &mut self,
        branches: Vec<(String, Vec<(String, TaskMetadata)>)>,
        default: Option<Vec<(String, TaskMetadata)>>,
    ) -> Result<String, BuildError> {
        if branches.is_empty() {
            return Err(BuildError::EmptyBranch);
        }
        for (_, chain) in &branches {
            if chain.is_empty() {
                return Err(BuildError::EmptyBranch);
            }
        }
        let branch_id = format!("branch_{}", self.branch_counter);
        self.branch_counter += 1;
        self.tasks.push(BuilderTask::Branch {
            branch_id: branch_id.clone(),
            branches,
            default,
        });
        Ok(branch_id)
    }

    /// Add a child workflow (inline composition).
    ///
    /// # Errors
    ///
    /// Returns an error if `child_tasks` is empty.
    pub fn add_child_workflow(&mut self, child_id: String, child_tasks: Vec<BuilderTask>) {
        self.tasks.push(BuilderTask::ChildWorkflow {
            child_id,
            child_tasks,
        });
    }

    /// Read access to the collected builder tasks.
    #[must_use]
    pub fn tasks(&self) -> &[BuilderTask] {
        &self.tasks
    }

    /// Build the final [`WorkflowContinuation`].
    ///
    /// # Errors
    ///
    /// Returns an error if the task list is empty or any branch chain is empty.
    ///
    /// Note: unlike the typed Rust [`crate::builder::WorkflowBuilder`], this does **not** reject
    /// duplicate task IDs. Binding-level workflows commonly reuse the same task
    /// function (and thus ID) at multiple positions in a pipeline — the task
    /// registry maps ID → callable, so duplicates simply re-execute the same task.
    pub fn build(&self) -> Result<WorkflowContinuation, BuildError> {
        build_continuation(&self.tasks)
    }
}

impl Default for FlowBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Build a [`WorkflowContinuation`] from a list of builder tasks.
///
/// # Errors
///
/// Returns an error if:
/// - `tasks` is empty
/// - Any fork or branch chain is empty
#[allow(clippy::too_many_lines)]
pub fn build_continuation(tasks: &[BuilderTask]) -> Result<WorkflowContinuation, BuildError> {
    if tasks.is_empty() {
        return Err(BuildError::EmptyWorkflow);
    }

    let mut current: Option<WorkflowContinuation> = None;

    for task in tasks.iter().rev() {
        current = Some(match task {
            BuilderTask::Sequential { task_id, metadata } => WorkflowContinuation::Task {
                id: task_id.clone(),
                func: None,
                timeout: metadata.timeout,
                retry_policy: metadata.retries.clone(),
                version: metadata.version.clone(),
                priority: metadata.priority.map(Priority::as_u8),
                tags: metadata.tags.clone(),
                next: current.map(Box::new),
            },
            BuilderTask::Delay {
                delay_id,
                duration_secs,
            } => WorkflowContinuation::Delay {
                id: delay_id.clone(),
                duration: std::time::Duration::from_secs_f64(*duration_secs),
                next: current.map(Box::new),
            },
            BuilderTask::AwaitSignal {
                signal_id,
                signal_name,
                timeout_secs,
            } => WorkflowContinuation::AwaitSignal {
                id: signal_id.clone(),
                signal_name: signal_name.clone(),
                timeout: timeout_secs.map(std::time::Duration::from_secs_f64),
                next: current.map(Box::new),
            },
            BuilderTask::Fork {
                branches,
                join_id,
                join_metadata,
            } => {
                let branch_ids: Vec<&str> = branches
                    .iter()
                    .filter_map(|chain| chain.first().map(|(id, _)| id.as_str()))
                    .collect();
                let fork_id = WorkflowContinuation::derive_fork_id(&branch_ids);

                let branch_conts: Vec<Arc<WorkflowContinuation>> = branches
                    .iter()
                    .map(|chain| {
                        let cont = build_chain(chain)?;
                        Ok(Arc::new(*cont))
                    })
                    .collect::<Result<Vec<_>, BuildError>>()?;

                let join_cont = WorkflowContinuation::Task {
                    id: join_id.clone(),
                    func: None,
                    timeout: join_metadata.timeout,
                    retry_policy: join_metadata.retries.clone(),
                    version: join_metadata.version.clone(),
                    priority: join_metadata.priority.map(Priority::as_u8),
                    tags: join_metadata.tags.clone(),
                    next: current.map(Box::new),
                };

                WorkflowContinuation::Fork {
                    id: fork_id,
                    branches: branch_conts.into_boxed_slice(),
                    join: Some(Box::new(join_cont)),
                }
            }
            BuilderTask::Branch {
                branch_id,
                branches,
                default,
            } => {
                let branch_map: HashMap<String, Box<WorkflowContinuation>> = branches
                    .iter()
                    .map(|(key, chain)| Ok((key.clone(), build_chain(chain)?)))
                    .collect::<Result<_, BuildError>>()?;

                let default_cont = default
                    .as_ref()
                    .map(|chain| build_chain(chain))
                    .transpose()?;

                WorkflowContinuation::Branch {
                    id: branch_id.clone(),
                    key_fn: None,
                    branches: branch_map,
                    default: default_cont,
                    next: current.map(Box::new),
                }
            }
            BuilderTask::Loop {
                loop_id,
                body_task_id,
                body_metadata,
                max_iterations,
                on_max,
            } => {
                if *max_iterations == 0 {
                    return Err(BuildError::InvalidMaxIterations(loop_id.clone()));
                }
                let body = WorkflowContinuation::Task {
                    id: body_task_id.clone(),
                    func: None,
                    timeout: body_metadata.timeout,
                    retry_policy: body_metadata.retries.clone(),
                    version: body_metadata.version.clone(),
                    priority: body_metadata.priority.map(Priority::as_u8),
                    tags: body_metadata.tags.clone(),
                    next: None,
                };
                WorkflowContinuation::Loop {
                    id: loop_id.clone(),
                    body: Box::new(body),
                    max_iterations: *max_iterations,
                    on_max: *on_max,
                    next: current.map(Box::new),
                }
            }
            BuilderTask::ChildWorkflow {
                child_id,
                child_tasks,
            } => {
                let child_cont = build_continuation(child_tasks)?;
                WorkflowContinuation::ChildWorkflow {
                    id: child_id.clone(),
                    child: Arc::new(child_cont),
                    next: current.map(Box::new),
                }
            }
        });
    }

    current.ok_or(BuildError::EmptyWorkflow)
}