sids 1.0.3

An actor-model concurrency framework providing abstraction over async and blocking actors.
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
use std::{collections::HashMap, sync::atomic::AtomicUsize, time::Duration};

use crate::actors::actor::{ActorImpl, BlockingActorImpl};
use crate::config::SidsConfig;

use super::{
    actor::Actor,
    actor_ref::{ActorRef, BlockingActorRef},
    channel_factory::ChannelFactory,
    error::{ActorError, ActorResult},
    messages::{Message, ResponseMessage},
};
use log::{info, warn};
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::time::timeout;

#[cfg(feature = "visualize")]
use crate::supervision::{ActorMetrics, SupervisionData, SupervisionSummary};

// Actor name constants for logging
const GUARDIAN_ACTOR_NAME: &str = "GUARDIAN";
const ACTOR_SYSTEM_NAME: &str = "Actor System";

/// The Guardian is a special actor that listens for shutdown signals and broadcasts them to all actors.
/// It also responds to pings to confirm that the system is alive.
struct Guardian {
    shutdown_tx: Option<broadcast::Sender<()>>,
}

impl<MType: Send + Clone> Actor<MType, ResponseMessage> for Guardian {
    async fn receive(&mut self, message: Message<MType, ResponseMessage>) {
        info!(actor=GUARDIAN_ACTOR_NAME; "Guardian received a message");
        if message.stop {
            info!(actor=GUARDIAN_ACTOR_NAME; "Guardian received a stop message. Shutting down...");
            if let Some(ref shutdown_tx) = self.shutdown_tx {
                let _ = shutdown_tx.send(());
                info!(actor=GUARDIAN_ACTOR_NAME; "Shutdown signal broadcast to all actors");
            }
        }
        match message.responder {
            Some(responder) => {
                responder.handle(ResponseMessage::Success).await;
            }
            None => {
                info!("No responder found");
            }
        }
    }
}

/// The ActorSystem is the main entry point for the actor system. It is responsible for creating the guardian actor and sending messages to the guardian actor.
///
/// The ActorSystem is designed to be an actor reference for the guardian actor that manages all other actors in the system.
/// In practice, it is the only actor_reference that is directly interacted with by the user.
///
/// # Example
/// ```rust
/// use sids::actors;
/// use sids::actors::messages::{Message, ResponseMessage};
/// use sids::actors::actor::Actor;
///
/// /// Sample actor type to receive message.
///
/// struct SampleActor;
/// impl Actor<String, ResponseMessage> for SampleActor {
///    async fn receive(&mut self, message: Message<String, ResponseMessage>) {
///       message.responder.unwrap().handle(ResponseMessage::Success).await;
///    }
/// }
///
/// pub async fn run_system() {
///    let actor = SampleActor;
///    
///    // Creates a new actor system that uses String as the message type.
///    let mut actor_system = actors::start_actor_system::<String, ResponseMessage>();
///    let (handler, rx) = actors::get_response_handler::<ResponseMessage>();
///    let message = Message { payload: Some("My String Message".to_string()), stop: false, responder: Some(handler), blocking: None };
///    actors::spawn_actor(&mut actor_system, actor, Some("Sample Actor".to_string())).await;
///    actors::send_message_by_id(&mut actor_system, 1, message).await;
///    let response = rx.await.expect("Failed to receive response");
///    assert_eq!(response, ResponseMessage::Success);
/// }
///
/// ```
pub struct ActorSystem<MType: Send + Clone + 'static, Response: Send + Clone + 'static> {
    _guardian: ActorRef<MType, ResponseMessage>,
    actors: HashMap<u32, ActorRef<MType, Response>>,
    blocking_actors: HashMap<u32, BlockingActorRef<MType, Response>>,
    actor_names: HashMap<u32, String>,
    total_messages: &'static AtomicUsize,
    total_threads: &'static AtomicUsize,
    snd: mpsc::Sender<Message<MType, ResponseMessage>>,
    shutdown_tx: broadcast::Sender<()>,
    actor_buffer_size: usize,
    shutdown_timeout_ms: Option<u64>,
    #[cfg(feature = "visualize")]
    supervision: SupervisionData,
}

