[go: up one dir, main page]

bastion 0.4.5

Fault-tolerant Runtime for Rust applications
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
//!
//! Special module that allows users to interact and communicate with a
//! group of actors through the dispatchers that holds information about
//! actors grouped together.
use crate::{
    child_ref::ChildRef,
    message::{Answer, Message},
    prelude::SendError,
};
use crate::{distributor::Distributor, envelope::SignedMessage};
use anyhow::Result as AnyResult;
use lever::prelude::*;
use std::hash::{Hash, Hasher};
use std::sync::RwLock;
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};
use std::{
    collections::HashMap,
    fmt::{self, Debug},
};
use tracing::{debug, trace};

/// Type alias for the concurrency hashmap. Each key-value pair stores
/// the Bastion identifier as the key and the module name as the value.
pub type DispatcherMap = LOTable<ChildRef, String>;

/// Type alias for the recipients hashset.
/// Each key-value pair stores the Bastion identifier as the key.
pub type RecipientMap = LOTable<ChildRef, ()>;

#[derive(Debug, Clone)]
/// Defines types of the notifications handled by the dispatcher
/// when the group of actors is changing.
pub enum NotificationType {
    /// Represents a notification when a new actor wants to
    /// join to the existing group of actors.
    Register,
    /// Represents a notification when the existing actor
    /// was stopped, killed, suspended or finished an execution.
    Remove,
}

#[derive(Debug, Clone)]
/// Defines types of the notifications handled by the dispatcher
/// when the group of actors is changing.
///
/// If the message can't be delivered to the declared group, then
/// the message will be marked as the "dead letter".
pub enum BroadcastTarget {
    /// Send the broadcasted message to everyone in the system.
    All,
    /// Send the broadcasted message to each actor in group.
    Group(String),
}

/// A `Recipient` is responsible for maintaining it's list
/// of recipients, and deciding which child gets to receive which message.
pub trait Recipient {
    /// Provide this function to declare which recipient will receive the next message
    fn next(&self) -> Option<ChildRef>;
    /// Return all recipients that will receive a broadcast message
    fn all(&self) -> Vec<ChildRef>;
    /// Add this actor to your list of recipients
    fn register(&self, actor: ChildRef);
    /// Remove this actor from your list of recipients
    fn remove(&self, actor: &ChildRef);
}

/// A `RecipientHandler` is a `Recipient` implementor, that can be stored in the dispatcher
pub trait RecipientHandler: Recipient + Send + Sync + Debug {}

impl RecipientHandler for RoundRobinHandler {}

/// The default handler, which does round-robin.
pub type DefaultRecipientHandler = RoundRobinHandler;

#[derive(Debug, Clone, Eq, PartialEq)]
/// Defines the type of the dispatcher.
///
/// The default type is `Anonymous`.
pub enum DispatcherType {
    /// The default kind of the dispatcher which is using for
    /// handling all actors in the cluster. Can be more than
    /// one instance of this type.
    Anonymous,
    /// The dispatcher with a unique name which will be using
    /// for updating and notifying actors in the same group
    /// base on the desired strategy. The logic handling broadcasted
    /// messages and their distribution across the group depends on
    /// the dispatcher's handler.
    Named(String),
}

/// The default handler, which does round-robin.
pub type DefaultDispatcherHandler = RoundRobinHandler;

/// Dispatcher that will do simple round-robin distribution
#[derive(Default, Debug)]
pub struct RoundRobinHandler {
    index: AtomicUsize,
    recipients: RecipientMap,
}

impl RoundRobinHandler {
    fn public_recipients(&self) -> Vec<ChildRef> {
        self.recipients
            .iter()
            .filter_map(|entry| {
                if entry.0.is_public() {
                    Some(entry.0)
                } else {
                    None
                }
            })
            .collect()
    }
}

impl Recipient for RoundRobinHandler {
    fn next(&self) -> Option<ChildRef> {
        let entries = self.public_recipients();

        if entries.is_empty() {
            return None;
        }

        let current_index = self.index.load(Ordering::SeqCst) % entries.len();
        self.index.store(current_index + 1, Ordering::SeqCst);
        entries.get(current_index).map(std::clone::Clone::clone)
    }

