pptr 0.3.0

Type-Driven Asynchronous Actor Runtime
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
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
use atomic_take::AtomicTake;
use indexmap::IndexSet;
use rustc_hash::{FxHashMap, FxHasher};
use std::{
    any::Any,
    future::Future,
    hash::BuildHasherDefault,
    num::NonZeroUsize,
    sync::{Arc, Mutex},
};
use tokio::{
    sync::{mpsc, oneshot, watch},
    task::JoinHandle,
};

use crate::{
    address::Address,
    errors::{
        PermissionDeniedError, PuppetAlreadyExist, PuppetCannotHandleMessage,
        PuppetDoesNotExistError, PuppetError, PuppetOperationError, PuppetSendCommandError,
        PuppetSendMessageError, ResourceAlreadyExist,
    },
    executor::{self, DedicatedExecutor},
    message::{
        Envelope, Mailbox, Message, Postman, ServiceCommand, ServiceMailbox, ServicePacket,
        ServicePostman,
    },
    pid::{Id, Pid},
    prelude::CriticalError,
    puppet::{Context, Handler, Puppet, PuppetHandle, PuppetStatus, ResponseFor},
};

pub type BoxedAny = Box<dyn Any + Send + Sync>;

/// Type alias for a tuple containing a `watch::Sender<PuppetStatus>` and `watch::Receiver<PuppetStatus>`.
///
/// `StatusChannels` is used for monitoring the lifecycle statuses of all actors in a system.
/// The `watch::Sender<PuppetStatus>` is used for broadcasting status updates, while the receiver end can be subscribed
/// to in order to observe these status changes.
pub type StatusChannels = (watch::Sender<PuppetStatus>, watch::Receiver<PuppetStatus>);

/// `FxIndexSet` is an alias for `IndexSet` from the `indexmap` crate, bundled with `FxHasher`.
type FxIndexSet<T> = IndexSet<T, BuildHasherDefault<FxHasher>>;

/// The `Puppeter` struct is the central entity responsible for managing actors within the system.
///
/// It handles the lifecycle, communication, and resource management of actors, as well as dealing
/// with critical errors that may occur during system operation.
///
/// The struct maintains mappings between actor process IDs (`Pid`) and various components such as
/// `Postman` instances for message passing, `ServicePostman` instances for handling service requests,
/// and `StatusChannels` for monitoring actor status. It also keeps track of the relationships between
/// master actors and their child actors (puppets) using the `master_to_puppets` and `puppet_to_master`
/// fields.
///
/// Additionally, the `Puppeter` manages shared resources accessible by the actors, utilizing a
/// dedicated `tokio` executor for running actor tasks. Critical errors that cannot be handled
/// internally are reported through the `failure_tx` and `failure_rx` fields, which are used for
/// sending and receiving `CriticalError` instances, respectively.
///
/// # Fields
///
/// * `message_postmans`: A mapping between a process ID (`Pid`) and its corresponding `Postman`
///   instance, used for message passing between actors.
/// * `service_postmans`: A mapping between a `Pid` and its associated `ServicePostman` instance,
///   responsible for handling service requests.
/// * `statuses`: A mapping between a `Pid` and its `StatusChannels`, used for monitoring the status
///   of actors.
/// * `master_to_puppets`: A mapping between a master actor's `Pid` and the `Pid`s of its child actors
///   (puppets).
/// * `puppet_to_master`: A mapping from a child actor's (puppet's) `Pid` to its master actor's `Pid`.
/// * `resources`: A collection of shared resources accessible by the actors, stored as a mapping
///   between a resource ID (`Id`) and an `Arc<Mutex<BoxedAny>>`.
/// * `executor`: A dedicated `tokio` executor used for running actor tasks.
/// * `failure_tx`: An unbounded sender for reporting critical errors that cannot be handled
///   internally.
/// * `failure_rx`: A receiver for critical errors reported by the system, wrapped in an `Arc` and
///   `AtomicTake` for concurrent access.
#[derive(Clone, Debug)]
pub struct Puppeteer {
    pub(crate) message_postmans: Arc<Mutex<FxHashMap<Pid, BoxedAny>>>,
    pub(crate) service_postmans: Arc<Mutex<FxHashMap<Pid, ServicePostman>>>,
    pub(crate) statuses: Arc<Mutex<FxHashMap<Pid, StatusChannels>>>,
    pub(crate) master_to_puppets: Arc<Mutex<FxHashMap<Pid, FxIndexSet<Pid>>>>,
    pub(crate) puppet_to_master: Arc<Mutex<FxHashMap<Pid, Pid>>>,
    pub(crate) resources: Arc<Mutex<FxHashMap<Id, Arc<Mutex<BoxedAny>>>>>,
    pub(crate) failure_tx: Arc<AtomicTake<oneshot::Sender<CriticalError>>>,
    pub(crate) failure_rx: Arc<AtomicTake<oneshot::Receiver<CriticalError>>>,
    pub(crate) executor: DedicatedExecutor,
}

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

#[allow(clippy::expect_used)]
impl Puppeteer {
    /// Constructs a new instance of Puppeter, which acts as a manager for various actors within
    /// the framework.
    ///
    /// This function initializes the internal communication channels, dedicated executor, and
    /// other necessary components based on the system's available resources (e.g., CPU cores).
    ///
    /// # Examples
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// let pptr = Puppeteer::new();
    /// // Now you can use `puppeter` to manage actors.
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if it fails to determine the number of available CPU cores on the system.
    #[must_use]
    pub fn new() -> Self {
        let (tx, rx) = oneshot::channel();
        let cpus = NonZeroUsize::new(num_cpus::get()).expect("Failed to get number of CPUs");
        let executor = DedicatedExecutor::new(cpus);
        Self {
            message_postmans: Arc::default(),
            service_postmans: Arc::default(),
            statuses: Arc::default(),
            master_to_puppets: Arc::default(),
            puppet_to_master: Arc::default(),
            resources: Arc::default(),
            executor,
            failure_tx: Arc::new(AtomicTake::new(tx)),
            failure_rx: Arc::new(AtomicTake::new(rx)),
        }
    }

    /// Sets a callback function to be called in the event of an unrecoverable error.
    ///
    /// This method allows setting a user-defined function that will be executed if a critical
    /// error occurs that cannot be internally handled by Puppet or any Master in the actor
    /// hierarchy. This function serves as a last resort and is typically used to perform cleanup
    /// or logging before shutting down the actor or system in a controlled manner.
    ///
    /// # Example Usage
    ///
    /// ```rust
    /// # use std::pin::Pin;
    /// # use pptr::puppeteer::Puppeteer;
    ///
    /// # let pptr = Puppeteer::new();
    /// pptr.on_unrecoverable_failure(|pptr, error| {
    ///     async move {
    ///         println!("Unrecoverable error encountered: {:?}", error);
    ///         // Application cleanup and termination logic here
    ///     }
    /// });
    /// ```
    ///
    /// # Panics
    ///
    /// This method does not panic by itself, but the user-supplied callback function can panic if
    /// not properly handled.
    pub async fn on_unrecoverable_failure<F, Fut>(&self, f: F)
    where
        F: FnOnce(Puppeteer, CriticalError) -> Fut + Send,
        Fut: Future<Output = ()> + Send,
    {
        if let Some(rx) = self.failure_rx.take() {
            if let Ok(err) = rx.await {
                f(self.clone(), err).await;
            }
        }
    }

