apocalypse/demon.rs
1use std::future::Future;
2pub use self::location::Location;
3mod location;
4
5/// Demon trait
6///
7/// Demons are actors in the apocalypse framework. Implement this trait in your actors to allow them to reply to messages.
8pub trait Demon: Sized + std::marker::Send + 'static{
9 type Input;
10 type Output;
11
12 /// Function that is called when a demon is spawned
13 ///
14 /// By default, the function does nothing.
15 ///
16 /// ```rust,no_run
17 /// use apocalypse::{Demon, Location};
18 ///
19 /// struct EchoBot;
20 ///
21 /// impl Demon for EchoBot {
22 /// type Input = String;
23 /// type Output = String;
24 ///
25 /// // Callback for demon spawning
26 /// async fn spawned(&mut self, location: Location<Self>) {
27 /// log::debug!("Spawned echo bot with location {}", location);
28 /// }
29 ///
30 /// // Basic implementation of an echo handle function
31 /// async fn handle(&mut self, message: Self::Input) -> Self::Output {
32 /// message
33 /// }
34 /// }
35 /// ```
36 fn spawned(&mut self, _location: Location<Self>) -> impl Future<Output = ()> + Send {
37 async {}
38 }
39
40 /// Handler function for messages
41 ///
42 /// This is the main function, called for every message that the broker receives.
43 ///
44 /// ```rust,no_run
45 /// use apocalypse::Demon;
46 ///
47 /// struct EchoBot;
48 ///
49 /// impl Demon for EchoBot {
50 /// type Input = String;
51 /// type Output = String;
52 ///
53 /// // Basic implementation of an echo handle function
54 /// async fn handle(&mut self, message: Self::Input) -> Self::Output {
55 /// message
56 /// }
57 /// }
58 /// ```
59 fn handle(&mut self, message: Self::Input) -> impl Future<Output = Self::Output> + Send;
60
61 /// Function that is called when a demon is removed
62 ///
63 /// By default, the function does nothing.
64 ///
65 /// ```rust,no_run
66 /// use apocalypse::{Demon, Location};
67 ///
68 /// struct EchoBot;
69 ///
70 /// impl Demon for EchoBot {
71 /// type Input = String;
72 /// type Output = String;
73 ///
74 /// // Basic implementation of an echo handle function
75 /// async fn handle(&mut self, message: Self::Input) -> Self::Output {
76 /// message
77 /// }
78 ///
79 /// // Callback function
80 /// async fn vanquished(self) {
81 /// log::debug!("Killed echo bot");
82 /// }
83 /// }
84 /// ```
85 fn vanquished(self) -> impl Future<Output = ()> + Send {
86 async {}
87 }
88
89 /// This id will be printed in the debug logs of the demon's thread.
90 ///
91 /// It is useful when some lockup is happening and you have trouble to find it.
92 #[cfg(feature = "full_log")]
93 fn id(&self) -> String {
94 "".to_string()
95 }
96
97 /// This id will be printed in the debug logs of the demon's thread, in case the [spawn_multiple](crate::Gate::spawn_multiple) function is used.
98 ///
99 /// It is useful when some lockup is happening and you have trouble to find it.
100 #[cfg(feature = "full_log")]
101 fn multiple_id() -> &'static str {
102 ""
103 }
104}