    fn all(&self) -> Vec<ChildRef> {
        self.public_recipients()
    }

    fn register(&self, actor: ChildRef) {
        let _ = self.recipients.insert(actor, ());
    }

    fn remove(&self, actor: &ChildRef) {
        let _ = self.recipients.remove(&actor);
    }
}

impl DispatcherHandler for RoundRobinHandler {
    // Will left this implementation as empty.
    fn notify(
        &self,
        _from_child: &ChildRef,
        _entries: &DispatcherMap,
        _notification_type: NotificationType,
    ) {
    }
    // Each child in turn will receive a message.
    fn broadcast_message(&self, entries: &DispatcherMap, message: &Arc<SignedMessage>) {
        let public_childrefs = entries
            .iter()
            .filter_map(|entry| {
                if entry.0.is_public() {
                    Some(entry.0)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        if public_childrefs.is_empty() {
            debug!("no public children to broadcast message to");
            return;
        }
        let current_index = self.index.load(Ordering::SeqCst) % public_childrefs.len();

        if let Some(entry) = public_childrefs.get(current_index) {
            debug!(
                "sending message to child {}/{} - {}",
                current_index + 1,
                entries.len(),
                entry.path()
            );
            entry.tell_anonymously(message.clone()).unwrap();
            self.index.store(current_index + 1, Ordering::SeqCst);
        };
    }
}
/// Generic trait which any custom dispatcher handler must implement for
/// the further usage by the `Dispatcher` instances.
pub trait DispatcherHandler {
    /// Sends the notification of the certain type to each actor in group.
    fn notify(
        &self,
        from_child: &ChildRef,
        entries: &DispatcherMap,
        notification_type: NotificationType,
    );
    /// Broadcasts the message to actors in according to the implemented behaviour.
    fn broadcast_message(&self, entries: &DispatcherMap, message: &Arc<SignedMessage>);
}

/// A generic implementation of the Bastion dispatcher
///
/// The main idea of the dispatcher is to provide an alternative way to
/// communicate between a group of actors. For example, dispatcher can
/// be used when a developer wants to send a specific message or share a
/// local state between the specific group of registered actors with
/// the usage of a custom dispatcher.
pub struct Dispatcher {
    /// Defines the type of the dispatcher.
    dispatcher_type: DispatcherType,
    /// The handler used for a notification or a message.
    handler: Box<dyn DispatcherHandler + Send + Sync + 'static>,
    /// Special field that stores information about all
    /// registered actors in the group.
    actors: DispatcherMap,
}

impl Dispatcher {
    /// Returns the type of the dispatcher.
    pub fn dispatcher_type(&self) -> DispatcherType {
        self.dispatcher_type.clone()
    }

    /// Returns the used handler by the dispatcher.
    pub fn handler(&self) -> &(dyn DispatcherHandler + Send + Sync + 'static) {
        &*self.handler
    }

    /// Sets the dispatcher type.
    pub fn with_dispatcher_type(mut self, dispatcher_type: DispatcherType) -> Self {
        trace!("Setting dispatcher the {:?} type.", dispatcher_type);
        self.dispatcher_type = dispatcher_type;
        self
    }

    /// Creates a dispatcher with a specific dispatcher type.
    pub fn with_type(dispatcher_type: DispatcherType) -> Self {
        trace!(
            "Instanciating a dispatcher with type {:?}.",
            dispatcher_type
        );
        Self {
            dispatcher_type,
            handler: Box::new(DefaultDispatcherHandler::default()),
            actors: Default::default(),
        }
    }

    /// Sets the handler for the dispatcher.
    pub fn with_handler(
        mut self,
        handler: Box<dyn DispatcherHandler + Send + Sync + 'static>,
    ) -> Self {
        trace!(
            "Setting handler for the {:?} dispatcher.",
            self.dispatcher_type
        );
        self.handler = handler;
        self
    }

    /// Appends the information about actor to the dispatcher.
    pub(crate) fn register(&self, key: &ChildRef, module_name: String) -> AnyResult<()> {
        self.actors.insert(key.to_owned(), module_name)?;
        self.handler
            .notify(key, &self.actors, NotificationType::Register);
        Ok(())
    }

    /// Removes and then returns the record from the registry by the given key.
    /// Returns `None` when the record wasn't found by the given key.
    pub(crate) fn remove(&self, key: &ChildRef) {
        if self.actors.remove(key).is_ok() {
            self.handler
                .notify(key, &self.actors, NotificationType::Remove);
        }
    }

    /// Forwards the message to the handler for processing.
    pub fn notify(&self, from_child: &ChildRef, notification_type: NotificationType) {
        self.handler
            .notify(from_child, &self.actors, notification_type)
    }

    /// Sends the message to the group of actors.
    /// The logic of who and how should receive the message relies onto
    /// the handler implementation.
    pub fn broadcast_message(&self, message: &Arc<SignedMessage>) {
        self.handler.broadcast_message(&self.actors, &message);
    }
}

impl Debug for Dispatcher {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Dispatcher(type: {:?}, actors: {:?})",
            self.dispatcher_type,
            self.actors.len()
        )
    }
}

impl DispatcherType {
    pub(crate) fn name(&self) -> String {
        match self {
            DispatcherType::Anonymous => String::from("__Anonymous__"),
            DispatcherType::Named(value) => value.to_owned(),
        }
    }
}

impl Default for Dispatcher {
    fn default() -> Self {
        Dispatcher {
            dispatcher_type: DispatcherType::default(),
            handler: Box::new(DefaultDispatcherHandler::default()),
            actors: LOTable::new(),
        }
    }
}

impl Default for DispatcherType {
    fn default() -> Self {
        DispatcherType::Anonymous
    }
}

#[allow(clippy::derive_hash_xor_eq)]
impl Hash for DispatcherType {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name().hash(state);
    }
}