    /// Awaits an unrecoverable error that cannot be handled internally or by any actor in the
    /// hierarchy.
    ///
    /// This function listens for a critical error that is deemed unrecoverable, meaning it cannot
    /// be gracefully handled by the current puppet or any supervising puppet in its hierarchy.
    /// This is typically used to perform cleanup or logging before shutting down the actor or
    /// system in a controlled manner.
    ///
    /// # Example Usage
    ///
    /// ```rust
    /// # use std::pin::Pin;
    /// # use pptr::puppeteer::Puppeteer;
    /// # use tokio::time::{timeout, Duration};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let pptr = Puppeteer::new();
    /// let result = timeout(Duration::from_millis(100), pptr.wait_for_unrecoverable_failure()).await;
    ///
    /// match result {
    ///     Ok(err) => println!("Unrecoverable error encountered: {:?}", err),
    ///     Err(_) => println!("No error encountered within 100 milliseconds"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the internal mechanism for receiving critical errors is not initialized or if
    /// receiving fails.
    pub async fn wait_for_unrecoverable_failure(self) -> CriticalError {
        self.failure_rx.take().unwrap().await.unwrap()
    }

    /// Registers a puppet within the system with all necessary data.
    ///
    /// This function is intended for internal use within the framework to associate a puppet with
    /// its communication and lifecycle channels. It ensures that the puppet is ready to receive
    /// and process messages, respond to service packets, and report its lifecycle status.
    ///
    /// # Panics
    ///
    /// This function can panic if it fails to acquire a lock on the internal mutex.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetError` if the puppet cannot be registered due to a conflict with an
    /// existing registration.
    pub(crate) fn register_puppet_by_pid<P>(
        &self,
        master: Pid,
        postman: Postman<P>,
        service_postman: ServicePostman,
        status_tx: watch::Sender<PuppetStatus>,
        status_rx: watch::Receiver<PuppetStatus>,
    ) -> Result<(), PuppetError>
    where
        P: Puppet,
    {
        let puppet = Pid::new::<P>();
        // Check if the puppet already exists by its Pid
        if self.is_puppet_exists_by_pid(puppet) {
            // If the puppet exists, return an error indicating it's already registered
            return Err(PuppetAlreadyExist::new(puppet).into());
        }

        // Check if the master exists
        if !self.is_puppet_exists_by_pid(master) && master != puppet {
            // If the master doesn't exist, return an error indicating it doesn't exist
            return Err(PuppetDoesNotExistError::new(master).into());
        }

        // Add the puppet's postman to the message_postmans map
        self.message_postmans
            .lock()
            .expect("Failed to acquire mutex lock")
            .insert(puppet, Box::new(postman));

        // Add the puppet's service postman to the service_postmans map
        self.service_postmans
            .lock()
            .expect("Failed to acquire mutex lock")
            .insert(puppet, service_postman);

        // Add the puppet to the master's set of puppets
        self.master_to_puppets
            .lock()
            .expect("Failed to acquire mutex lock")
            .entry(master)
            .or_default()
            .insert(puppet);

        // Associate the puppet with the master in the puppet_to_master map
        self.puppet_to_master
            .lock()
            .expect("Failed to acquire mutex lock")
            .insert(puppet, master);

        // Add the puppet's status receiver to the statuses map
        self.statuses
            .lock()
            .expect("Failed to acquire mutex lock")
            .insert(puppet, (status_tx, status_rx));

        // Return a successful result indicating the registration was successful
        Ok(())
    }

    /// Checks if a puppet of the specific type is registered and exists.
    ///
    /// This function inspects the internal registry to determine if a puppet,
    /// identified by its PID (`puppet`), is present. It is a convenience method
    /// for quickly verifying the existence of a puppet without needing to retrieve
    /// its entire data structure.
    ///
    /// # Panics
    ///
    /// This function can panic if it fails to acquire a lock on the internal mutex.
    #[must_use]
    pub fn is_puppet_exists<P>(&self) -> bool
    where
        P: Puppet,
    {
        let puppet = Pid::new::<P>();
        self.is_puppet_exists_by_pid(puppet)
    }

    /// Intenal function to check if a puppet exists by its PID.
    pub(crate) fn is_puppet_exists_by_pid(&self, puppet: Pid) -> bool {
        self.get_puppet_master_by_pid(puppet).is_some()
    }

    /// Retrieves a `Postman` instance for the specified Puppet type `P`.
    ///
    /// # Panics
    ///
    /// This method panics if it fails to acquire the mutex lock on the internal
    /// storage of `Postman` instances. This is a critical error indicating that
    /// the locking mechanism preventing data races is compromised.
    #[must_use]
    pub(crate) fn get_postman<P>(&self) -> Option<Postman<P>>
    where
        P: Puppet,
    {
        let puppet = Pid::new::<P>();
        self.message_postmans
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .and_then(|boxed| boxed.downcast_ref::<Postman<P>>())
            .cloned()
    }

    /// Retrieves the `ServicePostman` instance associated with the given puppet `Pid`.
    ///
    /// This function looks up the `ServicePostman` instance in the internal storage using the
    /// provided `puppet` identifier. If a matching instance is found, it is cloned and returned
    /// wrapped in an `Option`. If no instance is found for the given `Pid`, `None` is returned.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal storage of
    /// `ServicePostman` instances, indicating a critical error in the locking mechanism.
    pub(crate) fn get_service_postman_by_pid(&self, puppet: Pid) -> Option<ServicePostman> {
        self.service_postmans
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .cloned()
    }

    /// Updates the status of the puppet identified by `puppet` to the given `status`.
    ///
    /// This function retrieves the status entry associated with the `puppet` identifier
    /// from the internal status storage. If an entry is found, it sends the new `status`
    /// value to the associated channel, triggering a status update notification.
    ///
    /// The status is only updated if the new `status` differs from the current value.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal
    /// status storage, indicating a critical error in the locking mechanism.
    pub(crate) fn set_status_by_pid(&self, puppet: Pid, status: PuppetStatus) {
        self.statuses
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .map(|(tx, _)| {
                tx.send_if_modified(|current| {
                    if *current == status {
                        false
                    } else {
                        *current = status;
                        true
                    }
                })
            });
    }

    /// Subscribes to the status updates of the puppet associated with the type `P`.
    ///
    /// Returns a `watch::Receiver` that can be used to receive status updates for the puppet.
    /// If no status entry is found for the given puppet type, `None` is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pptr::prelude::*;
    /// # #[derive(Debug, Clone, Default)]
    /// # struct SomePuppet;
    /// # impl Puppet for SomePuppet {
    /// #     type Supervision = OneForAll;
    /// # }
    /// let pptr = Puppeteer::new();
    /// if let Some(receiver) = pptr.subscribe_puppet_status::<SomePuppet>() {
    ///     // Use the receiver to get status updates for Puppet
    ///     let status = receiver.borrow();
    ///     println!("Current status: {:?}", status);
    /// }
    /// ```
    #[must_use]
    pub fn subscribe_puppet_status<P>(&self) -> Option<watch::Receiver<PuppetStatus>>
    where
        P: Puppet,
    {
        let puppet = Pid::new::<P>();
        self.subscribe_puppet_status_by_pid(puppet)
    }

    /// Subscribes to the status updates of the puppet identified by `puppet`.
    ///
    /// Returns a cloned `watch::Receiver` that can be used to receive status updates for the puppet.
    /// If no status entry is found for the given `puppet` identifier, `None` is returned.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal status storage,
    /// indicating a critical error in the locking mechanism.
    pub(crate) fn subscribe_puppet_status_by_pid(
        &self,
        puppet: Pid,
    ) -> Option<watch::Receiver<PuppetStatus>> {
        self.statuses
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .map(|(_, rx)| rx.clone())
    }

