orcher-sdk 0.5.2

Rust SDK for Orcher, a durable workflow engine: workflows, tasks, actors, workers and a client
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Sagas: sequences of steps that are undone by compensating tasks on failure.
//!
//! A saga keeps several services consistent without a distributed transaction.
//! Each step that succeeds registers a compensation. If a later step fails, the
//! registered compensations run in reverse order.
//!
//! ## Example
//!
//! ```rust
//! use orcher_sdk::prelude::*;
//! use orcher_sdk::workflow::Saga;
//!
//! #[derive(Clone, Serialize, Deserialize)]
//! struct Trip {
//!     id: String,
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct TripResult {
//!     hotel_id: String,
//!     flight_id: String,
//! }
//!
//! // `#[task]` generates a typed reference with the task's name.
//! #[task(retry = 3)]
//! async fn book_hotel(_ctx: TaskContext, trip: Trip) -> Result<String> {
//!     Ok(format!("hotel-{}", trip.id))
//! }
//!
//! #[task(retry = 10)]
//! async fn cancel_hotel(_ctx: TaskContext, _trip: Trip) -> Result<bool> {
//!     Ok(true)
//! }
//!
//! #[workflow]
//! async fn book_trip(ctx: WorkflowContext, trip: Trip) -> Result<TripResult> {
//!     let mut saga = Saga::new();
//!
//!     // Tasks can be named by task reference...
//!     let hotel_id: String = saga
//!         .add_step(&ctx, book_hotel, trip.clone())
//!         .with_compensation(cancel_hotel)
//!         .execute()
//!         .await?;
//!
//!     // ...or by string literal.
//!     let flight_id: String = saga
//!         .add_step(&ctx, "book_flight", trip)
//!         .with_compensation("cancel_flight")
//!         .execute()
//!         .await?;
//!
//!     // If a step fails, the compensations registered so far run in reverse order.
//!     saga.commit();
//!     Ok(TripResult { hotel_id, flight_id })
//! }
//! ```

use crate::error::{Error, Result};
use crate::task::IntoTaskName;
use crate::workflow::WorkflowContext;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::VecDeque;

/// A sequence of workflow steps with their compensations.
///
/// When a step run through [`SagaStepBuilder::execute`] fails, every
/// compensation registered before it runs in reverse order (last in, first
/// out). A failing compensation does not stop the others from running.
///
/// ## Running steps with the builder
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # use orcher_sdk::workflow::Saga;
/// # #[task]
/// # async fn action2(_ctx: TaskContext, input: u32) -> Result<u32> { Ok(input) }
/// # #[task]
/// # async fn compensate2(_ctx: TaskContext, _input: u32) -> Result<bool> { Ok(true) }
/// # async fn example(ctx: &WorkflowContext) -> Result<()> {
/// let mut saga = Saga::new();
///
/// // Name tasks with string literals...
/// let result1: String = saga
///     .add_step(ctx, "action1", "input1".to_string())
///     .with_compensation("compensate1")
///     .execute()
///     .await?;
///
/// // ...or with task references, checked at compile time.
/// let result2: u32 = saga
///     .add_step(ctx, action2, 2)            // generated by #[task]
///     .with_compensation(compensate2)       // generated by #[task]
///     .execute()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// ## Registering a compensation by hand
/// ```rust
/// # use orcher_sdk::prelude::*;
/// # use orcher_sdk::workflow::Saga;
/// #[derive(Serialize, Deserialize)]
/// struct HotelBooking {
///     booking_id: String,
/// }
///
/// # async fn example(ctx: &WorkflowContext) -> Result<()> {
/// let mut saga = Saga::new();
///
/// let booking: HotelBooking = ctx.execute_task("book_hotel", "trip-1".to_string()).await?;
///
/// // If a later step fails, cancel_hotel runs with this booking id.
/// saga.add_compensation("cancel_hotel", booking.booking_id);
/// # Ok(())
/// # }
/// ```
pub struct Saga {
    /// Compensations of completed steps, in the order they were registered.
    compensations: VecDeque<CompensationEntry>,

    /// Set once the saga is committed or compensated; compensation then does nothing.
    completed: bool,

    steps_executed: usize,
}

/// A compensation entry for a completed saga step.
#[derive(Debug, Clone)]
struct CompensationEntry {
    compensation_task: &'static str,

    /// JSON-encoded compensation input.
    compensation_input: Vec<u8>,

    /// 1-based step number, used in log output.
    step_number: usize,
}

/// Builder for one saga step, returned by [`Saga::add_step`].
pub struct SagaStepBuilder<'a, I> {
    saga: &'a mut Saga,

    ctx: &'a WorkflowContext,

    action_task: &'static str,

    /// Also used as the compensation input if the action succeeds.
    action_input: I,

    compensation_task: Option<&'static str>,
}

