ave-actors-actor 0.4.1

Ave actor model
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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! Retries module.
//!
//! This module provides a helper actor that re-sends the same message according
//! to a retry schedule.
//!

use crate::{
    Actor, ActorContext, ActorPath, Error, Handler, Message,
    NotPersistentActor,
    supervision::{RetryStrategy, Strategy},
};

use async_trait::async_trait;

use std::{fmt::Debug, marker::PhantomData, time::Duration};
use tracing::{debug, error, info_span};

#[async_trait]
trait CompletionNotifier<T>: Send + Sync
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
{
    async fn notify(&self, ctx: &ActorContext<RetryActor<T>>);
}

struct ParentMessageNotifier<T, P>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
    P: Actor + Handler<P>,
{
    message: P::Message,
    _phantom: PhantomData<(T, P)>,
}

#[async_trait]
impl<T, P> CompletionNotifier<T> for ParentMessageNotifier<T, P>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
    P: Actor + Handler<P>,
{
    async fn notify(&self, ctx: &ActorContext<RetryActor<T>>) {
        if let Ok(parent) = ctx.get_parent::<P>().await {
            let _ = parent.tell(self.message.clone()).await;
        }
    }
}

/// Retry actor.
///
/// `RetryActor` re-sends the same message to a managed child actor according to
/// the configured schedule. A successful `tell()` does not end the sequence by
/// itself; retries continue until:
///
/// - `RetryMessage::End` is received
/// - `max_retries` is reached
/// - the target child can no longer accept messages
///
/// The retry cycle can only be started once with [`RetryMessage::Retry`]. Any
/// later `Retry` messages are ignored.
///
/// `RetryMessage::End` is always terminal:
/// - before the cycle starts, it stops the actor without sending the target message
/// - while a retry is scheduled, it cancels the pending retry and finishes the cycle
pub struct RetryActor<T>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
{
    target: T,
    message: T::Message,
    retry_strategy: Strategy,
    retries: usize,
    started: bool,
    is_end: bool,
    completion_pending: bool,
    completion_notified: bool,
    on_finished: Option<Box<dyn CompletionNotifier<T>>>,
    pending_retry: Option<tokio::task::JoinHandle<()>>,
}

impl<T> RetryActor<T>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
{
    /// Create a new RetryActor.
    pub const fn new(
        target: T,
        message: T::Message,
        retry_strategy: Strategy,
    ) -> Self {
        Self {
            target,
            message,
            retry_strategy,
            retries: 0,
            started: false,
            is_end: false,
            completion_pending: false,
            completion_notified: false,
            on_finished: None,
            pending_retry: None,
        }
    }

    /// Creates a `RetryActor` that notifies its parent with `completion_message`
    /// when the retry cycle finishes, either because:
    ///
    /// - the retry budget is exhausted
    /// - `RetryMessage::End` stops it explicitly
    /// - the managed child no longer accepts messages
    pub fn new_with_parent_message<P>(
        target: T,
        message: T::Message,
        retry_strategy: Strategy,
        completion_message: P::Message,
    ) -> Self
    where
        P: Actor + Handler<P>,
    {
        Self {
            target,
            message,
            retry_strategy,
            retries: 0,
            started: false,
            is_end: false,
            completion_pending: false,
            completion_notified: false,
            on_finished: Some(Box::new(ParentMessageNotifier::<T, P> {
                message: completion_message,
                _phantom: PhantomData,
            })),
            pending_retry: None,
        }
    }

    async fn finish_retry_cycle(&mut self, ctx: &ActorContext<Self>) {
        self.is_end = true;
        if let Some(handle) = self.pending_retry.take() {
            handle.abort();
        }
        if !self.completion_notified {
            self.completion_notified = true;
        } else {
            ctx.stop(None).await;
            return;
        }

        if let Some(notifier) = self.on_finished.as_ref() {
            notifier.notify(ctx).await;
        }

        self.schedule_completion(ctx).await;
    }

    async fn schedule_completion(&mut self, ctx: &ActorContext<Self>) {
        self.completion_pending = true;
        if let Ok(actor) = ctx.reference().await {
            self.pending_retry = Some(tokio::spawn(async move {
                tokio::time::sleep(Duration::ZERO).await;
                let _ = actor.tell(RetryMessage::Complete).await;
            }));
        } else {
            ctx.stop(None).await;
        }
    }