    /// Retrieves the current status of the puppet associated with the type `P`.
    ///
    /// Returns the current `PuppetStatus` of the puppet wrapped in an `Option`.
    /// If no status entry is found for the given puppet type, `None` is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pptr::prelude::*;
    /// # #[derive(Debug, Clone, Default)]
    /// # struct SomePuppet;
    /// # impl Puppet for SomePuppet {
    /// #     type Supervision = OneForAll;
    /// # }
    /// # let pptr = Puppeteer::new();
    /// if let Some(status) = pptr.get_puppet_status::<SomePuppet>() {
    ///     println!("Current status: {:?}", status);
    /// }
    /// ```
    #[must_use]
    pub fn get_puppet_status<P>(&self) -> Option<PuppetStatus>
    where
        P: Puppet,
    {
        let puppet = Pid::new::<P>();
        self.get_puppet_status_by_pid(puppet)
    }

    /// Retrieves the current status of the puppet identified by `puppet`.
    ///
    /// Returns the current `PuppetStatus` of the puppet wrapped in an `Option`.
    /// If no status entry is found for the given `puppet` identifier, `None` is returned.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal status storage,
    /// indicating a critical error in the locking mechanism.
    pub(crate) fn get_puppet_status_by_pid(&self, puppet: Pid) -> Option<PuppetStatus> {
        self.statuses
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .map(|(_, rx)| *rx.borrow())
    }