impl Into<DispatcherType> for String {
    fn into(self) -> DispatcherType {
        match self == DispatcherType::Anonymous.name() {
            true => DispatcherType::Anonymous,
            false => DispatcherType::Named(self),
        }
    }
}

#[derive(Debug)]
/// The global dispatcher of bastion the cluster.
///
/// The main purpose of this dispatcher is be a point through
/// developers can communicate with actors through group names.
pub(crate) struct GlobalDispatcher {
    /// Storage for all registered group of actors.
    pub dispatchers: LOTable<DispatcherType, Arc<Box<Dispatcher>>>,
    // TODO: switch to LOTable once lever implements write optimized granularity
    pub distributors: Arc<RwLock<HashMap<Distributor, Box<(dyn RecipientHandler)>>>>,
}

impl GlobalDispatcher {
    /// Creates a new instance of the global registry.
    pub(crate) fn new() -> Self {
        GlobalDispatcher {
            dispatchers: LOTable::new(),
            distributors: Arc::new(RwLock::new(HashMap::new()))
            // TODO: switch to LOTable once lever implements write optimized granularity
            // distributors: LOTableBuilder::new()
                //.with_concurrency(TransactionConcurrency::Optimistic)
                //.with_isolation(TransactionIsolation::Serializable)
                //.build(),
        }
    }

    /// Appends the information about actor to the dispatcher.
    pub(crate) fn register(
        &self,
        dispatchers: &[DispatcherType],
        child_ref: &ChildRef,
        module_name: String,
    ) -> AnyResult<()> {
        dispatchers
            .iter()
            .filter(|key| self.dispatchers.contains_key(*key))
            .map(|key| {
                if let Some(dispatcher) = self.dispatchers.get(key) {
                    dispatcher.register(child_ref, module_name.clone())
                } else {
                    Ok(())
                }
            })
            .collect::<AnyResult<Vec<_>>>()?;
        Ok(())
    }

    /// Removes and then returns the record from the registry by the given key.
    /// Returns `None` when the record wasn't found by the given key.
    pub(crate) fn remove(&self, dispatchers: &[DispatcherType], child_ref: &ChildRef) {
        dispatchers
            .iter()
            .filter(|key| self.dispatchers.contains_key(*key))
            .for_each(|key| {
                if let Some(dispatcher) = self.dispatchers.get(key) {
                    dispatcher.remove(child_ref)
                }
            })
    }