    async fn handle_retry_attempt(
        &mut self,
        ctx: &ActorContext<Self>,
    ) -> Result<(), Error> {
        if self.is_end {
            return Ok(());
        }

        self.retries += 1;
        if self.retries > self.retry_strategy.max_retries() {
            self.finish_retry_cycle(ctx).await;
            return Ok(());
        }

        debug!(
            retry = self.retries,
            max_retries = self.retry_strategy.max_retries(),
            "Executing retry"
        );

        // Re-send to the managed target child. Successful delivery does not stop
        // the schedule; only explicit End, max retries or target unavailability do.
        let child = match ctx.get_child::<T>("target").await {
            Ok(child) => child,
            Err(err) => {
                error!(error = %err, "Retry target is not available");
                self.finish_retry_cycle(ctx).await;
                return Ok(());
            }
        };

        if let Err(err) = child.tell(self.message.clone()).await {
            error!(error = %err, "Failed to send retry message to target");
            self.finish_retry_cycle(ctx).await;
            return Ok(());
        }

        if let Ok(actor) = ctx.reference().await {
            match self.retry_strategy.next_backoff() {
                Some(duration) => {
                    self.pending_retry = Some(tokio::spawn(async move {
                        tokio::time::sleep(duration).await;
                        let _ = actor.tell(RetryMessage::Continue).await;
                    }));
                }
                None => {
                    let _ = actor.tell(RetryMessage::Continue).await;
                }
            }
        } else {
            debug!("Retry actor no longer registered, stopping silently");
            self.is_end = true;
            ctx.stop(None).await;
        }

        Ok(())
    }
}
#[derive(Debug, Clone)]
pub enum RetryMessage {
    /// Starts the retry cycle. Later `Retry` messages are ignored.
    Retry,
    /// Internal scheduled retry attempt after the cycle has already started.
    Continue,
    /// Explicitly finishes the retry cycle.
    End,
    /// Internal completion marker used to stop after the final target delivery
    /// had a chance to run.
    Complete,
}

impl Message for RetryMessage {}

impl<T> NotPersistentActor for RetryActor<T> where
    T: Actor + Handler<T> + Clone + NotPersistentActor
{
}

#[async_trait]
impl<T> Actor for RetryActor<T>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
{
    type Message = RetryMessage;
    type Response = ();
    type Event = ();

    fn get_span(
        id: &str,
        _parent_span: Option<tracing::Span>,
    ) -> tracing::Span {
        info_span!("RetryActor", id = %id)
    }

    async fn pre_start(
        &mut self,
        ctx: &mut ActorContext<Self>,
    ) -> Result<(), Error> {
        ctx.create_child("target", self.target.clone()).await?;
        Ok(())
    }

    async fn pre_stop(
        &mut self,
        _ctx: &mut ActorContext<Self>,
    ) -> Result<(), Error> {
        if let Some(handle) = self.pending_retry.take() {
            handle.abort();
        }
        Ok(())
    }
}