impl Saga {
    /// Creates an empty saga.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::workflow::Saga;
    /// let saga = Saga::new();
    /// ```
    pub fn new() -> Self {
        Self {
            compensations: VecDeque::new(),
            completed: false,
            steps_executed: 0,
        }
    }

    /// Starts a saga step that runs `action_task` with `action_input`.
    ///
    /// The task can be a string literal or a task reference. Call
    /// [`SagaStepBuilder::with_compensation`] and then
    /// [`SagaStepBuilder::execute`] on the returned builder.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use orcher_sdk::workflow::Saga;
    /// # async fn example(ctx: &WorkflowContext) -> Result<()> {
    /// let mut saga = Saga::new();
    ///
    /// let booking_id: String = saga
    ///     .add_step(ctx, "book_hotel", "trip-1".to_string())
    ///     .with_compensation("cancel_hotel")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_step<'a, T, I>(
        &'a mut self,
        ctx: &'a WorkflowContext,
        action_task: T,
        action_input: I,
    ) -> SagaStepBuilder<'a, I>
    where
        T: IntoTaskName,
        I: Serialize,
    {
        SagaStepBuilder {
            saga: self,
            ctx,
            action_task: action_task.into_task_name(),
            action_input,
            compensation_task: None,
        }
    }

    /// Registers a compensation for an action you ran yourself.
    ///
    /// Use this when the action is not run through [`Saga::add_step`]. The
    /// task can be a string literal or a task reference. If the input cannot
    /// be serialized, the compensation is registered with an empty input.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use orcher_sdk::workflow::Saga;
    /// #[derive(Serialize, Deserialize)]
    /// struct Booking {
    ///     id: String,
    /// }
    ///
    /// # async fn example(ctx: &WorkflowContext) -> Result<()> {
    /// let mut saga = Saga::new();
    ///
    /// let booking: Booking = ctx.execute_task("book_hotel", "trip-1".to_string()).await?;
    ///
    /// // If a later step fails, cancel_hotel runs with this booking id.
    /// saga.add_compensation("cancel_hotel", booking.id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_compensation<T, C>(&mut self, compensation_task: T, compensation_input: C)
    where
        T: IntoTaskName,
        C: Serialize,
    {
        let compensation_task = compensation_task.into_task_name();
        self.steps_executed += 1;

        let compensation_bytes = serde_json::to_vec(&compensation_input).unwrap_or_else(|_| vec![]);

        self.compensations.push_back(CompensationEntry {
            compensation_task,
            compensation_input: compensation_bytes,
            step_number: self.steps_executed,
        });

        tracing::debug!(
            step = %self.steps_executed,
            compensation = %compensation_task,
            "Registered saga compensation"
        );
    }

    /// Runs the compensations of all completed steps, in reverse order.
    ///
    /// [`SagaStepBuilder::execute`] calls this when its action fails. Calling it
    /// on a saga that is already committed or compensated does nothing.
    ///
    /// # Errors
    ///
    /// If any compensation fails, the others still run and the first failure is
    /// returned as a state error. A suspension (a compensation task being
    /// scheduled) is returned unchanged so the runtime can schedule it; on
    /// replay, finished compensations return their journaled results.
    pub async fn compensate(&mut self, ctx: &WorkflowContext) -> Result<()> {
        if self.completed {
            tracing::warn!("Saga already completed, skipping compensation");
            return Ok(());
        }

        self.completed = true;

        if self.compensations.is_empty() {
            tracing::info!("No compensations to execute");
            return Ok(());
        }

        tracing::info!(
            total_compensations = %self.compensations.len(),
            "Starting saga compensation (reverse order)"
        );

        let mut first_error: Option<Error> = None;
        let mut successful_compensations = 0;
        let mut failed_compensations = 0;

        while let Some(entry) = self.compensations.pop_back() {
            tracing::info!(
                step = %entry.step_number,
                task = %entry.compensation_task,
                "Executing compensation"
            );

            let input_result: Result<serde_json::Value> =
                serde_json::from_slice(&entry.compensation_input).map_err(|e| {
                    Error::Serialization(format!("Failed to deserialize compensation input: {}", e))
                });

            let compensation_result: Result<serde_json::Value> = match input_result {
                Ok(input) => ctx.execute_task(entry.compensation_task, input).await,
                Err(e) => Err(e),
            };

            match compensation_result {
                Ok(_) => {
                    successful_compensations += 1;
                    tracing::info!(
                        step = %entry.step_number,
                        task = %entry.compensation_task,
                        "Compensation successful"
                    );
                }
                // A suspension means the compensation task is being scheduled, not
                // that it failed. Propagate it so the runtime schedules the task and
                // replays; on replay this compensation returns its journaled result
                // and the loop moves on. It must not count as a failure.
                Err(e) if e.is_suspend() => return Err(e),
                Err(e) => {
                    failed_compensations += 1;
                    tracing::error!(
                        step = %entry.step_number,
                        task = %entry.compensation_task,
                        error = %e,
                        "Compensation failed"
                    );

                    // Keep the first error and keep compensating.
                    if first_error.is_none() {
                        first_error = Some(e);
                    }
                }
            }
        }

        tracing::info!(
            successful = %successful_compensations,
            failed = %failed_compensations,
            "Saga compensation complete"
        );

        if let Some(error) = first_error {
            Err(Error::Workflow(crate::error::WorkflowError::StateError(
                format!("Saga compensation failed: {}", error),
            )))
        } else {
            Ok(())
        }
    }

    /// Returns the number of steps that have registered a compensation.
    pub fn steps_executed(&self) -> usize {
        self.steps_executed
    }

    /// Returns the number of compensations that have not run yet.
    pub fn pending_compensations(&self) -> usize {
        self.compensations.len()
    }

    /// Returns `true` once the saga has been committed or compensated.
    pub fn is_completed(&self) -> bool {
        self.completed
    }

    /// Marks the saga as successfully completed.
    ///
    /// Call this after all steps succeed. Later calls to [`Saga::compensate`]
    /// then do nothing.
    pub fn commit(&mut self) {
        self.completed = true;
        tracing::info!(
            steps = %self.steps_executed,
            "Saga committed successfully"
        );
    }
}

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