    /// Checks if the puppet identified by `puppet` is associated with the master identified by `master`.
    ///
    /// Returns `Some(true)` if the `puppet` is associated with the `master`, `Some(false)` if not,
    /// and `None` if no entry is found for the given `master` identifier.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal `master_to_puppets`
    /// storage, indicating a critical error in the locking mechanism.
    pub(crate) fn puppet_has_puppet_by_pid(&self, master: Pid, puppet: Pid) -> Option<bool> {
        self.master_to_puppets
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&master)
            .map(|puppets| puppets.contains(&puppet))
    }

    /// Checks if the puppet identified by `puppet` has permission from the master identified by `master`.
    ///
    /// Returns `Some(true)` if the `puppet` has permission from the `master`, `Some(false)` if not,
    /// and `None` if no entry is found for the given `master` identifier.
    ///
    /// # Panics
    ///
    /// This function is a wrapper around `puppet_has_puppet_by_pid`, so the same panic conditions apply.
    pub(crate) fn puppet_has_permission_by_pid(&self, master: Pid, puppet: Pid) -> Option<bool> {
        self.puppet_has_puppet_by_pid(master, puppet)
    }

    /// Retrieves the master identifier associated with the given `puppet` identifier.
    ///
    /// Returns `Some(Pid)` if a master is found for the `puppet`, or `None` if no association exists.
    ///
    /// # Panics
    ///
    /// This function may panic if it fails to acquire the mutex lock on the internal `puppet_to_master`
    /// storage, indicating a critical error in the locking mechanism.
    pub(crate) fn get_puppet_master_by_pid(&self, puppet: Pid) -> Option<Pid> {
        self.puppet_to_master
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&puppet)
            .copied()
    }

    /// Sets the master for a given puppet.
    ///
    /// This method allows changing the master of a puppet, transferring control
    /// from the old master to a new master. The old master must have permission
    /// over the puppet, otherwise an error is returned.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub fn set_puppet_master<P, O, M>(&self) -> Result<(), PuppetOperationError>
    where
        P: Puppet,
        O: Puppet,
        M: Puppet,
    {
        let old_master = Pid::new::<O>();
        let new_master = Pid::new::<M>();
        let puppet = Pid::new::<P>();
        self.set_puppet_master_by_pid(old_master, new_master, puppet)
    }

    /// Sets the master for a puppet using their Pids.
    ///
    /// This is the internal implementation of `set_puppet_master` that operates
    /// directly on Pids. It transfers a puppet from its old master to a new master,
    /// checking permissions and updating the internal mappings.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) fn set_puppet_master_by_pid(
        &self,
        old_master: Pid,
        new_master: Pid,
        puppet: Pid,
    ) -> Result<(), PuppetOperationError> {
        match self.puppet_has_permission_by_pid(old_master, puppet) {
            None => Err(PuppetDoesNotExistError::new(puppet).into()),
            Some(false) => {
                Err(PermissionDeniedError::new(old_master, puppet)
                    .with_message("Cannot change master of another master puppet")
                    .into())
            }
            Some(true) => {
                // Remove puppet from old master
                self.master_to_puppets
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .get_mut(&old_master)
                    .expect("Old master has no puppets")
                    .shift_remove(&puppet);

                // Add puppet to new master
                self.master_to_puppets
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .entry(new_master)
                    .or_default()
                    .insert(puppet);

                // Set new master for puppet
                self.puppet_to_master
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .insert(puppet, new_master);
                Ok(())
            }
        }
    }

    /// Retrieves the set of puppets controlled by a given master.
    ///
    /// This method returns an optional `FxIndexSet` containing the `Pid`s of all puppets
    /// currently under the control of the specified master. If the master has no puppets,
    /// or if the master does not exist, `None` is returned.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) fn get_puppets_by_pid(&self, master: Pid) -> Option<FxIndexSet<Pid>> {
        self.master_to_puppets
            .lock()
            .expect("Failed to acquire mutex lock")
            .get(&master)
            .cloned()
    }

    /// Detaches a puppet from its current master, making it its own master.
    ///
    /// This method allows a master to relinquish control over a puppet, effectively
    /// making the puppet independent. The master must have permission over the puppet,
    /// otherwise an error is returned.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetOperationError` if:
    /// - The specified puppet does not exist.
    /// - The master does not have permission to detach the puppet.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) fn detach_puppet_by_pid(
        &self,
        master: Pid,
        puppet: Pid,
    ) -> Result<(), PuppetOperationError> {
        match self.puppet_has_permission_by_pid(master, puppet) {
            None => Err(PuppetDoesNotExistError::new(puppet).into()),
            Some(false) => {
                Err(PermissionDeniedError::new(master, puppet)
                    .with_message("Cannot detach puppet from another master")
                    .into())
            }
            Some(true) => {
                self.set_puppet_master_by_pid(master, puppet, puppet)?;
                Ok(())
            }
        }
    }

    /// Deletes a puppet, removing it from the control of its master.
    ///
    /// This method allows a master to completely remove a puppet from the system,
    /// deleting all associated data. The master must have permission over the puppet,
    /// otherwise an error is returned.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetOperationError` if:
    /// - The specified puppet does not exist.
    /// - The master does not have permission to delete the puppet.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub fn delete_puppet<O, P>(&self) -> Result<(), PuppetOperationError>
    where
        O: Puppet,
        P: Puppet,
    {
        let master = Pid::new::<O>();
        let puppet = Pid::new::<P>();
        self.delete_puppet_by_pid(master, puppet)
    }

    /// Deletes a puppet by its `Pid`, removing it from the control of its master.
    ///
    /// This is the internal implementation of `delete_puppet` that operates directly
    /// on `Pid`s. It removes a puppet from the system, deleting all associated data.
    /// The master must have permission over the puppet, otherwise an error is returned.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetOperationError` if:
    /// - The specified puppet does not exist.
    /// - The master does not have permission to delete the puppet.
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) fn delete_puppet_by_pid(
        &self,
        master: Pid,
        puppet: Pid,
    ) -> Result<(), PuppetOperationError> {
        match self.puppet_has_permission_by_pid(master, puppet) {
            None => Err(PuppetDoesNotExistError::new(puppet).into()),
            Some(false) => {
                Err(PermissionDeniedError::new(master, puppet)
                    .with_message("Cannot delete puppet of another master")
                    .into())
            }
            Some(true) => {
                // Delete address from addresses
                self.message_postmans
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .remove(&puppet);

                // Delete status from statuses
                self.statuses
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .remove(&puppet);

                // Delete puppet from master_to_puppets
                self.master_to_puppets
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .get_mut(&master)
                    .expect("Master has no puppets")
                    .shift_remove(&puppet);

                // Delete puppet from puppet_to_master
                self.puppet_to_master
                    .lock()
                    .expect("Failed to acquire mutex lock")
                    .remove(&puppet);

                // TODO: Break loop
                Ok(())
            }
        }
    }

    /// Sends a message of type `E` to the puppet handler of type `P`.
    ///
    /// This method sends a message to the puppet's message handler of the specified type.
    /// It returns a `Result` indicating the success or failure of the send operation.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetSendMessageError` if:
    /// - The puppet does not exist.
    /// - The message fails to send.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let result = pptr.send::<Puppet, _>(Message::new()).await;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub fn send<P, E>(&self, message: E) -> Result<(), PuppetSendMessageError>
    where
        P: Handler<E>,
        E: Message,
    {
        if let Some(postman) = self.get_postman::<P>() {
            Ok(postman.send(message)?)
        } else {
            Err(PuppetDoesNotExistError::new(Pid::new::<P>()).into())
        }
    }

    /// Sends a message of type `E` to the puppet handler of type `P` and awaits a response.
    ///
    /// This method sends a message to the puppet's message handler of the specified type
    /// and awaits a response. It returns a `Result` containing the response or an error.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetSendMessageError` if:
    /// - The puppet does not exist.
    /// - The message fails to send or receive a response.
    /// - Handler return error.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let response = pptr.ask::<Puppet, _>(MyMessage::new()).await?;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub async fn ask<P, E>(&self, message: E) -> Result<ResponseFor<P, E>, PuppetSendMessageError>
    where
        P: Handler<E>,
        E: Message,
    {
        if let Some(postman) = self.get_postman::<P>() {
            Ok(postman.send_and_await_response::<E>(message, None).await?)
        } else {
            Err(PuppetDoesNotExistError::new(Pid::new::<P>()).into())
        }
    }

    /// Sends a message of type `E` to the puppet handler of type `P` with a timeout and awaits a response.
    ///
    /// This method sends a message to the puppet's message handler of the specified type
    /// and awaits a response, with a specified timeout duration. It returns a `Result`
    /// containing the response or an error.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetSendMessageError` if:
    /// - The puppet does not exist.
    /// - The message fails to send or receive a response within the timeout duration.
    /// - Handler return error.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let response = pptr.ask_with_timeout::<Puppet, _>(MyMessage::new(), Duration::from_secs(5)).await?;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) async fn ask_with_timeout<P, E>(
        &self,
        message: E,
        duration: std::time::Duration,
    ) -> Result<ResponseFor<P, E>, PuppetSendMessageError>
    where
        P: Handler<E>,
        E: Message,
    {
        if let Some(postman) = self.get_postman::<P>() {
            Ok(postman
                .send_and_await_response::<E>(message, Some(duration))
                .await?)
        } else {
            Err(PuppetDoesNotExistError::new(Pid::new::<P>()).into())
        }
    }

    /// Sends a command to a puppet by its `Pid`, with the master's permission.
    ///
    /// This method sends a `ServiceCommand` to a puppet identified by its `Pid`, ensuring
    /// that the master has permission over the puppet. It returns a `Result` indicating
    /// the success or failure of the send operation.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetSendCommandError` if:
    /// - The specified puppet does not exist.
    /// - The master does not have permission to send commands to the puppet.
    /// - The command fails to send or receive a response.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let result = pptr.send_command_by_pid(master_pid, puppet_pid, ServiceCommand::Start).await;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) async fn send_command_by_pid(
        &self,
        master: Pid,
        puppet: Pid,
        command: ServiceCommand,
    ) -> Result<(), PuppetSendCommandError> {
        match self.puppet_has_permission_by_pid(master, puppet) {
            None => Err(PuppetDoesNotExistError::new(puppet).into()),
            Some(false) => {
                Err(PermissionDeniedError::new(master, puppet)
                    .with_message("Cannot send command to puppet of another master")
                    .into())
            }
            Some(true) => {
                let Some(serivce_address) = self.get_service_postman_by_pid(puppet) else {
                    return Err(PuppetDoesNotExistError::new(puppet).into());
                };
                Ok(serivce_address
                    .send_and_await_response(puppet, command, None)
                    .await?)
            }
        }
    }

    /// Spawns a new puppet and links it to the specified master.
    ///
    /// This method creates a new puppet using the provided `PuppetBuilder` and links it to
    /// the specified master `Pid`. It returns an `Address<P>` for the newly spawned puppet.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetError` if:
    /// - The specified master does not exist and is not the same as the puppet's `Pid`.
    /// - The puppet fails to spawn or initialize.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let address = pptr.spawn::<Master, Puppet>(builder).await?;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub async fn spawn<P, M>(&self, puppet: P) -> Result<Address<P>, PuppetError>
    where
        P: Puppet,
        M: Puppet,
    {
        let master_pid = Pid::new::<M>();
        self.spawn_puppet_by_pid(puppet, master_pid).await
    }

    /// Spawns a new independent puppet and links it to itself.
    ///
    /// This method creates a new puppet using the provided `PuppetBuilder` and links it to
    /// itself, making it an independent puppet. It returns an `Address<P>` for the newly
    /// spawned puppet.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetError` if:
    /// - The puppet fails to spawn or initialize.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let address = pptr.spawn_self::<Puppet>(builder).await?;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    #[allow(clippy::impl_trait_in_params)]
    pub async fn spawn_self<P>(&self, puppet: P) -> Result<Address<P>, PuppetError>
    where
        P: Puppet,
    {
        self.spawn::<P, P>(puppet).await
    }

    /// Spawns a new puppet and links it to the specified master.
    ///
    /// This method creates a new puppet using the provided `PuppetBuilder` and links it to
    /// the specified master `Pid`. It returns an `Address<P>` for the newly spawned puppet.
    ///
    /// # Errors
    ///
    /// Returns a `PuppetError` if:
    /// - The specified master does not exist and is not the same as the puppet's `Pid`.
    /// - The puppet fails to spawn or initialize.
    ///
    /// # Example Usage
    ///
    /// ```ignore
    /// let address = pptr.spawn::<Master, Puppet>(builder).await?;
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the mutex lock is poisoned, indicating a failure in lock acquisition.
    pub(crate) async fn spawn_puppet_by_pid<P>(
        &self,
        mut puppet: P,
        master_pid: Pid,
    ) -> Result<Address<P>, PuppetError>
    where
        P: Puppet,
    {
        let puppet_pid = Pid::new::<P>();
        if !self.is_puppet_exists_by_pid(master_pid) && master_pid != puppet_pid {
            return Err(PuppetDoesNotExistError::new(master_pid).into());
        }

        let pid = Pid::new::<P>();
        let (status_tx, status_rx) = watch::channel::<PuppetStatus>(PuppetStatus::Inactive);
        let (message_tx, message_rx) = mpsc::unbounded_channel::<Box<dyn Envelope<P>>>();
        let (command_tx, command_rx) = mpsc::channel::<ServicePacket>(1);
        let postman = Postman::new(message_tx);
        let service_postman = ServicePostman::new(command_tx);
        self.register_puppet_by_pid::<P>(
            master_pid,
            postman.clone(),
            service_postman,
            status_tx,
            status_rx.clone(),
        )?;

        let ctx = Context::<P>::new(self.clone());

        let handle = PuppetHandle {
            status_rx: status_rx.clone(),
            message_rx: Mailbox::new(message_rx),
            command_rx: ServiceMailbox::new(command_rx),
        };

        let address = Address {
            pid,
            status_rx,
            message_tx: postman,
            pptr: self.clone(),
        };

        puppet.on_init(&ctx).await?;
        ctx.start(&mut puppet, false).await?;

        tokio::spawn(run_puppet_loop(puppet, ctx, handle));
        Ok(address)
    }

    /// Adds a new resource to the resource collection.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime. If a
    /// resource with the same type already exists, an error will be returned.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// pptr.add_resource::<i32>(10).unwrap();
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if the internal mutex lock fails.
    ///
    /// # Errors
    ///
    /// Returns a `ResourceAlreadyExist` error if a resource of the same type already exists in the
    /// collection.
    pub fn add_resource<T>(&self, resource: T) -> Result<(), ResourceAlreadyExist>
    where
        T: Send + Sync + Clone + 'static,
    {
        let id = Id::new::<T>();
        if let std::collections::hash_map::Entry::Vacant(e) = self
            .resources
            .lock()
            .expect("Failed to acquire mutex lock")
            .entry(id)
        {
            e.insert(Arc::new(Mutex::new(Box::new(resource))));
            Ok(())
        } else {
            Err(ResourceAlreadyExist { id })
        }
    }

    /// Returns a cloned copy of the resource of type `T`, if it exists.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let value = pptr.get_resource::<i32>().unwrap();
    /// assert_eq!(value, 10);
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if the internal mutex lock fails.
    ///
    /// # Returns
    ///
    /// `Some(T)` if the resource exists, otherwise `None`.
    #[must_use]
    pub fn get_resource<T>(&self) -> Option<T>
    where
        T: Send + Sync + Clone + 'static,
    {
        let resource = {
            let id = Id::new::<T>();
            let resources_guard = self.resources.lock().expect("Failed to acquire mutex lock");
            Arc::clone(resources_guard.get(&id)?)
        };

        let boxed = resource
            .lock()
            .expect("Failed to acquire mutex lock on resource");
        let any_ref = boxed.downcast_ref::<T>()?;
        Some(any_ref.clone())
    }

    /// Borrows the resource of type `T` and passes it to the provided closure `f`.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let result = pptr.with_resource::<i32, _, _>(|value| {
    ///     assert_eq!(*value, 10);
    ///     "success"
    /// }).unwrap();
    /// assert_eq!(result, "success");
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if the internal mutex lock fails.
    ///
    /// # Returns
    ///
    /// `Some(R)` if the resource exists, where `R` is the return type of the closure `f`.
    /// Returns `None` if the resource doesn't exist.
    pub fn with_resource<T, F, R>(&self, f: F) -> Option<R>
    where
        T: Send + Sync + Clone + 'static,
        F: FnOnce(&T) -> R,
    {
        let resource = {
            let id = Id::new::<T>();
            let resources_guard = self.resources.lock().expect("Failed to acquire mutex lock");
            Arc::clone(resources_guard.get(&id)?)
        };

        let boxed = resource
            .lock()
            .expect("Failed to acquire mutex lock on resource");
        let any_ref = boxed.downcast_ref::<T>()?;
        Some(f(any_ref))
    }

    /// Borrows the resource of type `T` and passes it to the provided closure `f`.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let result = pptr.with_expected_resource::<i32, _, _>(|value| {
    ///     assert_eq!(*value, 10);
    ///     "success"
    /// });
    /// assert_eq!(result, "success");
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if:
    /// - The internal mutex lock fails.
    /// - The resource of type `T` doesn't exist.
    /// - Downcasting the resource to type `T` fails.
    ///
    /// # Returns
    ///
    /// The return value `R` of the closure `f`.
    pub fn with_expected_resource<T, F, R>(&self, f: F) -> R
    where
        T: Send + Sync + Clone + 'static,
        F: FnOnce(&T) -> R,
    {
        let resource = {
            let id = Id::new::<T>();
            let resources_guard = self.resources.lock().expect("Failed to acquire mutex lock");
            Arc::clone(resources_guard.get(&id).expect("Resource doesn't exist"))
        };

        let boxed = resource
            .lock()
            .expect("Failed to acquire mutex lock on resource");
        let any_ref = boxed
            .downcast_ref::<T>()
            .expect("Failed to downcast resource");
        f(any_ref)
    }

    /// Mutably borrows the resource of type `T` and passes it to the provided closure `f`.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let result = pptr.with_resource_mut::<i32, _, _>(|value| {
    ///     *value += 1;
    ///     "success"
    /// }).unwrap();
    /// assert_eq!(result, "success");
    /// assert_eq!(pptr.expect_resource::<i32>(), 11);
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if the internal mutex lock fails.
    ///
    /// # Returns
    ///
    /// `Some(R)` if the resource exists, where `R` is the return type of the closure `f`.
    /// Returns `None` if the resource doesn't exist.
    pub fn with_resource_mut<T, F, R>(&self, f: F) -> Option<R>
    where
        T: Send + Sync + Clone + 'static,
        F: FnOnce(&mut T) -> R,
    {
        let resource = {
            let id = Id::new::<T>();
            let resources_guard = self.resources.lock().expect("Failed to acquire mutex lock");
            Arc::clone(resources_guard.get(&id)?)
        };

        let mut boxed = resource
            .lock()
            .expect("Failed to acquire mutex lock on resource");
        let any_mut = boxed.downcast_mut::<T>()?;
        Some(f(any_mut))
    }
    /// Mutably borrows the resource of type `T` and passes it to the provided closure `f`.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let result = pptr.with_expected_resource_mut::<i32, _, _>(|value| {
    ///     *value += 1;
    ///     "success"
    /// }).unwrap();
    /// assert_eq!(result, "success");
    /// assert_eq!(pptr.expect_resource::<i32>(), 11);
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if:
    /// - The internal mutex lock fails.
    /// - The resource of type `T` doesn't exist.
    /// - Downcasting the resource to type `T` fails.
    ///
    /// # Returns
    ///
    /// `Some(R)`, where `R` is the return type of the closure `f`.
    pub fn with_expected_resource_mut<T, F, R>(&self, f: F) -> Option<R>
    where
        T: Send + Sync + Clone + 'static,
        F: FnOnce(&mut T) -> R,
    {
        let resource = {
            let id = Id::new::<T>();
            let resources_guard = self.resources.lock().expect("Failed to acquire mutex lock");
            Arc::clone(resources_guard.get(&id).expect("Resource doesn't exist"))
        };

        let mut boxed = resource
            .lock()
            .expect("Failed to acquire mutex lock on resource");
        let any_mut = boxed
            .downcast_mut::<T>()
            .expect("Failed to downcast resource");
        Some(f(any_mut))
    }

    /// Returns a cloned copy of the resource of type `T`, or panics if it doesn't exist.
    ///
    /// The resource must implement `Send`, `Sync`, `Clone`, and have a `'static` lifetime.
    ///
    /// # Example Usage
    ///
    /// ```
    /// # use pptr::puppeteer::Puppeteer;
    /// # let pptr = Puppeteer::new();
    /// # pptr.add_resource::<i32>(10).unwrap();
    /// let value = pptr.expect_resource::<i32>();
    /// assert_eq!(value, 10);
    /// ```
    ///
    /// # Panics
    ///
    /// This function will panic if the internal mutex lock fails or if the resource doesn't exist.
    #[must_use]
    pub fn expect_resource<T>(&self) -> T
    where
        T: Send + Sync + Clone + 'static,
    {
        self.get_resource::<T>().expect("Resource doesn't exist")
    }

    pub fn spawn_task<F, Fut, O>(&self, task: F) -> JoinHandle<O>
    where
        F: FnOnce(Self) -> Fut + Send + 'static,
        Fut: Future<Output = O> + Send + 'static,
        O: Send + 'static,
    {
        tokio::spawn(task(self.clone()))
    }

    pub fn spawn_heavy_task<F, Fut, O>(&self, task: F) -> executor::Job<O>
    where
        F: FnOnce(Self) -> Fut + Send + 'static,
        Fut: Future<Output = O> + Send + 'static,
        O: Send + 'static,
    {
        let cloned_self = self.clone();
        self.executor.spawn(async move { task(cloned_self).await })
    }
}