#[async_trait]
impl<T> Handler<Self> for RetryActor<T>
where
    T: Actor + Handler<T> + Clone + NotPersistentActor,
{
    async fn handle_message(
        &mut self,
        _path: ActorPath,
        message: RetryMessage,
        ctx: &mut ActorContext<Self>,
    ) -> Result<(), Error> {
        match message {
            RetryMessage::Retry => {
                if self.started {
                    debug!(
                        "Retry cycle already started, ignoring duplicate start"
                    );
                } else {
                    self.started = true;
                    self.handle_retry_attempt(ctx).await?;
                }
            }
            RetryMessage::Continue => {
                self.handle_retry_attempt(ctx).await?;
            }
            RetryMessage::End => {
                self.finish_retry_cycle(ctx).await;
            }
            RetryMessage::Complete => {
                if self.completion_pending {
                    self.completion_pending = false;
                    ctx.stop(None).await;
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {

    use test_log::test;
    use tokio_util::sync::CancellationToken;
    use tracing::info_span;

    use super::*;

    use crate::{ActorRef, ActorSystem, Error, FixedIntervalStrategy};

    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };
    use std::time::Duration;

    pub struct SourceActor;

    impl NotPersistentActor for SourceActor {}

    #[derive(Debug, Clone)]
    pub struct SourceMessage(pub String);

    impl Message for SourceMessage {}

    #[async_trait]
    impl Actor for SourceActor {
        type Message = SourceMessage;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("SourceActor", id = %id)
        }

        async fn pre_start(
            &mut self,
            ctx: &mut ActorContext<SourceActor>,
        ) -> Result<(), Error> {
            println!("SourceActor pre_start");
            let target = TargetActor { counter: 0 };

            let strategy = Strategy::FixedInterval(FixedIntervalStrategy::new(
                3,
                Duration::from_secs(1),
            ));

            let retry_actor = RetryActor::new(
                target,
                TargetMessage {
                    source: ctx.path().clone(),
                    message: "Hello from parent".to_owned(),
                },
                strategy,
            );
            let retry: ActorRef<RetryActor<TargetActor>> =
                ctx.create_child("retry", retry_actor).await.unwrap();

            retry.tell(RetryMessage::Retry).await.unwrap();
            Ok(())
        }
    }

    #[async_trait]
    impl Handler<SourceActor> for SourceActor {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            message: SourceMessage,
            ctx: &mut ActorContext<SourceActor>,
        ) -> Result<(), Error> {
            println!("Message: {:?}", message);
            assert_eq!(message.0, "Hello from child");

            let retry = ctx
                .get_child::<RetryActor<TargetActor>>("retry")
                .await
                .unwrap();
            retry.tell(RetryMessage::End).await.unwrap();

            Ok(())
        }
    }

    #[derive(Debug, Clone)]
    enum ParentMsg {
        Start,
        RetryFinished,
    }

    impl Message for ParentMsg {}

    #[derive(Clone)]
    struct CompletionParent {
        completions: Arc<AtomicUsize>,
    }

    impl NotPersistentActor for CompletionParent {}

    #[async_trait]
    impl Actor for CompletionParent {
        type Message = ParentMsg;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("CompletionParent", id = %id)
        }

        async fn pre_start(
            &mut self,
            ctx: &mut ActorContext<Self>,
        ) -> Result<(), Error> {
            let retry = RetryActor::new_with_parent_message::<CompletionParent>(
                PassiveTarget,
                PassiveMessage,
                Strategy::FixedInterval(FixedIntervalStrategy::new(
                    2,
                    Duration::from_millis(10),
                )),
                ParentMsg::RetryFinished,
            );
            let _: ActorRef<RetryActor<PassiveTarget>> =
                ctx.create_child("retry", retry).await?;
            Ok(())
        }
    }

    #[async_trait]
    impl Handler<CompletionParent> for CompletionParent {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            message: ParentMsg,
            ctx: &mut ActorContext<CompletionParent>,
        ) -> Result<(), Error> {
            match message {
                ParentMsg::Start => {
                    let retry = ctx
                        .get_child::<RetryActor<PassiveTarget>>("retry")
                        .await?;
                    retry.tell(RetryMessage::Retry).await?;
                }
                ParentMsg::RetryFinished => {
                    self.completions.fetch_add(1, Ordering::SeqCst);
                }
            }
            Ok(())
        }
    }

    #[derive(Clone)]
    struct PassiveTarget;

    impl NotPersistentActor for PassiveTarget {}

    #[derive(Debug, Clone)]
    struct PassiveMessage;

    impl Message for PassiveMessage {}

    impl Actor for PassiveTarget {
        type Message = PassiveMessage;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("PassiveTarget", id = %id)
        }
    }

    #[async_trait]
    impl Handler<PassiveTarget> for PassiveTarget {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            _message: PassiveMessage,
            _ctx: &mut ActorContext<PassiveTarget>,
        ) -> Result<(), Error> {
            Ok(())
        }
    }

    #[derive(Clone)]
    struct CountingTarget {
        deliveries: Arc<AtomicUsize>,
    }

    impl NotPersistentActor for CountingTarget {}

    #[derive(Debug, Clone)]
    struct CountMessage;

    impl Message for CountMessage {}

    impl Actor for CountingTarget {
        type Message = CountMessage;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("CountingTarget", id = %id)
        }
    }

    #[async_trait]
    impl Handler<CountingTarget> for CountingTarget {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            _message: CountMessage,
            _ctx: &mut ActorContext<CountingTarget>,
        ) -> Result<(), Error> {
            self.deliveries.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    #[derive(Clone)]
    pub struct TargetActor {
        counter: usize,
    }

    #[derive(Debug, Clone)]
    pub struct TargetMessage {
        pub source: ActorPath,
        pub message: String,
    }

    impl Message for TargetMessage {}

    impl NotPersistentActor for TargetActor {}

    impl Actor for TargetActor {
        type Message = TargetMessage;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("TargetActor", id = %id)
        }
    }

    #[async_trait]
    impl Handler<TargetActor> for TargetActor {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            message: TargetMessage,
            ctx: &mut ActorContext<TargetActor>,
        ) -> Result<(), Error> {
            assert_eq!(message.message, "Hello from parent");
            self.counter += 1;
            println!("Counter: {}", self.counter);
            if self.counter == 2 {
                let source = ctx
                    .system()
                    .get_actor::<SourceActor>(&message.source)
                    .await
                    .unwrap();
                source
                    .tell(SourceMessage("Hello from child".to_owned()))
                    .await?;
            }
            Ok(())
        }
    }

    #[test(tokio::test)]
    async fn test_retry_actor() {
        let (system, mut runner) = ActorSystem::create(
            CancellationToken::new(),
            CancellationToken::new(),
        );

        tokio::spawn(async move {
            runner.run().await;
        });

        let _: ActorRef<SourceActor> = system
            .create_root_actor("source", SourceActor)
            .await
            .unwrap();

        tokio::time::sleep(Duration::from_secs(5)).await;
    }

    #[derive(Clone)]
    struct StopAfterFirstTarget {
        deliveries: Arc<AtomicUsize>,
    }

    impl NotPersistentActor for StopAfterFirstTarget {}

    #[derive(Debug, Clone)]
    struct StopAfterFirstMessage;

    impl Message for StopAfterFirstMessage {}

    impl Actor for StopAfterFirstTarget {
        type Message = StopAfterFirstMessage;
        type Response = ();
        type Event = ();

        fn get_span(
            id: &str,
            _parent_span: Option<tracing::Span>,
        ) -> tracing::Span {
            info_span!("StopAfterFirstTarget", id = %id)
        }
    }

    #[async_trait]
    impl Handler<StopAfterFirstTarget> for StopAfterFirstTarget {
        async fn handle_message(
            &mut self,
            _path: ActorPath,
            _message: StopAfterFirstMessage,
            ctx: &mut ActorContext<StopAfterFirstTarget>,
        ) -> Result<(), Error> {
            let count = self.deliveries.fetch_add(1, Ordering::SeqCst) + 1;
            if count == 1 {
                ctx.stop(None).await;
            }
            Ok(())
        }
    }

    #[test(tokio::test)]
    async fn test_retry_actor_stops_when_target_unavailable() {
        let (system, mut runner) = ActorSystem::create(
            CancellationToken::new(),
            CancellationToken::new(),
        );

        tokio::spawn(async move {
            runner.run().await;
        });

        let deliveries = Arc::new(AtomicUsize::new(0));
        let retry_actor = RetryActor::new(
            StopAfterFirstTarget {
                deliveries: deliveries.clone(),
            },
            StopAfterFirstMessage,
            Strategy::FixedInterval(FixedIntervalStrategy::new(
                5,
                Duration::from_millis(20),
            )),
        );

        let retry_ref: ActorRef<RetryActor<StopAfterFirstTarget>> = system
            .create_root_actor("retry_stop_on_send_failure", retry_actor)
            .await
            .unwrap();

        retry_ref.tell(RetryMessage::Retry).await.unwrap();

        tokio::time::timeout(Duration::from_secs(1), retry_ref.closed())
            .await
            .expect("retry actor should stop after target becomes unavailable");

        assert_eq!(deliveries.load(Ordering::SeqCst), 1);
    }

    #[test(tokio::test)]
    async fn test_retry_actor_notifies_parent_when_retries_finish() {
        let (system, mut runner) = ActorSystem::create(
            CancellationToken::new(),
            CancellationToken::new(),
        );

        tokio::spawn(async move {
            runner.run().await;
        });

        let completions = Arc::new(AtomicUsize::new(0));
        let parent = CompletionParent {
            completions: completions.clone(),
        };

        let parent_ref: ActorRef<CompletionParent> = system
            .create_root_actor("completion_parent", parent)
            .await
            .unwrap();

        parent_ref.tell(ParentMsg::Start).await.unwrap();

        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                if completions.load(Ordering::SeqCst) == 1 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("parent should receive completion notification");
    }

    #[test(tokio::test)]
    async fn test_retry_actor_ignores_duplicate_retry_start() {
        let (system, mut runner) = ActorSystem::create(
            CancellationToken::new(),
            CancellationToken::new(),
        );

        tokio::spawn(async move {
            runner.run().await;
        });

        let deliveries = Arc::new(AtomicUsize::new(0));
        let retry_actor = RetryActor::new(
            CountingTarget {
                deliveries: deliveries.clone(),
            },
            CountMessage,
            Strategy::NoInterval(crate::NoIntervalStrategy::new(3)),
        );

        let retry_ref: ActorRef<RetryActor<CountingTarget>> = system
            .create_root_actor::<RetryActor<CountingTarget>, _>(
                "retry_duplicate_start",
                retry_actor,
            )
            .await
            .unwrap();

        retry_ref.tell(RetryMessage::Retry).await.unwrap();
        retry_ref.tell(RetryMessage::Retry).await.unwrap();

        tokio::time::timeout(Duration::from_secs(1), async {
            loop {
                if deliveries.load(Ordering::SeqCst) == 3 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("retry actor should deliver exactly one retry cycle");

        tokio::time::timeout(Duration::from_secs(1), retry_ref.closed())
            .await
            .expect("retry actor should stop after exhausting retries");
    }
}