    /// Passes the notification from the actor to everyone that registered in the same
    /// groups as the caller.
    pub(crate) fn notify(
        &self,
        from_actor: &ChildRef,
        dispatchers: &[DispatcherType],
        notification_type: NotificationType,
    ) {
        self.dispatchers
            .iter()
            .filter(|pair| dispatchers.contains(&pair.0))
            .for_each(|pair| {
                let dispatcher = pair.1;
                dispatcher.notify(from_actor, notification_type.clone())
            })
    }

    /// Broadcasts the given message in according with the specified target.
    pub(crate) fn broadcast_message(&self, target: BroadcastTarget, message: &Arc<SignedMessage>) {
        let acked_dispatchers = match target {
            BroadcastTarget::All => self
                .dispatchers
                .iter()
                .map(|pair| pair.0.name().into())
                .collect(),
            BroadcastTarget::Group(name) => {
                let target_dispatcher = name.into();
                vec![target_dispatcher]
            }
        };

        for dispatcher_type in acked_dispatchers {
            match self.dispatchers.get(&dispatcher_type) {
                Some(dispatcher) => {
                    dispatcher.broadcast_message(&message.clone());
                }
                // TODO: Put the message into the dead queue
                None => {
                    let name = dispatcher_type.name();
                    debug!(
                        "The message can't be delivered to the group with the '{}' name.",
                        name
                    );
                }
            }
        }
    }

    pub(crate) fn tell<M>(&self, distributor: Distributor, message: M) -> Result<(), SendError>
    where
        M: Message,
    {
        let child = self.next(distributor)?.ok_or(SendError::EmptyRecipient)?;
        child.try_tell_anonymously(message).map(Into::into)
    }

    pub(crate) fn ask<M>(&self, distributor: Distributor, message: M) -> Result<Answer, SendError>
    where
        M: Message,
    {
        let child = self.next(distributor)?.ok_or(SendError::EmptyRecipient)?;
        child.try_ask_anonymously(message).map(Into::into)
    }

    pub(crate) fn ask_everyone<M>(
        &self,
        distributor: Distributor,
        message: M,
    ) -> Result<Vec<Answer>, SendError>
    where
        M: Message + Clone,
    {
        let all_children = self.all(distributor)?;
        if all_children.is_empty() {
            Err(SendError::EmptyRecipient)
        } else {
            all_children
                .iter()
                .map(|child| child.try_ask_anonymously(message.clone()))
                .collect::<Result<Vec<_>, _>>()
        }
    }

    pub(crate) fn tell_everyone<M>(
        &self,
        distributor: Distributor,
        message: M,
    ) -> Result<Vec<()>, SendError>
    where
        M: Message + Clone,
    {
        let all_children = self.all(distributor)?;
        if all_children.is_empty() {
            Err(SendError::EmptyRecipient)
        } else {
            all_children
                .iter()
                .map(|child| child.try_tell_anonymously(message.clone()))
                .collect()
        }
    }

    fn next(&self, distributor: Distributor) -> Result<Option<ChildRef>, SendError> {
        self.distributors
            .read()
            .map_err(|error| {
                SendError::Other(anyhow::anyhow!(
                    "couldn't get read lock on distributors {:?}",
                    error
                ))
            })?
            .get(&distributor)
            .map(|recipient| recipient.next())
            .ok_or_else(|| SendError::from(distributor))
    }

    fn all(&self, distributor: Distributor) -> Result<Vec<ChildRef>, SendError> {
        self.distributors
            .read()
            .map_err(|error| {
                SendError::Other(anyhow::anyhow!(
                    "couldn't get read lock on distributors {:?}",
                    error
                ))
            })?
            .get(&distributor)
            .map(|recipient| recipient.all())
            .ok_or_else(|| SendError::from(distributor))
    }