/// Runs the main event loop for a puppet, handling lifecycle status changes, commands, and messages.
///
/// The loop continues running until one of the following conditions is met:
/// - The puppet's status changes to `Inactive` or `Failed`.
/// - The `puppet_status` channel is closed.
/// - The `command_rx` channel is closed.
/// - The `message_rx` channel is closed.
///
/// If the puppet's status is `Active`, incoming commands and messages are handled by the puppet.
/// Otherwise, commands are ignored and an error response is sent, while messages are met with an
/// error reply indicating the puppet's status.
///
/// # Panics
///
/// This function does not explicitly panic, but may propagate panics from the `handle_command` or
/// `handle_message` methods of the `Puppet` and `Puppeteer` structs.
pub(crate) async fn run_puppet_loop<P>(
    mut puppet: P,
    mut ctx: Context<P>,
    mut handle: PuppetHandle<P>,
) where
    P: Puppet,
{
    let mut puppet_status = handle.status_rx;

    loop {
        tokio::select! {
            Ok(()) = puppet_status.changed() => {
                if matches!(*puppet_status.borrow(), PuppetStatus::Inactive
                    | PuppetStatus::Failed) {
                    tracing::info!(puppet = %ctx.pid, "Stopping loop due to puppet status change");
                    break;
                }
            }
            Some(mut service_packet) = handle.command_rx.recv() => {
                if matches!(*puppet_status.borrow(), PuppetStatus::Active) {
                    if let Err(err) = service_packet.handle_command(&mut puppet, &mut ctx).await {
                        tracing::error!(puppet = %ctx.pid, "Failed to handle command: {}", err);
                    }
                } else {
                    tracing::debug!(puppet = %ctx.pid, "Ignoring command due to non-Active puppet status");
                    let status = *puppet_status.borrow();
                    let error_response = PuppetCannotHandleMessage::new(ctx.pid, status).into();
                    service_packet.reply_error(error_response);
                }
            }
            Some(mut envelope) = handle.message_rx.recv() => {
                let status = *puppet_status.borrow();
                if matches!(status, PuppetStatus::Active) {
                    envelope.handle_message(&mut puppet, &mut ctx).await;
                } else {
                    tracing::debug!(puppet = %ctx.pid,  "Ignoring message due to non-Active puppet status");
                    envelope.reply_error(&ctx, PuppetCannotHandleMessage::new(ctx.pid, status).into()).await;
                }
            }
            else => {
                tracing::debug!(puppet = %ctx.pid, "Stopping loop due to closed channels");
                break;
            }
        }
    }
}