impl<MType: Send + Clone + 'static, Response: Send + Clone + 'static>
    ChannelFactory<MType, Response> for ActorSystem<MType, Response>
{
    /// Creates a new actor channel with the configured buffer size. Returns a sender and receiver for the channel.
    fn create_actor_channel(
        &self,
    ) -> (
        tokio::sync::mpsc::Sender<Message<MType, Response>>,
        tokio::sync::mpsc::Receiver<Message<MType, Response>>,
    ) {
        mpsc::channel::<Message<MType, Response>>(self.actor_buffer_size)
    }

    /// Creates a new blocking actor channel. Returns a sender and receiver for the channel.
    fn create_blocking_actor_channel(
        &self,
    ) -> (
        std::sync::mpsc::Sender<Message<MType, Response>>,
        std::sync::mpsc::Receiver<Message<MType, Response>>,
    ) {
        std::sync::mpsc::channel::<Message<MType, Response>>()
    }

    /// Creates a new oneshot response channel. Returns a sender and receiver for the channel.
    fn create_response_channel(
        &self,
    ) -> (
        tokio::sync::oneshot::Sender<Response>,
        tokio::sync::oneshot::Receiver<Response>,
    ) {
        oneshot::channel::<Response>()
    }

    /// Creates a new onehot blocking response channel. Returns a sender and receiver for the channel.
    fn create_blocking_response_channel(
        &self,
    ) -> (
        std::sync::mpsc::SyncSender<Response>,
        std::sync::mpsc::Receiver<Response>,
    ) {
        // Buffer size of one because responses should only ever be sent one time.
        std::sync::mpsc::sync_channel::<Response>(1)
    }
}

impl<MType: Send + Clone + 'static, Response: Send + Clone + 'static> ActorSystem<MType, Response> {
    /// Create a new ActorSystem
    ///
    /// The ActorSystem will start by launching a guardian, which is a non-blocking officer-actor that manages all other actors in the system.
    /// The guardian will be dormant until start_system is called in the ActorSystem.
    pub(super) fn new() -> Self {
        Self::new_with_config(SidsConfig::default())
    }

    /// Create a new ActorSystem with a custom configuration.
    pub(super) fn new_with_config(config: SidsConfig) -> Self {
        let actor_buffer_size = config.configuration.actor_buffer_size;
        let shutdown_timeout_ms = config.configuration.shutdown_timeout_ms;
        let (tx, rx) = mpsc::channel::<Message<MType, ResponseMessage>>(actor_buffer_size);
        let (shutdown_tx, _) = broadcast::channel::<()>(1);
        info!(actor = "GUARDIAN"; "Guardian channel and actor created. Launching...");
        info!(actor = "GUARDIAN"; "Guardian actor spawned");
        let guardian = ActorImpl::new(
            Some("Guardian Type".to_string()),
            Guardian {
                shutdown_tx: Some(shutdown_tx.clone()),
            },
            rx,
            None,
        );
        info!(actor = "GUARDIAN"; "Actor system created");
        static MESSAGE_MONITOR: AtomicUsize = AtomicUsize::new(0);
        static THREAD_MONITOR: AtomicUsize = AtomicUsize::new(0);
        let actor_ref = ActorRef::new(guardian, tx.clone(), &THREAD_MONITOR, &MESSAGE_MONITOR);
        let actors = HashMap::<u32, ActorRef<MType, Response>>::new();
        let blocking_actors = HashMap::new();
        let actor_names = HashMap::new();
        ActorSystem {
            _guardian: actor_ref,
            actors,
            blocking_actors,
            actor_names,
            total_messages: &MESSAGE_MONITOR,
            total_threads: &THREAD_MONITOR,
            snd: tx,
            shutdown_tx,
            actor_buffer_size,
            shutdown_timeout_ms,
            #[cfg(feature = "visualize")]
            supervision: SupervisionData::new(),
        }
    }

    pub async fn spawn_actor<T>(&mut self, actor: T, name: Option<String>)
    where
        T: Actor<MType, Response> + 'static,
    {
        info!(actor=ACTOR_SYSTEM_NAME;"Spawning actor within the actor system.");
        let (snd, rec) = self.create_actor_channel();
        let shutdown_rx = self.shutdown_tx.subscribe();
        let actor_impl = ActorImpl::new(name.clone(), actor, rec, Some(shutdown_rx));
        let actor_ref = ActorRef::new(actor_impl, snd, self.total_threads, self.total_messages);
        let actor_id = self.actors.len() as u32;
        self.actors.insert(actor_id, actor_ref);

        // Store actor name
        let actor_name = name
            .clone()
            .unwrap_or_else(|| format!("Actor<{}>", actor_id));
        self.actor_names.insert(actor_id, actor_name.clone());

        #[cfg(feature = "visualize")]
        {
            self.record_actor_spawn(actor_id, actor_name);
        }

        info!(actor=ACTOR_SYSTEM_NAME; "Actor spawned successfully with id: {}", actor_id);
    }