    /// Adds dispatcher to the global registry.
    pub(crate) fn register_dispatcher(&self, dispatcher: &Arc<Box<Dispatcher>>) -> AnyResult<()> {
        let dispatcher_type = dispatcher.dispatcher_type();
        let is_registered = self.dispatchers.contains_key(&dispatcher_type);

        if is_registered && dispatcher_type != DispatcherType::Anonymous {
            debug!(
                "The dispatcher with the '{:?}' name already registered in the cluster.",
                dispatcher_type
            );
            return Ok(());
        }

        let instance = dispatcher.clone();
        self.dispatchers.insert(dispatcher_type, instance)?;
        Ok(())
    }

    /// Removes dispatcher from the global registry.
    pub(crate) fn remove_dispatcher(&self, dispatcher: &Arc<Box<Dispatcher>>) -> AnyResult<()> {
        self.dispatchers.remove(&dispatcher.dispatcher_type())?;
        Ok(())
    }

    /// Appends the information about actor to the recipients.
    pub(crate) fn register_recipient(
        &self,
        distributor: &Distributor,
        child_ref: ChildRef,
    ) -> AnyResult<()> {
        let mut distributors = self.distributors.write().map_err(|error| {
            anyhow::anyhow!("couldn't get read lock on distributors {:?}", error)
        })?;
        if let Some(recipients) = distributors.get(&distributor) {
            recipients.register(child_ref);
        } else {
            let recipients = DefaultRecipientHandler::default();
            recipients.register(child_ref);
            distributors.insert(
                distributor.clone(),
                Box::new(recipients) as Box<(dyn RecipientHandler)>,
            );
        };
        Ok(())
    }

    pub(crate) fn remove_recipient(
        &self,
        distributor_list: &[Distributor],
        child_ref: &ChildRef,
    ) -> AnyResult<()> {
        let distributors = self.distributors.write().map_err(|error| {
            anyhow::anyhow!("couldn't get read lock on distributors {:?}", error)
        })?;
        distributor_list.iter().for_each(|distributor| {
            distributors
                .get(&distributor)
                .map(|recipients| recipients.remove(child_ref));
        });
        Ok(())
    }

    /// Adds distributor to the global registry.
    pub(crate) fn register_distributor(&self, distributor: &Distributor) -> AnyResult<()> {
        let mut distributors = self.distributors.write().map_err(|error| {
            anyhow::anyhow!("couldn't get read lock on distributors {:?}", error)
        })?;
        if distributors.contains_key(&distributor) {
            debug!(
                "The distributor with the '{:?}' name already registered in the cluster.",
                distributor
            );
        } else {
            distributors.insert(
                distributor.clone(),
                Box::new(DefaultRecipientHandler::default()),
            );
        }
        Ok(())
    }

