nova-boot-data-patterns 0.1.1

CQRS, event sourcing and saga patterns for Nova
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Saga orchestration primitives and a coordinator implementation.
//!
//! Defines `Saga` and `SagaStep` traits, execution tracking types, and a
//! `SagaCoordinator` which can run composed sagas with retry/compensation logic.
use async_trait::async_trait;
use std::sync::Arc;

use crate::error::SagaError;

// ---------------------------------------------------------------------------
// SagaStep – one atomic unit of work within a saga
// ---------------------------------------------------------------------------

#[async_trait]
pub trait SagaStep: Send + Sync {
    type Input: Clone + Send + Sync;
    type Output: Send;

    async fn execute(&self, input: Self::Input) -> Result<Self::Output, SagaError>;
    async fn compensate(&self, input: Self::Input) -> Result<(), SagaError>;
    fn step_name(&self) -> &str;
}

// ---------------------------------------------------------------------------
// Saga – named composition of steps
// ---------------------------------------------------------------------------

#[async_trait]
pub trait Saga: Send + Sync {
    type Input: Clone + Send + Sync;
    type Output: Send;

    fn saga_id(&self) -> &str;

    fn steps(&self) -> Vec<Arc<dyn SagaStep<Input = Self::Input, Output = ()>>>;

    /// Override for direct execution without SagaCoordinator.
    async fn execute(&self, _input: Self::Input) -> Result<Self::Output, SagaError> {
        Err(SagaError::Aborted(
            "direct execution not implemented; use SagaCoordinator".into(),
        ))
    }