    pub(super) fn spawn_blocking_actor<T>(&mut self, actor: T, name: Option<String>)
    where
        T: Actor<MType, Response> + 'static,
    {
        info!(actor=ACTOR_SYSTEM_NAME; "Spawning blocking actor within the actor system.");
        let (snd, rec) = self.create_blocking_actor_channel();
        let shutdown_rx = self.shutdown_tx.subscribe();
        let actor_impl = BlockingActorImpl::new(name.clone(), actor, rec, Some(shutdown_rx));
        let actor_ref =
            BlockingActorRef::new(actor_impl, snd, self.total_threads, self.total_messages);
        let actor_id = self.blocking_actors.len() as u32;
        self.blocking_actors.insert(actor_id, actor_ref);

        // Store actor name
        let actor_name = name
            .clone()
            .unwrap_or_else(|| format!("BlockingActor<{}>", actor_id));
        self.actor_names.insert(actor_id, actor_name.clone());

        #[cfg(feature = "visualize")]
        {
            self.record_actor_spawn(actor_id, actor_name);
        }

        info!(actor=ACTOR_SYSTEM_NAME; "Blocking actor spawned successfully with id: {}", actor_id);
    }

    pub(super) async fn send_message_to_actor(
        &mut self,
        actor_id: u32,
        message: Message<MType, Response>,
    ) -> ActorResult<()> {
        if let Message {
            payload: _,
            stop: _,
            responder: None,
            blocking: Some(_),
        } = &message
        {
            let blocking_actor = self
                .blocking_actors
                .get_mut(&actor_id)
                .ok_or(ActorError::ActorNotFound { id: actor_id })?;
            blocking_actor.send(message);

            #[cfg(feature = "visualize")]
            {
                self.record_message_processed(actor_id);
            }
        } else if let Message {
            payload: _,
            stop: _,
            responder: _,
            blocking: None,
        } = &message
        {
            let actor = self
                .actors
                .get_mut(&actor_id)
                .ok_or(ActorError::ActorNotFound { id: actor_id })?;
            actor.send(message).await;

            #[cfg(feature = "visualize")]
            {
                self.record_message_processed(actor_id);
            }
        } else {
            warn!("No actor found with id: {}", actor_id);
        }
        Ok(())
    }

    pub(super) async fn ping_system(&self) -> ActorResult<()> {
        info!("Pinging system");
        self.snd
            .send(Message {
                payload: None,
                stop: false,
                responder: None,
                blocking: None,
            })
            .await
            .map_err(|e| ActorError::SendFailed {
                reason: format!("Failed to ping guardian: {}", e),
            })?;
        Ok(())
    }
    /// Send a shutdown signal to the guardian, which will broadcast shutdown to all actors.
    pub async fn shutdown(&self) -> ActorResult<()> {
        info!("Sending shutdown signal to guardian");
        let (handler, rx) = self.create_guardian_response_channel();
        self.snd
            .send(Message {
                payload: None,
                stop: true,
                responder: Some(handler),
                blocking: None,
            })
            .await
            .map_err(|e| ActorError::SendFailed {
                reason: format!("Failed to send shutdown: {}", e),
            })?;

        if let Some(timeout_ms) = self.shutdown_timeout_ms {
            match timeout(Duration::from_millis(timeout_ms), rx).await {
                Ok(result) => result
                    .map(|_| {
                        info!("Guardian confirmed shutdown");
                    })
                    .map_err(|_| ActorError::GuardianNotResponding),
                Err(_) => Err(ActorError::ShutdownTimeout),
            }
        } else {
            rx.await
                .map(|_| {
                    info!("Guardian confirmed shutdown");
                })
                .map_err(|_| ActorError::GuardianNotResponding)
        }
    }

    /// Get a receiver for the shutdown broadcast signal.
    /// Useful if you want to await system shutdown outside the actor system.
    pub fn subscribe_shutdown(&self) -> broadcast::Receiver<()> {
        self.shutdown_tx.subscribe()
    }