impl<'a, I> SagaStepBuilder<'a, I>
where
    I: Serialize + Send + Sync + Clone + 'static,
{
    /// Sets the task that undoes this step.
    ///
    /// The task can be a string literal or a task reference. It receives the
    /// same input as the action.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use orcher_sdk::prelude::*;
    /// # use orcher_sdk::workflow::Saga;
    /// #[task]
    /// async fn book_flight(_ctx: TaskContext, trip_id: String) -> Result<String> {
    ///     Ok(format!("flight-{trip_id}"))
    /// }
    ///
    /// #[task]
    /// async fn cancel_flight(_ctx: TaskContext, _trip_id: String) -> Result<bool> {
    ///     Ok(true)
    /// }
    ///
    /// # async fn example(ctx: &WorkflowContext, saga: &mut Saga) -> Result<()> {
    /// // With string literal
    /// let hotel_id: String = saga
    ///     .add_step(ctx, "book_hotel", "trip-1".to_string())
    ///     .with_compensation("cancel_hotel")
    ///     .execute()
    ///     .await?;
    ///
    /// // With a task reference, checked at compile time
    /// let flight_id: String = saga
    ///     .add_step(ctx, book_flight, "trip-1".to_string())
    ///     .with_compensation(cancel_flight)
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_compensation<T>(mut self, compensation_task: T) -> Self
    where
        T: IntoTaskName,
    {
        self.compensation_task = Some(compensation_task.into_task_name());
        self
    }

    /// Runs the action and, if it succeeds, registers the compensation.
    ///
    /// Returns the action's result.
    ///
    /// # Errors
    ///
    /// If the action fails, no compensation is registered for it, the
    /// compensations of all earlier steps run, and the action's error is
    /// returned. A suspension (the action or a compensation being scheduled) is
    /// returned unchanged; it is not treated as a failure.
    pub async fn execute<O>(self) -> Result<O>
    where
        O: DeserializeOwned + Send + Sync + 'static,
    {
        // The original input is kept as the compensation input.
        let action_input_owned = self.action_input.clone();

        let action_result: Result<O> = self
            .ctx
            .execute_task(self.action_task, action_input_owned)
            .await;

        match action_result {
            Ok(result) => {
                if let Some(compensation_task) = self.compensation_task {
                    self.saga
                        .add_compensation(compensation_task, self.action_input);
                }

                tracing::info!(
                    step = %(self.saga.steps_executed + 1),
                    action = %self.action_task,
                    "Saga step completed successfully"
                );

                Ok(result)
            }
            Err(e) if e.is_suspend() => {
                // Suspension is normal control flow, not a step failure: the action
                // is being scheduled and the workflow will replay. Compensating here
                // would undo earlier successful steps of a healthy workflow.
                Err(e)
            }
            Err(e) => {
                tracing::error!(
                    step = %(self.saga.steps_executed + 1),
                    action = %self.action_task,
                    error = %e,
                    "Saga step failed, starting compensation"
                );

                if let Err(comp_error) = self.saga.compensate(self.ctx).await {
                    // A compensation being scheduled surfaces as a suspension, not a
                    // failure. Propagate it so the runtime schedules the compensation and
                    // replays; on replay it returns its journaled result and the next one
                    // runs. Swallowing it would let the workflow finish before the
                    // compensations run.
                    if comp_error.is_suspend() {
                        return Err(comp_error);
                    }
                    tracing::error!(
                        compensation_error = %comp_error,
                        "Saga compensation encountered errors"
                    );
                }

                Err(e)
            }
        }
    }

    /// Runs the action without registering a compensation.
    ///
    /// Use this for steps with nothing to undo, such as reads. A failure here
    /// does not trigger compensation of earlier steps.
    pub async fn execute_without_compensation<O>(self) -> Result<O>
    where
        O: DeserializeOwned + Send + Sync + 'static,
    {
        let action_input_owned = self.action_input.clone();

        self.ctx
            .execute_task(self.action_task, action_input_owned)
            .await
    }
}

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

    #[derive(Debug, Clone, Copy)]
    struct MockTaskRef(&'static str);

    impl TaskReference for MockTaskRef {
        fn task_name(&self) -> &'static str {
            self.0
        }
    }

    #[allow(dead_code)]
    const BOOK_HOTEL: MockTaskRef = MockTaskRef("book_hotel");
    const CANCEL_HOTEL: MockTaskRef = MockTaskRef("cancel_hotel");

    #[test]
    fn test_saga_new() {
        let saga = Saga::new();
        assert_eq!(saga.steps_executed(), 0);
        assert_eq!(saga.pending_compensations(), 0);
        assert!(!saga.is_completed());
    }

    #[test]
    fn test_saga_add_compensation() {
        let mut saga = Saga::new();

        saga.add_compensation("cancel_hotel", "hotel-123");
        assert_eq!(saga.steps_executed(), 1);
        assert_eq!(saga.pending_compensations(), 1);

        saga.add_compensation("cancel_flight", "flight-456");
        assert_eq!(saga.steps_executed(), 2);
        assert_eq!(saga.pending_compensations(), 2);
    }

    #[test]
    fn test_saga_add_compensation_with_task_reference() {
        let mut saga = Saga::new();

        saga.add_compensation(CANCEL_HOTEL, "hotel-123");
        assert_eq!(saga.steps_executed(), 1);
        assert_eq!(saga.pending_compensations(), 1);

        saga.add_compensation("cancel_flight", "flight-456");
        assert_eq!(saga.steps_executed(), 2);
        assert_eq!(saga.pending_compensations(), 2);
    }

    #[test]
    fn test_saga_commit() {
        let mut saga = Saga::new();
        saga.add_compensation("cancel_hotel", "hotel-123");

        saga.commit();
        assert!(saga.is_completed());
    }

    #[test]
    fn test_saga_default() {
        let saga = Saga::default();
        assert_eq!(saga.steps_executed(), 0);
        assert!(!saga.is_completed());
    }

    #[test]
    fn test_saga_accepts_task_references() {
        // Saga methods accept both task references and string literals
        // through `IntoTaskName`.
        let mut saga = Saga::new();

        saga.add_compensation(CANCEL_HOTEL, "booking-123");
        assert_eq!(saga.steps_executed(), 1);

        saga.add_compensation("cancel_flight", "booking-456");
        assert_eq!(saga.steps_executed(), 2);

        assert_eq!(saga.pending_compensations(), 2);
    }
}