    /// Removes distributor from the global registry if it has no remaining recipients.
    pub(crate) fn remove_distributor(&self, distributor: &Distributor) -> AnyResult<()> {
        let mut distributors = self.distributors.write().map_err(|error| {
            anyhow::anyhow!("couldn't get write lock on distributors {:?}", error)
        })?;
        if distributors
            .get(&distributor)
            .map(|recipient| recipient.all().is_empty())
            .unwrap_or_default()
        {
            distributors.remove(distributor);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::child_ref::ChildRef;
    use crate::context::BastionId;
    use crate::dispatcher::*;
    use crate::envelope::{RefAddr, SignedMessage};
    use crate::message::Msg;
    use crate::path::BastionPath;
    use futures::channel::mpsc;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    struct CustomHandler {
        called: Arc<Mutex<bool>>,
    }

    // Here we actually want both
    // the locking mechanism and
    // the bool value
    #[allow(clippy::mutex_atomic)]
    impl CustomHandler {
        pub fn new(value: bool) -> Self {
            CustomHandler {
                called: Arc::new(Mutex::new(value)),
            }
        }

        pub fn was_called(&self) -> bool {
            *self.called.clone().lock().unwrap()
        }
    }

    impl DispatcherHandler for CustomHandler {
        fn notify(
            &self,
            _from_child: &ChildRef,
            _entries: &DispatcherMap,
            _notification_type: NotificationType,
        ) {
            let handler_field_ref = self.called.clone();
            let mut data = handler_field_ref.lock().unwrap();
            *data = true;
        }

        fn broadcast_message(&self, _entries: &DispatcherMap, _message: &Arc<SignedMessage>) {
            let handler_field_ref = self.called.clone();
            let mut data = handler_field_ref.lock().unwrap();
            *data = true;
        }
    }

    #[test]
    fn test_get_dispatcher_type_as_anonymous() {
        let instance = Dispatcher::default();

        assert_eq!(instance.dispatcher_type(), DispatcherType::Anonymous);
    }

    #[test]
    fn test_get_dispatcher_type_as_named() {
        let name = "test_group".to_string();
        let dispatcher_type = DispatcherType::Named(name);
        let instance = Dispatcher::with_type(dispatcher_type.clone());

        assert_eq!(instance.dispatcher_type(), dispatcher_type);
    }

    #[test]
    fn test_local_dispatcher_append_child_ref() {
        let instance = Dispatcher::default();
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        assert_eq!(instance.actors.contains_key(&child_ref), false);

        instance
            .register(&child_ref, "my::test::module".to_string())
            .unwrap();
        assert_eq!(instance.actors.contains_key(&child_ref), true);
    }

    #[test]
    fn test_dispatcher_remove_child_ref() {
        let instance = Dispatcher::default();
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        instance
            .register(&child_ref, "my::test::module".to_string())
            .unwrap();
        assert_eq!(instance.actors.contains_key(&child_ref), true);

        instance.remove(&child_ref);
        assert_eq!(instance.actors.contains_key(&child_ref), false);
    }

    #[test]
    fn test_local_dispatcher_notify() {
        let handler = Box::new(CustomHandler::new(false));
        let instance = Dispatcher::default().with_handler(handler.clone());
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        instance.notify(&child_ref, NotificationType::Register);
        let handler_was_called = handler.was_called();
        assert_eq!(handler_was_called, true);
    }

    #[test]
    fn test_local_dispatcher_broadcast_message() {
        let handler = Box::new(CustomHandler::new(false));
        let instance = Dispatcher::default().with_handler(handler.clone());
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());

        const DATA: &str = "A message containing data (ask).";
        let message = Arc::new(SignedMessage::new(
            Msg::broadcast(DATA),
            RefAddr::new(path, sender),
        ));

        instance.broadcast_message(&message);
        let handler_was_called = handler.was_called();
        assert_eq!(handler_was_called, true);
    }

    #[test]
    fn test_global_dispatcher_add_local_dispatcher() {
        let dispatcher_type = DispatcherType::Named("test".to_string());
        let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone())));
        let global_dispatcher = GlobalDispatcher::new();

        assert_eq!(
            global_dispatcher.dispatchers.contains_key(&dispatcher_type),
            false
        );

        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();
        assert_eq!(
            global_dispatcher.dispatchers.contains_key(&dispatcher_type),
            true
        );
    }

    #[test]
    fn test_global_dispatcher_remove_local_dispatcher() {
        let dispatcher_type = DispatcherType::Named("test".to_string());
        let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone())));
        let global_dispatcher = GlobalDispatcher::new();

        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();
        assert_eq!(
            global_dispatcher.dispatchers.contains_key(&dispatcher_type),
            true
        );

        global_dispatcher
            .remove_dispatcher(&local_dispatcher)
            .unwrap();
        assert_eq!(
            global_dispatcher.dispatchers.contains_key(&dispatcher_type),
            false
        );
    }

    #[test]
    fn test_global_dispatcher_register_actor() {
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        let dispatcher_type = DispatcherType::Named("test".to_string());
        let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone())));
        let actor_groups = vec![dispatcher_type];
        let module_name = "my::test::module".to_string();

        let global_dispatcher = GlobalDispatcher::new();
        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();

        assert_eq!(local_dispatcher.actors.contains_key(&child_ref), false);

        global_dispatcher
            .register(&actor_groups, &child_ref, module_name)
            .unwrap();
        assert_eq!(local_dispatcher.actors.contains_key(&child_ref), true);
    }

    #[test]
    fn test_global_dispatcher_remove_actor() {
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        let dispatcher_type = DispatcherType::Named("test".to_string());
        let local_dispatcher = Arc::new(Box::new(Dispatcher::with_type(dispatcher_type.clone())));
        let actor_groups = vec![dispatcher_type];
        let module_name = "my::test::module".to_string();

        let global_dispatcher = GlobalDispatcher::new();
        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();

        global_dispatcher
            .register(&actor_groups, &child_ref, module_name)
            .unwrap();
        assert_eq!(local_dispatcher.actors.contains_key(&child_ref), true);

        global_dispatcher.remove(&actor_groups, &child_ref);
        assert_eq!(local_dispatcher.actors.contains_key(&child_ref), false);
    }

    #[test]
    fn test_global_dispatcher_notify() {
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        let dispatcher_type = DispatcherType::Named("test".to_string());
        let handler = Box::new(CustomHandler::new(false));
        let local_dispatcher = Arc::new(Box::new(
            Dispatcher::with_type(dispatcher_type.clone()).with_handler(handler.clone()),
        ));
        let actor_groups = vec![dispatcher_type];
        let module_name = "my::test::module".to_string();

        let global_dispatcher = GlobalDispatcher::new();
        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();
        global_dispatcher
            .register(&actor_groups, &child_ref, module_name)
            .unwrap();

        global_dispatcher.notify(&child_ref, &actor_groups, NotificationType::Register);
        let handler_was_called = handler.was_called();
        assert_eq!(handler_was_called, true);
    }

    #[test]
    fn test_global_dispatcher_broadcast_message() {
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        let dispatcher_type = DispatcherType::Named("test".to_string());
        let handler = Box::new(CustomHandler::new(false));
        let local_dispatcher = Arc::new(Box::new(
            Dispatcher::with_type(dispatcher_type.clone()).with_handler(handler.clone()),
        ));
        let actor_groups = vec![dispatcher_type];
        let module_name = "my::test::module".to_string();

        let global_dispatcher = GlobalDispatcher::new();
        global_dispatcher
            .register_dispatcher(&local_dispatcher)
            .unwrap();
        global_dispatcher
            .register(&actor_groups, &child_ref, module_name)
            .unwrap();

        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        const DATA: &str = "A message containing data (ask).";
        let message = Arc::new(SignedMessage::new(
            Msg::broadcast(DATA),
            RefAddr::new(path, sender),
        ));

        global_dispatcher.broadcast_message(BroadcastTarget::Group("".to_string()), &message);
        let handler_was_called = handler.was_called();
        assert_eq!(handler_was_called, true);
    }

    #[test]
    fn test_global_dispatcher_removes_distributor_with_no_recipients() {
        let global_dispatcher = GlobalDispatcher::new();
        let distributor = Distributor::named("test-distributor");
        global_dispatcher
            .register_distributor(&distributor)
            .unwrap();
        assert!(!global_dispatcher.distributors.read().unwrap().is_empty());
        global_dispatcher.remove_distributor(&distributor).unwrap();
        assert!(global_dispatcher.distributors.read().unwrap().is_empty());
    }

    #[test]
    fn test_global_dispatcher_keeps_distributor_with_recipients() {
        let bastion_id = BastionId::new();
        let (sender, _) = mpsc::unbounded();
        let path = Arc::new(BastionPath::root());
        let name = "test_name".to_string();
        let child_ref = ChildRef::new(bastion_id, sender, name, path);

        let global_dispatcher = GlobalDispatcher::new();
        let distributor = Distributor::named("test-distributor");
        global_dispatcher
            .register_distributor(&distributor)
            .unwrap();
        global_dispatcher
            .register_recipient(&distributor, child_ref.clone())
            .unwrap();
        global_dispatcher.remove_distributor(&distributor).unwrap();
        // Should maintain the dispatcher because it still has a recipient.
        assert!(!global_dispatcher.distributors.read().unwrap().is_empty());

        global_dispatcher
            .remove_recipient(&[distributor], &child_ref)
            .unwrap();
        global_dispatcher.remove_distributor(&distributor).unwrap();
        // Distributor is now removed because it has no remaining recipients.
        assert!(global_dispatcher.distributors.read().unwrap().is_empty());
    }
}