    fn create_guardian_response_channel(
        &self,
    ) -> (
        super::response_handler::BoxedResponseHandler<ResponseMessage>,
        tokio::sync::oneshot::Receiver<ResponseMessage>,
    ) {
        use super::response_handler::from_oneshot;
        let (tx, rx) = oneshot::channel::<ResponseMessage>();
        let handler = from_oneshot(tx);
        (handler, rx)
    }
    pub fn get_actor_ref(&self, id: u32) -> ActorResult<ActorRef<MType, Response>> {
        self.actors
            .get(&id)
            .cloned()
            .ok_or(ActorError::ActorNotFound { id })
    }

    /// Sends a stop message to a specific actor by ID.
    /// Returns an error if the actor does not exist.
    pub async fn stop_actor(&mut self, id: u32) -> ActorResult<()> {
        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        self.send_message_to_actor(id, stop_message).await
    }

    /// Returns a list of all actors with their IDs and names.
    /// Names are returned as they were provided during spawn, or auto-generated if none was provided.
    pub fn list_actors(&self) -> Vec<(u32, String)> {
        let mut actors = Vec::new();

        // Collect async actors
        for (id, _) in self.actors.iter() {
            if let Some(name) = self.actor_names.get(id) {
                actors.push((*id, name.clone()));
            }
        }

        // Collect blocking actors
        for (id, _) in self.blocking_actors.iter() {
            if let Some(name) = self.actor_names.get(id) {
                actors.push((*id, name.clone()));
            }
        }

        actors.sort_by_key(|(id, _)| *id);
        actors
    }

    /// Finds an actor ID by its name.
    /// Returns the first actor found with the matching name.
    /// Returns an error if no actor with that name exists.
    pub fn find_actor_by_name(&self, name: &str) -> ActorResult<u32> {
        self.actor_names
            .iter()
            .find(|(_, actor_name)| actor_name.as_str() == name)
            .map(|(id, _)| *id)
            .ok_or(ActorError::InvalidState {
                reason: format!("Actor with name '{}' not found", name),
            })
    }

    /// Checks if an actor with the given ID exists in the system.
    pub fn actor_exists(&self, id: u32) -> bool {
        self.actors.contains_key(&id) || self.blocking_actors.contains_key(&id)
    }

    pub fn get_actor_count(&self) -> usize {
        self.actors.len()
    }