#[allow(unused_variables, clippy::unwrap_used)]
#[cfg(test)]
mod tests {

    use std::time::Duration;

    use executor::ConcurrentExecutor;

    use crate::{executor::SequentialExecutor, supervision::strategy::OneForAll};

    use super::*;

    #[derive(Debug, Clone, Default)]
    struct MasterActor {
        failures: usize,
    }

    impl Puppet for MasterActor {
        type Supervision = OneForAll;

        async fn reset(&self, ctx: &Context<Self>) -> Result<Self, CriticalError> {
            println!("Resetting MasterActor");
            Err(CriticalError::new(ctx.pid, "Failed to reset MasterActor"))
        }
    }

    #[derive(Debug, Clone, Default)]
    struct PuppetActor {
        failures: usize,
    }

    impl Puppet for PuppetActor {
        type Supervision = OneForAll;

        async fn reset(&self, ctx: &Context<Self>) -> Result<Self, CriticalError> {
            Ok(Self {
                failures: self.failures,
            })
        }
    }

    #[derive(Debug)]
    struct MasterMessage;

    #[derive(Debug)]
    struct PuppetMessage;

    #[derive(Debug)]
    struct MasterFailingMessage;

    #[derive(Debug)]
    struct PuppetFailingMessage;

    impl Handler<MasterMessage> for MasterActor {
        type Response = ();
        type Executor = SequentialExecutor;
        async fn handle_message(
            &mut self,
            _msg: MasterMessage,
            _ctx: &Context<Self>,
        ) -> Result<Self::Response, PuppetError> {
            Ok(())
        }
    }

    impl Handler<PuppetMessage> for PuppetActor {
        type Response = ();
        type Executor = SequentialExecutor;
        async fn handle_message(
            &mut self,
            _msg: PuppetMessage,
            _ctx: &Context<Self>,
        ) -> Result<Self::Response, PuppetError> {
            Ok(())
        }
    }

    impl Handler<MasterFailingMessage> for MasterActor {
        type Response = ();
        type Executor = SequentialExecutor;
        async fn handle_message(
            &mut self,
            _msg: MasterFailingMessage,
            ctx: &Context<Self>,
        ) -> Result<Self::Response, PuppetError> {
            println!("Handling MasterFailingMessage. Failures: {}", self.failures);
            if self.failures < 3 {
                self.failures += 1;
                Err(PuppetError::critical(
                    ctx.pid,
                    "Failed to handle MasterFailingMessage",
                ))
            } else {
                Ok(())
            }
        }
    }

    impl Handler<PuppetFailingMessage> for PuppetActor {
        type Response = ();
        type Executor = SequentialExecutor;
        async fn handle_message(
            &mut self,
            _msg: PuppetFailingMessage,
            ctx: &Context<Self>,
        ) -> Result<Self::Response, PuppetError> {
            println!("Handling MasterFailingMessage. Failures: {}", self.failures);
            if self.failures < 3 {
                self.failures += 1;
                Err(PuppetError::critical(
                    ctx.pid,
                    "Failed to handle PuppetFailingMessage",
                ))
            } else {
                Ok(())
            }
        }
    }

    pub fn register_puppet<P, M>(pptr: &Puppeteer) -> Result<(), PuppetError>
    where
        P: Puppet,
        M: Puppet,
    {
        let (message_tx, _message_rx) = mpsc::unbounded_channel::<Box<dyn Envelope<P>>>();
        let (service_tx, _service_rx) = mpsc::channel::<ServicePacket>(1);
        let (status_tx, status_rx) = watch::channel::<PuppetStatus>(PuppetStatus::Inactive);
        let postman = Postman::new(message_tx);
        let service_postman = ServicePostman::new(service_tx);
        let master_pid = Pid::new::<M>();

        pptr.register_puppet_by_pid(master_pid, postman, service_postman, status_tx, status_rx)
    }

    #[tokio::test]
    async fn test_register() {
        let pptr = Puppeteer::new();

        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);

        // Master puppet doesn't exist