    /// Override for direct compensation without SagaCoordinator.
    async fn compensate(&self, _input: Self::Input) -> Result<(), SagaError> {
        Err(SagaError::Aborted(
            "direct compensation not implemented; use SagaCoordinator".into(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Saga execution tracking
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub enum SagaExecutionStatus {
    Running,
    Completed,
    Failed(String),
    Compensating,
    Compensated,
}

#[derive(Debug, Clone)]
pub struct SagaExecution {
    pub saga_id: String,
    pub status: SagaExecutionStatus,
    pub completed_steps: Vec<String>,
    pub started_at: u64,
    pub updated_at: u64,
}

// ---------------------------------------------------------------------------
// SagaCoordinator – distributed transaction engine
// ---------------------------------------------------------------------------

#[cfg(feature = "messaging-bridge")]
pub use nova_boot_messaging::MessageBroker;

#[cfg(feature = "messaging-bridge")]
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[cfg(feature = "messaging-bridge")]
use tokio::sync::RwLock;

#[cfg(feature = "messaging-bridge")]
use tracing::{info, warn};

#[cfg(feature = "messaging-bridge")]
fn now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(feature = "messaging-bridge")]
pub struct SagaCoordinator<M: MessageBroker> {
    messaging: Arc<M>,
    max_retries: u32,
    timeout_ms: u64,
    executions: Arc<RwLock<std::collections::HashMap<String, SagaExecution>>>,
}

#[cfg(feature = "messaging-bridge")]
impl<M: MessageBroker> SagaCoordinator<M> {
    pub fn new(messaging: Arc<M>, max_retries: u32, timeout_ms: u64) -> Self {
        Self {
            messaging,
            max_retries,
            timeout_ms,
            executions: Arc::new(RwLock::new(std::collections::HashMap::new())),
        }
    }

    pub fn executions(&self) -> &Arc<RwLock<std::collections::HashMap<String, SagaExecution>>> {
        &self.executions
    }

    /// Run a saga: execute steps sequentially. On any step failure, run
    /// compensations in reverse order for previously-completed steps.
    pub async fn run<S: Saga>(&self, saga: &S, input: S::Input) -> Result<(), SagaError>
    where
        S::Input: Clone,
    {
        let saga_id = saga.saga_id().to_string();
        let steps = saga.steps();
        let mut completed: Vec<usize> = Vec::new();

        // Record execution start
        {
            let mut execs = self.executions.write().await;
            execs.insert(
                saga_id.clone(),
                SagaExecution {
                    saga_id: saga_id.clone(),
                    status: SagaExecutionStatus::Running,
                    completed_steps: Vec::new(),
                    started_at: now_ms(),
                    updated_at: now_ms(),
                },
            );
        }

        info!(saga_id = %saga_id, step_count = %steps.len(), "saga started");

        for (i, step) in steps.iter().enumerate() {
            let step_name = step.step_name().to_string();

            self.publish_event(&saga_id, &step_name, "started").await;

            let result = self
                .execute_step_with_retry(step.as_ref(), input.clone())
                .await;

            match result {
                Ok(()) => {
                    completed.push(i);
                    if let Some(exec) = self.executions.write().await.get_mut(&saga_id) {
                        exec.completed_steps.push(step_name.clone());
                        exec.updated_at = now_ms();
                    }
                    self.publish_event(&saga_id, &step_name, "succeeded").await;
                    info!(saga_id = %saga_id, step = %step_name, "step completed");
                }
                Err(e) => {
                    warn!(
                        saga_id = %saga_id,
                        step = %step_name,
                        error = %e,
                        "step failed, starting compensation"
                    );
                    self.publish_event(&saga_id, &step_name, "failed").await;

                    // Compensate in reverse order
                    if let Some(status) = self.executions.write().await.get_mut(&saga_id) {
                        status.status = SagaExecutionStatus::Compensating;
                        status.updated_at = now_ms();
                    }

                    for idx in completed.iter().rev() {
                        let comp_step = &steps[*idx];
                        let comp_name = comp_step.step_name().to_string();
                        self.publish_event(&saga_id, &comp_name, "compensating")
                            .await;

                        match comp_step.compensate(input.clone()).await {
                            Ok(()) => {
                                self.publish_event(&saga_id, &comp_name, "compensated")
                                    .await;
                                info!(
                                    saga_id = %saga_id,
                                    step = %comp_name,
                                    "compensation succeeded"
                                );
                            }
                            Err(ce) => {
                                warn!(
                                    saga_id = %saga_id,
                                    step = %comp_name,
                                    error = %ce,
                                    "compensation failed"
                                );
                                self.publish_event(&saga_id, &comp_name, "compensation_failed")
                                    .await;
                            }
                        }
                    }

                    if let Some(status) = self.executions.write().await.get_mut(&saga_id) {
                        status.status = SagaExecutionStatus::Compensated;
                        status.updated_at = now_ms();
                    }

                    self.publish_event(&saga_id, "saga", "compensated").await;
                    return Err(e);
                }
            }
        }

        // All steps completed successfully
        if let Some(status) = self.executions.write().await.get_mut(&saga_id) {
            status.status = SagaExecutionStatus::Completed;
            status.updated_at = now_ms();
        }

        self.publish_event(&saga_id, "saga", "completed").await;
        info!(saga_id = %saga_id, "saga completed successfully");
        Ok(())
    }

    // ------------------------------------------------------------------
    // Internal helpers
    // ------------------------------------------------------------------

    /// Execute a single step, retrying up to `max_retries`, with a timeout.
    async fn execute_step_with_retry<I: Clone + Send + Sync>(
        &self,
        step: &dyn SagaStep<Input = I, Output = ()>,
        input: I,
    ) -> Result<(), SagaError> {
        let mut attempt = 0u32;
        loop {
            let timeout = Duration::from_millis(self.timeout_ms);
            let deadline = tokio::time::Instant::now() + timeout;

            let result = tokio::select! {
                biased;
                _ = tokio::time::sleep_until(deadline) => {
                    return Err(SagaError::Timeout {
                        step: step.step_name().to_string(),
                    });
                }
                res = step.execute(input.clone()) => {
                    res.map(|_output| ())
                }
            };

            match result {
                Ok(()) => return Ok(()),
                Err(e) => {
                    attempt += 1;
                    if attempt > self.max_retries {
                        return Err(e);
                    }
                    warn!(
                        step = %step.step_name(),
                        attempt = %attempt,
                        max_retries = %self.max_retries,
                        error = %e,
                        "retrying step"
                    );
                    tokio::time::sleep(Duration::from_millis(100 * attempt as u64)).await;
                }
            }
        }
    }

    /// Publish a saga lifecycle event to topic `saga.{saga_id}.{step}.{status}`.
    async fn publish_event(&self, saga_id: &str, step: &str, status: &str) {
        use nova_boot_messaging::EventEnvelope;
        let topic = format!("saga.{saga_id}.{step}.{status}");
        let payload = serde_json::json!({
            "saga_id": saga_id,
            "step": step,
            "status": status,
            "timestamp_ms": now_ms(),
        });
        let envelope = EventEnvelope::new(
            format!("{saga_id}-{step}-{status}"),
            &topic,
            "saga.event",
            payload,
        );
        if let Err(e) = self.messaging.publish(envelope).await {
            warn!(
                saga_id = %saga_id,
                step = %step,
                status = %status,
                error = %e,
                "failed to publish saga event"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;
    use tracing::warn;

    struct PassStep {
        name: String,
    }

    #[async_trait]
    impl SagaStep for PassStep {
        type Input = String;
        type Output = ();
        async fn execute(&self, _input: String) -> Result<(), SagaError> {
            Ok(())
        }
        async fn compensate(&self, _input: String) -> Result<(), SagaError> {
            Ok(())
        }
        fn step_name(&self) -> &str {
            &self.name
        }
    }

    struct FailStep {
        name: String,
    }

    #[async_trait]
    impl SagaStep for FailStep {
        type Input = String;
        type Output = ();
        async fn execute(&self, _input: String) -> Result<(), SagaError> {
            Err(SagaError::StepFailed {
                step: self.name.clone(),
                reason: "intentional failure".into(),
            })
        }
        async fn compensate(&self, _input: String) -> Result<(), SagaError> {
            Ok(())
        }
        fn step_name(&self) -> &str {
            &self.name
        }
    }

    struct BadCompensateStep {
        name: String,
    }

    #[async_trait]
    impl SagaStep for BadCompensateStep {
        type Input = String;
        type Output = ();
        async fn execute(&self, _input: String) -> Result<(), SagaError> {
            Ok(())
        }
        async fn compensate(&self, _input: String) -> Result<(), SagaError> {
            Err(SagaError::CompensationFailed {
                step: self.name.clone(),
                reason: "compensation failure".into(),
            })
        }
        fn step_name(&self) -> &str {
            &self.name
        }
    }

    // Saga wrapper that carries Arc'd steps
    fn make_test_saga(
        steps: Vec<Arc<dyn SagaStep<Input = String, Output = ()>>>,
    ) -> impl Saga<Input = String, Output = ()> {
        struct TestSaga {
            steps: Vec<Arc<dyn SagaStep<Input = String, Output = ()>>>,
        }

        #[async_trait]
        impl Saga for TestSaga {
            type Input = String;
            type Output = ();
            fn saga_id(&self) -> &str {
                "test-saga"
            }
            fn steps(&self) -> Vec<Arc<dyn SagaStep<Input = String, Output = ()>>> {
                self.steps.clone()
            }
        }

        TestSaga { steps }
    }

    struct SimpleCoordinator {
        timeout_ms: u64,
    }

    impl SimpleCoordinator {
        fn new(_max_retries: u32, timeout_ms: u64) -> Self {
            Self { timeout_ms }
        }

        async fn run<S: Saga>(&self, saga: &S, input: S::Input) -> Result<(), SagaError>
        where
            S::Input: Clone,
        {
            let steps = saga.steps();
            let mut completed: Vec<usize> = Vec::new();

            for (i, step) in steps.iter().enumerate() {
                let timeout = Duration::from_millis(self.timeout_ms);
                let deadline = tokio::time::Instant::now() + timeout;

                let result = tokio::select! {
                    biased;
                    _ = tokio::time::sleep_until(deadline) => {
                        return Err(SagaError::Timeout {
                            step: step.step_name().to_string(),
                        });
                    }
                    res = step.execute(input.clone()) => res.map(|_| ())
                };

                match result {
                    Ok(()) => {
                        completed.push(i);
                    }
                    Err(e) => {
                        for idx in completed.iter().rev() {
                            let comp = &steps[*idx];
                            if let Err(ce) = comp.compensate(input.clone()).await {
                                warn!("compensation failed for step {}: {}", comp.step_name(), ce);
                            }
                        }
                        return Err(e);
                    }
                }
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn successful_saga_executes_all_steps() {
        let saga = make_test_saga(vec![
            Arc::new(PassStep {
                name: "step1".into(),
            }),
            Arc::new(PassStep {
                name: "step2".into(),
            }),
            Arc::new(PassStep {
                name: "step3".into(),
            }),
        ]);
        let coord = SimpleCoordinator::new(0, 5000);
        let result = coord.run(&saga, "ctx".to_string()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn saga_compensates_on_step_failure() {
        let saga = make_test_saga(vec![
            Arc::new(PassStep {
                name: "step1".into(),
            }),
            Arc::new(FailStep {
                name: "step2".into(),
            }),
            Arc::new(PassStep {
                name: "step3".into(),
            }),
        ]);
        let coord = SimpleCoordinator::new(0, 5000);
        let result = coord.run(&saga, "ctx".to_string()).await;
        assert!(result.is_err());
        match result {
            Err(SagaError::StepFailed { step, .. }) => {
                assert_eq!(step, "step2");
            }
            _ => panic!("expected StepFailed for step2"),
        }
    }

    #[tokio::test]
    async fn saga_timeout_returns_timeout_error() {
        struct SlowStep;

        #[async_trait]
        impl SagaStep for SlowStep {
            type Input = String;
            type Output = ();
            async fn execute(&self, _input: String) -> Result<(), SagaError> {
                tokio::time::sleep(Duration::from_millis(200)).await;
                Ok(())
            }
            async fn compensate(&self, _input: String) -> Result<(), SagaError> {
                Ok(())
            }
            fn step_name(&self) -> &str {
                "slow"
            }
        }

        let saga = make_test_saga(vec![Arc::new(SlowStep)]);
        let coord = SimpleCoordinator::new(0, 50);
        let result = coord.run(&saga, "ctx".to_string()).await;
        assert!(result.is_err());
        match result {
            Err(SagaError::Timeout { step }) => {
                assert_eq!(step, "slow");
            }
            _ => panic!("expected Timeout error"),
        }
    }

    #[tokio::test]
    async fn compensation_failure_does_not_panic() {
        let saga = make_test_saga(vec![
            Arc::new(BadCompensateStep {
                name: "bad-comp".into(),
            }),
            Arc::new(FailStep {
                name: "trigger".into(),
            }),
        ]);
        let coord = SimpleCoordinator::new(0, 5000);
        let result = coord.run(&saga, "ctx".to_string()).await;
        assert!(result.is_err());
        match result {
            Err(SagaError::StepFailed { step, .. }) => {
                assert_eq!(step, "trigger");
            }
            _ => panic!("expected StepFailed"),
        }
    }

    // Full SagaCoordinator tests with InMemoryBroker
    #[cfg(feature = "messaging-bridge")]
    mod messaging_tests {
        use super::*;
        use nova_boot_messaging::{InMemoryBroker, MessageBroker};

        #[tokio::test]
        async fn coordinator_publishes_events_for_each_step() {
            let broker = Arc::new(InMemoryBroker::default());
            let coord = SagaCoordinator::new(broker.clone(), 0, 5000);

            let saga = make_test_saga(vec![
                Arc::new(PassStep { name: "a".into() }),
                Arc::new(PassStep { name: "b".into() }),
            ]);

            coord
                .run(&saga, "ctx".to_string())
                .await
                .expect("saga should succeed");

            let events = broker.poll("saga.test-saga.a.started", 10).await.unwrap();
            assert_eq!(events.len(), 1);

            let events = broker.poll("saga.test-saga.a.succeeded", 10).await.unwrap();
            assert_eq!(events.len(), 1);

            let events = broker.poll("saga.test-saga.b.succeeded", 10).await.unwrap();
            assert_eq!(events.len(), 1);

            let events = broker
                .poll("saga.test-saga.saga.completed", 10)
                .await
                .unwrap();
            assert_eq!(events.len(), 1);
        }

        #[tokio::test]
        async fn coordinator_compensates_and_publishes_compensation_events() {
            let broker = Arc::new(InMemoryBroker::default());
            let coord = SagaCoordinator::new(broker.clone(), 0, 5000);

            let saga = make_test_saga(vec![
                Arc::new(PassStep {
                    name: "reserve".into(),
                }),
                Arc::new(FailStep {
                    name: "charge".into(),
                }),
            ]);

            let result = coord.run(&saga, "ctx".to_string()).await;
            assert!(result.is_err());

            let compensated = broker
                .poll("saga.test-saga.reserve.compensated", 10)
                .await
                .unwrap();
            assert_eq!(compensated.len(), 1);

            let saga_comp = broker
                .poll("saga.test-saga.saga.compensated", 10)
                .await
                .unwrap();
            assert_eq!(saga_comp.len(), 1);
        }

        #[tokio::test]
        async fn coordinator_retries_and_then_fails() {
            struct FlakyStep {
                attempts: Arc<std::sync::atomic::AtomicU32>,
            }

            #[async_trait]
            impl SagaStep for FlakyStep {
                type Input = String;
                type Output = ();
                async fn execute(&self, _input: String) -> Result<(), SagaError> {
                    let prev = self
                        .attempts
                        .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    if prev == 0 {
                        Err(SagaError::StepFailed {
                            step: "flaky".into(),
                            reason: "transient".into(),
                        })
                    } else {
                        Ok(())
                    }
                }
                async fn compensate(&self, _input: String) -> Result<(), SagaError> {
                    Ok(())
                }
                fn step_name(&self) -> &str {
                    "flaky"
                }
            }

            let attempts = Arc::new(std::sync::atomic::AtomicU32::new(0));
            let broker = Arc::new(InMemoryBroker::default());
            let coord = SagaCoordinator::new(broker.clone(), 3, 5000);

            let saga = make_test_saga(vec![Arc::new(FlakyStep {
                attempts: attempts.clone(),
            })]);

            let result = coord.run(&saga, "ctx".to_string()).await;
            assert!(result.is_ok());
            assert_eq!(attempts.load(std::sync::atomic::Ordering::SeqCst), 2);
        }
    }
}