    pub fn get_thread_count_reference(&self) -> &'static AtomicUsize {
        self.total_messages
    }

    pub fn get_message_count_reference(&self) -> &'static AtomicUsize {
        self.total_threads
    }

    pub fn get_thread_count(&self) -> usize {
        self.total_threads
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    pub fn get_message_count(&self) -> usize {
        self.total_messages
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    #[cfg(feature = "visualize")]
    pub fn record_actor_spawn(&mut self, actor_id: u32, actor_type: String) {
        let actor_id_str = format!("actor-{}", actor_id);
        let actor_metrics = ActorMetrics::new(actor_id_str, actor_type);
        self.supervision
            .actors
            .insert(format!("actor-{}", actor_id), actor_metrics);
    }

    #[cfg(feature = "visualize")]
    pub fn record_message_processed(&mut self, actor_id: u32) {
        self.supervision
            .record_message_processed(&format!("actor-{}", actor_id));
    }

    #[cfg(feature = "visualize")]
    pub fn record_message_sent(&mut self, from_id: u32, to_id: u32) {
        let from = format!("actor-{}", from_id);
        let to = format!("actor-{}", to_id);
        if let Some(actor) = self.supervision.actors.get_mut(&from) {
            actor.record_message_sent(to);
        }
    }

    #[cfg(feature = "visualize")]
    pub fn get_supervision_data(&self) -> SupervisionData {
        self.supervision.clone()
    }

    #[cfg(feature = "visualize")]
    pub fn get_supervision_summary(&self) -> SupervisionSummary {
        self.supervision.summary()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actors::messages::ResponseMessage;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use tokio::time::{timeout, Duration};

    // Test payload types
    #[derive(Clone)]
    struct StringPayload {
        _content: String,
    }

    #[derive(Clone)]
    struct CounterPayload {
        value: i32,
    }

    // Simple echo actor that responds back
    struct EchoActor;

    impl Actor<StringPayload, ResponseMessage> for EchoActor {
        async fn receive(&mut self, message: Message<StringPayload, ResponseMessage>) {
            if let Some(responder) = message.responder {
                responder.handle(ResponseMessage::Success).await;
            }
        }
    }

    // Actor that accumulates values
    struct AccumulatorActor {
        total: Arc<Mutex<i32>>,
    }

    impl Actor<CounterPayload, ResponseMessage> for AccumulatorActor {
        async fn receive(&mut self, message: Message<CounterPayload, ResponseMessage>) {
            if let Some(payload) = message.payload {
                let mut total = self.total.lock().unwrap();
                *total += payload.value;
            }
        }
    }

    // Blocking echo actor
    struct BlockingEchoActor;

    impl Actor<StringPayload, ResponseMessage> for BlockingEchoActor {
        async fn receive(&mut self, message: Message<StringPayload, ResponseMessage>) {
            if let Some(blocking) = message.blocking {
                let _ = blocking.send(ResponseMessage::Success);
            }
        }
    }

    struct CountingActor {
        counter: Arc<AtomicUsize>,
    }

    impl Actor<StringPayload, ResponseMessage> for CountingActor {
        async fn receive(&mut self, message: Message<StringPayload, ResponseMessage>) {
            if message.payload.is_some() {
                self.counter.fetch_add(1, Ordering::SeqCst);
                if let Some(responder) = message.responder {
                    responder.handle(ResponseMessage::Success).await;
                }
            }
        }
    }

    struct SilentActor;

    impl Actor<StringPayload, ResponseMessage> for SilentActor {
        async fn receive(&mut self, _message: Message<StringPayload, ResponseMessage>) {
            // Simulate a failure to respond without panicking the runtime.
        }
    }

    #[tokio::test]
    async fn test_actor_system_creation() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();
        assert_eq!(actor_system.actors.len(), 0);
        assert_eq!(actor_system.blocking_actors.len(), 0);
    }

    #[tokio::test]
    async fn test_spawn_actor() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = EchoActor;

        actor_system
            .spawn_actor(actor, Some("TestActor".to_string()))
            .await;

        assert_eq!(actor_system.actors.len(), 1);
        assert_eq!(actor_system.get_actor_count(), 1);
    }

    #[tokio::test]
    async fn test_spawn_multiple_actors() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();

        for i in 0..5 {
            let actor = EchoActor;
            actor_system
                .spawn_actor(actor, Some(format!("Actor_{}", i)))
                .await;
        }

        assert_eq!(actor_system.actors.len(), 5);
        assert_eq!(actor_system.get_actor_count(), 5);
    }

    #[tokio::test]
    async fn test_spawn_blocking_actor() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = BlockingEchoActor;

        actor_system.spawn_blocking_actor(actor, Some("BlockingActor".to_string()));

        assert_eq!(actor_system.blocking_actors.len(), 1);
    }

    #[tokio::test]
    async fn test_get_actor_ref() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = EchoActor;

        actor_system
            .spawn_actor(actor, Some("TestActor".to_string()))
            .await;

        let actor_ref = actor_system
            .get_actor_ref(0)
            .expect("Guardian should exist");
        assert!(actor_ref.sender.capacity() > 0);
    }

    #[tokio::test]
    async fn test_send_message_to_actor() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = EchoActor;

        actor_system
            .spawn_actor(actor, Some("EchoActor".to_string()))
            .await;

        let (tx, rx) = actor_system.create_response_channel();
        let handler = super::super::response_handler::from_oneshot(tx);
        let payload = StringPayload {
            _content: "test".to_string(),
        };
        let message = Message {
            payload: Some(payload),
            stop: false,
            responder: Some(handler),
            blocking: None,
        };

        actor_system
            .send_message_to_actor(0, message)
            .await
            .expect("Send should succeed");

        let response = rx.await.expect("Failed to receive response");
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_send_message_to_blocking_actor() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = BlockingEchoActor;

        actor_system.spawn_blocking_actor(actor, Some("BlockingEcho".to_string()));

        let (tx, rx) = actor_system.create_blocking_response_channel();
        let payload = StringPayload {
            _content: "test".to_string(),
        };
        let message = Message {
            payload: Some(payload),
            stop: false,
            responder: None,
            blocking: Some(tx),
        };

        actor_system
            .send_message_to_actor(0, message)
            .await
            .expect("Send should succeed");

        // Give time for blocking actor to process
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        let response = rx.recv().expect("Failed to receive response");
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_actor_accumulator() {
        let mut actor_system = ActorSystem::<CounterPayload, ResponseMessage>::new();
        let total = Arc::new(Mutex::new(0));
        let total_clone = total.clone();

        let actor = AccumulatorActor { total: total_clone };
        actor_system
            .spawn_actor(actor, Some("Accumulator".to_string()))
            .await;

        // Send multiple messages
        for i in 1..=10 {
            let payload = CounterPayload { value: i };
            let message = Message {
                payload: Some(payload),
                stop: false,
                responder: None,
                blocking: None,
            };
            actor_system
                .send_message_to_actor(0, message)
                .await
                .expect("Send should succeed");
        }

        // Give actors time to process
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        let result = *total.lock().unwrap();
        assert_eq!(result, 55); // Sum of 1 to 10
    }

    #[tokio::test]
    async fn test_ping_system() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();

        // Should not panic
        actor_system
            .ping_system()
            .await
            .expect("Ping should succeed");
    }

    #[tokio::test]
    async fn test_get_actor_count() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();

        assert_eq!(actor_system.get_actor_count(), 0);

        actor_system
            .spawn_actor(EchoActor, Some("Actor1".to_string()))
            .await;
        assert_eq!(actor_system.get_actor_count(), 1);

        actor_system
            .spawn_actor(EchoActor, Some("Actor2".to_string()))
            .await;
        assert_eq!(actor_system.get_actor_count(), 2);
    }

    #[tokio::test]
    async fn test_create_actor_channel() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();
        let (tx, _rx) = actor_system.create_actor_channel();

        assert!(tx.capacity() > 0);
    }

    #[tokio::test]
    async fn test_create_blocking_actor_channel() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();
        let (tx, _rx) = actor_system.create_blocking_actor_channel();

        // Should successfully create channels
        let test_msg = Message {
            payload: Some("test".to_string()),
            stop: false,
            responder: None,
            blocking: None,
        };
        assert!(tx.send(test_msg).is_ok());
    }

    #[tokio::test]
    async fn test_create_response_channel() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();
        let (tx, rx) = actor_system.create_response_channel();

        tx.send(ResponseMessage::Success).unwrap();
        let response = rx.await.unwrap();
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_create_blocking_response_channel() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();
        let (tx, rx) = actor_system.create_blocking_response_channel();

        tx.send(ResponseMessage::Success).unwrap();
        let response = rx.recv().unwrap();
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_guardian_receives_message() {
        let actor_system = ActorSystem::<String, ResponseMessage>::new();

        let (tx, rx) = tokio::sync::oneshot::channel();
        let handler = super::super::response_handler::from_oneshot(tx);
        let message = Message {
            payload: Some("test".to_string()),
            stop: false,
            responder: Some(handler),
            blocking: None,
        };

        actor_system.snd.send(message).await.unwrap();

        let response = rx.await.expect("Guardian should respond");
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_multiple_actors_concurrent_messages() {
        let mut actor_system = ActorSystem::<CounterPayload, ResponseMessage>::new();

        // Create 3 accumulator actors
        let totals: Vec<Arc<Mutex<i32>>> = (0..3).map(|_| Arc::new(Mutex::new(0))).collect();

        for total in &totals {
            let actor = AccumulatorActor {
                total: total.clone(),
            };
            actor_system.spawn_actor(actor, None).await;
        }

        // Send messages to each actor
        for actor_id in 0..3 {
            for value in 1..=5 {
                let payload = CounterPayload { value };
                let message = Message {
                    payload: Some(payload),
                    stop: false,
                    responder: None,
                    blocking: None,
                };
                actor_system
                    .send_message_to_actor(actor_id, message)
                    .await
                    .expect("Send should succeed");
            }
        }

        // Give time for processing
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        // Each actor should have sum of 1 to 5 = 15
        for total in totals {
            assert_eq!(*total.lock().unwrap(), 15);
        }
    }

    #[tokio::test]
    async fn test_actor_system_with_different_types() {
        // Test that we can create actor systems with different message types
        let _system1 = ActorSystem::<String, ResponseMessage>::new();
        let _system2 = ActorSystem::<i32, ResponseMessage>::new();
        let _system3 = ActorSystem::<Vec<u8>, ResponseMessage>::new();

        // Just verify they compile and construct
    }

    #[tokio::test]
    async fn test_spawn_actor_without_name() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = EchoActor;

        actor_system.spawn_actor(actor, None).await;

        assert_eq!(actor_system.get_actor_count(), 1);
    }

    #[tokio::test]
    async fn test_spawn_blocking_actor_without_name() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let actor = BlockingEchoActor;

        actor_system.spawn_blocking_actor(actor, None);

        assert_eq!(actor_system.blocking_actors.len(), 1);
    }

    #[tokio::test]
    async fn test_shutdown_signal_broadcast() {
        // Test that the shutdown broadcast channel can be subscribed to
        let actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();

        // Subscribe to the shutdown signal (does not receive yet)
        let mut shutdown_rx1 = actor_system.subscribe_shutdown();
        let mut shutdown_rx2 = actor_system.subscribe_shutdown();

        // Manually broadcast shutdown signal
        let _ = actor_system.shutdown_tx.send(());

        // Both receivers should get the signal
        let result1 =
            tokio::time::timeout(tokio::time::Duration::from_millis(100), shutdown_rx1.recv())
                .await;
        let result2 =
            tokio::time::timeout(tokio::time::Duration::from_millis(100), shutdown_rx2.recv())
                .await;

        assert!(result1.is_ok(), "First receiver should get shutdown signal");
        assert!(
            result2.is_ok(),
            "Second receiver should get shutdown signal"
        );
    }

    #[tokio::test]
    async fn test_actor_stop_prevents_future_messages() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();
        let counter = Arc::new(AtomicUsize::new(0));
        let actor = CountingActor {
            counter: counter.clone(),
        };

        actor_system
            .spawn_actor(actor, Some("CountingActor".to_string()))
            .await;

        let (tx, rx) = actor_system.create_response_channel();
        let handler = super::super::response_handler::from_oneshot(tx);
        let message = Message {
            payload: Some(StringPayload {
                _content: "first".to_string(),
            }),
            stop: false,
            responder: Some(handler),
            blocking: None,
        };
        actor_system
            .send_message_to_actor(0, message)
            .await
            .expect("Send should succeed");
        let response = rx.await.expect("Failed to receive response");
        assert_eq!(response, ResponseMessage::Success);
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        actor_system
            .send_message_to_actor(0, stop_message)
            .await
            .expect("Send should succeed");
        tokio::time::sleep(Duration::from_millis(25)).await;

        let (tx2, rx2) = actor_system.create_response_channel();
        let handler2 = super::super::response_handler::from_oneshot(tx2);
        let message_after_stop = Message {
            payload: Some(StringPayload {
                _content: "after".to_string(),
            }),
            stop: false,
            responder: Some(handler2),
            blocking: None,
        };
        actor_system
            .send_message_to_actor(0, message_after_stop)
            .await
            .expect("Send should succeed");

        let result = timeout(Duration::from_millis(50), rx2).await;
        match result {
            Err(_) => {}
            Ok(Err(_)) => {}
            Ok(Ok(_)) => panic!("Actor should not respond after stop"),
        }
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_actor_panic_does_not_break_other_actors() {
        let mut actor_system = ActorSystem::<StringPayload, ResponseMessage>::new();

        actor_system
            .spawn_actor(SilentActor, Some("SilentActor".to_string()))
            .await;
        actor_system
            .spawn_actor(EchoActor, Some("EchoActor".to_string()))
            .await;

        let (tx, rx) = actor_system.create_response_channel();
        let handler = super::super::response_handler::from_oneshot(tx);
        let panic_message = Message {
            payload: Some(StringPayload {
                _content: "boom".to_string(),
            }),
            stop: false,
            responder: Some(handler),
            blocking: None,
        };
        actor_system
            .send_message_to_actor(0, panic_message)
            .await
            .expect("Send should succeed");

        let silent_result = timeout(Duration::from_millis(50), rx).await;
        match silent_result {
            Err(_) => {}
            Ok(Err(_)) => {}
            Ok(Ok(_)) => panic!("Silent actor should not respond"),
        }

        let (tx2, rx2) = actor_system.create_response_channel();
        let handler2 = super::super::response_handler::from_oneshot(tx2);
        let echo_message = Message {
            payload: Some(StringPayload {
                _content: "ok".to_string(),
            }),
            stop: false,
            responder: Some(handler2),
            blocking: None,
        };
        actor_system
            .send_message_to_actor(1, echo_message)
            .await
            .expect("Send should succeed");

        let echo_response = timeout(Duration::from_millis(50), rx2)
            .await
            .expect("Echo actor should respond")
            .expect("Response channel should be open");
        assert_eq!(echo_response, ResponseMessage::Success);
    }
}