        assert!(res.is_err());

        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);

        // Master is same as puppet

        assert!(res.is_ok());
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);

        // Puppet already exists

        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_is_puppet_exists() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        assert!(pptr.is_puppet_exists::<PuppetActor>());
        assert!(!pptr.is_puppet_exists::<MasterActor>());
    }

    #[tokio::test]
    async fn test_get_postman() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        assert!(pptr.get_postman::<PuppetActor>().is_some());
        assert!(pptr.get_postman::<MasterActor>().is_none());
    }

    #[tokio::test]
    async fn test_get_service_postman_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr.get_service_postman_by_pid(puppet_pid).is_some());
        let master_pid = Pid::new::<MasterActor>();
        assert!(pptr.get_service_postman_by_pid(master_pid).is_none());
    }

    #[tokio::test]
    async fn test_get_status_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        let puppet_pid = Pid::new::<PuppetActor>();
        assert_eq!(
            pptr.get_puppet_status_by_pid(puppet_pid),
            Some(PuppetStatus::Inactive)
        );
        let master_pid = Pid::new::<MasterActor>();
        assert!(pptr.get_puppet_status_by_pid(master_pid).is_none());
    }

    #[tokio::test]
    async fn test_set_status_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        let puppet_pid = Pid::new::<PuppetActor>();
        pptr.set_status_by_pid(puppet_pid, PuppetStatus::Active);
        assert_eq!(
            pptr.get_puppet_status_by_pid(puppet_pid),
            Some(PuppetStatus::Active)
        );
    }

    #[tokio::test]
    async fn test_subscribe_status_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        let puppet_pid = Pid::new::<PuppetActor>();
        let rx = pptr.subscribe_puppet_status_by_pid(puppet_pid).unwrap();
        pptr.set_status_by_pid(puppet_pid, PuppetStatus::Active);
        assert_eq!(*rx.borrow(), PuppetStatus::Active);
    }

    #[tokio::test]
    async fn test_has_puppet_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr
            .puppet_has_puppet_by_pid(master_pid, puppet_pid)
            .is_some());
        let master_pid = Pid::new::<PuppetActor>();
        assert!(pptr
            .puppet_has_puppet_by_pid(master_pid, puppet_pid)
            .is_none());
    }

    #[tokio::test]
    async fn test_has_permission_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr
            .puppet_has_permission_by_pid(master_pid, puppet_pid)
            .is_some());
        let master_pid = Pid::new::<PuppetActor>();
        assert!(pptr
            .puppet_has_permission_by_pid(master_pid, puppet_pid)
            .is_none());
    }

    #[tokio::test]
    async fn test_get_master_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert_eq!(pptr.get_puppet_master_by_pid(puppet_pid), Some(master_pid));
        assert_eq!(pptr.get_puppet_master_by_pid(master_pid), Some(master_pid));
    }

    #[tokio::test]
    async fn test_set_master_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        assert!(res.is_ok());
        let res = register_puppet::<PuppetActor, PuppetActor>(&pptr);
        assert!(res.is_ok());
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr
            .set_puppet_master_by_pid(puppet_pid, master_pid, puppet_pid)
            .is_ok());
        assert_eq!(pptr.get_puppet_master_by_pid(puppet_pid), Some(master_pid));
        assert_eq!(pptr.get_puppet_master_by_pid(master_pid), Some(master_pid));
    }

    #[tokio::test]
    async fn test_get_puppets_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        res.unwrap();
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        res.unwrap();
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        let puppets = pptr.get_puppets_by_pid(master_pid).unwrap();
        assert_eq!(puppets.len(), 2);
        assert!(puppets.contains(&puppet_pid));
    }

    #[tokio::test]
    async fn test_detach_puppet_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        res.unwrap();
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        res.unwrap();
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr.detach_puppet_by_pid(master_pid, puppet_pid).is_ok());
        assert_eq!(pptr.get_puppet_master_by_pid(puppet_pid), Some(puppet_pid));
        assert_eq!(pptr.get_puppet_master_by_pid(master_pid), Some(master_pid));
    }

    #[tokio::test]
    async fn test_delete_puppet_by_pid() {
        let pptr = Puppeteer::new();
        let res = register_puppet::<MasterActor, MasterActor>(&pptr);
        res.unwrap();
        let res = register_puppet::<PuppetActor, MasterActor>(&pptr);
        res.unwrap();
        let master_pid = Pid::new::<MasterActor>();
        let puppet_pid = Pid::new::<PuppetActor>();
        assert!(pptr.delete_puppet_by_pid(master_pid, puppet_pid).is_ok());
        assert!(pptr.get_postman::<PuppetActor>().is_none());
        assert!(pptr.get_postman::<MasterActor>().is_some());
    }

    #[tokio::test]
    async fn test_spawn() {
        let pptr = Puppeteer::new();
        let res = pptr.spawn::<_, PuppetActor>(PuppetActor::default()).await;
        res.unwrap();
        let res = pptr.spawn::<_, MasterActor>(PuppetActor::default()).await;
        res.unwrap_err();
    }

    #[tokio::test]
    async fn test_send() {
        let pptr = Puppeteer::new();

        let res = pptr.spawn::<_, PuppetActor>(PuppetActor::default()).await;
        res.unwrap();

        let res = pptr.send::<PuppetActor, PuppetMessage>(PuppetMessage);
        res.unwrap();

        // Send without creating the puppet
        let res = pptr.send::<MasterActor, MasterMessage>(MasterMessage);
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_ask() {
        let pptr = Puppeteer::new();

        let res = pptr.spawn_self(PuppetActor::default()).await;
        res.unwrap();

        let res = pptr.ask::<PuppetActor, _>(PuppetMessage).await;
        res.unwrap();

        // Send without creating the puppet
        let res = pptr.ask::<MasterActor, _>(MasterMessage).await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_ask_with_timeout() {
        let pptr = Puppeteer::new();

        let res = pptr.spawn_self(PuppetActor::default()).await;
        assert!(res.is_ok());

        let res = pptr
            .ask_with_timeout::<PuppetActor, _>(PuppetMessage, Duration::from_secs(1))
            .await;
        assert!(res.is_ok());

        let res = pptr
            .ask_with_timeout::<MasterActor, _>(MasterMessage, Duration::from_secs(1))
            .await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn self_mutate_puppet() {
        #[derive(Debug, Clone, Default)]
        pub struct CounterPuppet {
            counter: i32,
        }

        impl Puppet for CounterPuppet {
            type Supervision = OneForAll;
            async fn reset(&self, _ctx: &Context<Self>) -> Result<Self, CriticalError> {
                Ok(CounterPuppet::default())
            }
        }

        #[derive(Debug)]
        pub struct IncrementCounter;

        impl Handler<IncrementCounter> for CounterPuppet {
            type Response = i32;
            type Executor = SequentialExecutor;
            async fn handle_message(
                &mut self,
                _msg: IncrementCounter,
                ctx: &Context<Self>,
            ) -> Result<Self::Response, PuppetError> {
                println!("Counter: {}", self.counter);
                if self.counter < 10 {
                    self.counter += 1;
                    ctx.send::<Self, _>(IncrementCounter)?;
                } else {
                    ctx.send::<Self, _>(DebugCounterPuppet)?;
                }
                Ok(self.counter)
            }
        }

        #[derive(Debug)]
        pub struct DebugCounterPuppet;

        impl Handler<DebugCounterPuppet> for CounterPuppet {
            type Response = i32;
            type Executor = SequentialExecutor;
            async fn handle_message(
                &mut self,
                _msg: DebugCounterPuppet,
                _ctx: &Context<Self>,
            ) -> Result<Self::Response, PuppetError> {
                Ok(self.counter)
            }
        }

        let pptr = Puppeteer::new();
        let address = pptr.spawn_self(CounterPuppet::default()).await.unwrap();
        address.send(IncrementCounter).unwrap();
        // wait 1 second for the puppet to finish
        tokio::time::sleep(Duration::from_secs(1)).await;
        let x = address.ask(DebugCounterPuppet).await.unwrap();
        assert_eq!(x, 10);
    }

    #[tokio::test]
    #[allow(unused_assignments)]
    async fn test_successful_recovery_after_failure() {
        let pptr = Puppeteer::new();
        let res = pptr.spawn_self(PuppetActor::default()).await;
        res.unwrap();
        let mut success = false;

        loop {
            let res = pptr.ask::<PuppetActor, _>(PuppetFailingMessage).await;
            if res.is_ok() {
                success = true;
                break;
            }
        }
        assert!(success);
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
    #[tokio::test]
    #[allow(unused_assignments)]
    async fn test_failed_recovery_after_failure() {
        let pptr = Puppeteer::new();
        let res = pptr.spawn_self(MasterActor::default()).await;
        res.unwrap();
        let mut success = false;

        loop {
            let res = pptr.ask::<MasterActor, _>(MasterFailingMessage).await;
            if res.is_err() {
                success = true;
                break;
            }
        }
        assert!(success);
        tokio::time::sleep(Duration::from_secs(1)).await;
    }

    #[tokio::test]
    async fn test_wait_for_unrecoverable_failure() {
        let pptr = Puppeteer::new();

        // Spawn a master actor that will fail after 3 attempts
        let res = pptr.spawn_self(MasterActor::default()).await;
        assert!(res.is_ok());

        // Send failing messages to trigger the unrecoverable failure
        for _ in 0..3 {
            let _ = pptr.ask::<MasterActor, _>(MasterFailingMessage).await;
        }

        // Wait for the unrecoverable failure
        let err = pptr.wait_for_unrecoverable_failure().await;

        // Verify the expected error details
        assert_eq!(err.puppet, Pid::new::<MasterActor>());
        assert_eq!(err.message, "Failed to reset MasterActor");
    }

    #[tokio::test]
    #[should_panic(expected = "Unrecoverable error encountered")]
    async fn test_wait_for_unrecoverable_failure_panic() {
        let pptr = Puppeteer::new();

        // Spawn a master actor that will fail after 3 attempts
        let res = pptr.spawn_self(MasterActor::default()).await;
        assert!(res.is_ok());

        // Send failing messages to trigger the unrecoverable failure
        for _ in 0..3 {
            let _ = pptr.ask::<MasterActor, _>(MasterFailingMessage).await;
        }

        // Wait for the unrecoverable failure and expect a panic
        let err = pptr.wait_for_unrecoverable_failure().await;
        panic!("Unrecoverable error encountered: {err:?}");
    }

    #[tokio::test]
    async fn test_wait_for_unrecoverable_failure_timeout() {
        let pptr = Puppeteer::new();

        // Spawn a puppet actor that will not fail
        let res = pptr.spawn_self(PuppetActor::default()).await;
        assert!(res.is_ok());

        // Wait for an unrecoverable failure with a timeout
        let result = tokio::time::timeout(
            Duration::from_millis(100),
            pptr.wait_for_unrecoverable_failure(),
        )
        .await;

        // Verify that the timeout occurred and no error was encountered
        assert!(result.is_err());
    }

    #[tokio::test]
    #[should_panic(expected = "Unrecoverable error encountered")]
    async fn test_unrecoverable_error_inside_puppet() {
        #[derive(Debug, Clone, Default)]
        struct UnrecoverablePuppet;

        #[derive(Debug)]
        struct UnrecoverableMessage;

        impl Puppet for UnrecoverablePuppet {
            type Supervision = OneForAll;
            async fn reset(&self, ctx: &Context<Self>) -> Result<Self, CriticalError> {
                Err(CriticalError::new(
                    ctx.pid,
                    "Failed to reset UnrecoverablePuppet",
                ))
            }
        }

        impl Handler<UnrecoverableMessage> for UnrecoverablePuppet {
            type Response = ();

            type Executor = SequentialExecutor;

            async fn handle_message(
                &mut self,
                msg: UnrecoverableMessage,
                ctx: &Context<Self>,
            ) -> Result<Self::Response, PuppetError> {
                Err(ctx.critical_error("Unrecoverable error"))
            }
        }

        let pptr = Puppeteer::new();

        let res = pptr.spawn_self(UnrecoverablePuppet).await;
        assert!(res.is_ok());

        pptr.send::<UnrecoverablePuppet, _>(UnrecoverableMessage)
            .unwrap();

        let result = pptr.wait_for_unrecoverable_failure().await;
        panic!("Unrecoverable error encountered: {result:?}");
    }

    #[tokio::test]
    async fn test_puppet_self_send_msg() {
        #[derive(Debug, Clone, Default)]
        struct SelfSendPuppet {
            i: i32,
        }

        #[derive(Debug)]
        struct SelfSendMessage;

        impl Puppet for SelfSendPuppet {
            type Supervision = OneForAll;
        }

        impl Handler<SelfSendMessage> for SelfSendPuppet {
            type Response = i32;

            type Executor = SequentialExecutor;

            async fn handle_message(
                &mut self,
                msg: SelfSendMessage,
                ctx: &Context<Self>,
            ) -> Result<Self::Response, PuppetError> {
                if self.i < 10 {
                    dbg!(self.i);
                    self.i += 1;
                    Ok(ctx.ask::<SelfSendPuppet, _>(SelfSendMessage).await?)
                } else {
                    dbg!("finish");
                    Ok(self.i)
                }
            }
        }

        let pptr = Puppeteer::new();

        let res = pptr.spawn_self(SelfSendPuppet { i: 0 }).await;
        assert!(res.is_ok());

        pptr.send::<SelfSendPuppet, _>(SelfSendMessage).unwrap();
        tokio::time::sleep(Duration::from_secs(1)).await;
    }

    // #[tokio::test]
    // #[should_panic(expected = "Unrecoverable error encountered")]
    // async fn test_unrecoverable_panic_inside_puppet() {
    //     #[derive(Debug, Clone, Default)]
    //     struct UnrecoverablePuppet;
    //
    //     #[derive(Debug)]
    //     struct UnrecoverableMessage;
    //
    //     impl Puppet for UnrecoverablePuppet {
    //         type Supervision = OneForAll;
    //         async fn reset(&self, ctx: &Context) -> Result<Self, CriticalError> {
    //             dbg!("1");
    //             Err(CriticalError::new(
    //                 ctx.pid,
    //                 "Failed to reset UnrecoverablePuppet",
    //             ))
    //         }
    //     }
    //
    //     impl Handler<UnrecoverableMessage> for UnrecoverablePuppet {
    //         type Response = ();
    //
    //         type Executor = SequentialExecutor;
    //
    //         async fn handle_message(
    //             &mut self,
    //             msg: UnrecoverableMessage,
    //             ctx: &Context,
    //         ) -> Result<Self::Response, PuppetError> {
    //             dbg!("2");
    //             panic!("Unrecoverable error");
    //         }
    //     }
    //
    //     let pptr = Puppeteer::new();
    //
    //     let res = pptr.spawn_self(UnrecoverablePuppet).await;
    //     assert!(res.is_ok());
    //
    //     pptr.send::<UnrecoverablePuppet, _>(UnrecoverableMessage)
    //         .await
    //         .unwrap();
    //
    //     let result = pptr.wait_for_unrecoverable_failure().await;
    //     panic!("Unrecoverable error encountered: {result:?}");
    // }
}