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
use std::{any::Any, collections::HashMap, sync::Arc};
use tokio::sync::RwLock;
use crate::{ActorError, ActorPath, actor::{Actor, ActorRef, runner::ActorRunner}, bus::{EventBus, EventConsumer}};
pub trait SystemEvent: Clone + Send + Sync + 'static {}
#[derive(Clone)]
pub struct ActorSystem<E: SystemEvent> {
name: String,
actors: Arc<RwLock<HashMap<ActorPath, Box<dyn Any + Send + Sync + 'static>>>>,
bus: EventBus<E>
}
impl<E: SystemEvent> ActorSystem<E> {
pub fn name(&self) -> &str {
&self.name
}
pub fn publish(&self, event: E) {
self.bus.send(event).unwrap_or_else(|error| {
log::warn!(
"No listeners active on event bus. Dropping event: {:?}",
&error.to_string(),
);
0
});
}
pub fn events(&self) -> EventConsumer<E> {
self.bus.subscribe()
}
pub async fn get_actor<A: Actor<E>>(&self, path: &ActorPath) -> Option<ActorRef<E, A>> {
let actors = self.actors.read().await;
actors.get(path).and_then(|any| {
any.downcast_ref::<ActorRef<E, A>>().cloned()
})
}
pub(crate) async fn create_actor_path<A: Actor<E>>(&self, path: ActorPath, actor: A) -> Result<ActorRef<E, A>, ActorError> {
log::debug!("Creating actor '{}' on system '{}'...", &path, &self.name);
let mut actors = self.actors.write().await;
if actors.contains_key(&path) {
return Err(ActorError::Exists( path ))
}
let system = self.clone();
let (mut runner, actor_ref) = ActorRunner::create(path, actor);
tokio::spawn( async move {
runner.start(system).await;
});
let path = actor_ref.get_path().clone();
let any = Box::new(actor_ref.clone());
actors.insert(path, any);
Ok(actor_ref)
}
pub async fn create_actor<A: Actor<E>>(&self, name: &str, actor: A) -> Result<ActorRef<E, A>, ActorError> {
let path = ActorPath::from("/user") / name;
self.create_actor_path(path, actor).await
}
pub async fn stop_actor(&self, path: &ActorPath) {
log::debug!("Stopping actor '{}' on system '{}'...", &path, &self.name);
let mut paths: Vec<ActorPath> = Vec::new();
{
let current_actors = self.actors.read().await;
for child in current_actors.keys() {
if child.is_descendant_of(path) {
paths.push(child.clone());
}
}
}
paths.sort_unstable();
paths.reverse();
let mut actors = self.actors.write().await;
for path in &paths {
actors.remove(path);
}
}
pub fn new(name: &str, bus: EventBus<E>) -> Self {
let name = name.to_string();
let actors = Arc::new(RwLock::new(HashMap::new()));
ActorSystem { name, actors, bus }
}
}
#[cfg(test)]
mod tests {
use async_trait::async_trait;
use crate::actor::{Actor, ActorContext, Handler, Message};
use super::*;
#[derive(Clone, Debug)]
struct TestEvent(String);
impl SystemEvent for TestEvent {}
#[derive(Clone)]
struct TestActor {
counter: usize
}
#[async_trait]
impl Actor<TestEvent> for TestActor {
async fn pre_start(&mut self, _ctx: &mut ActorContext<TestEvent>) {
log::debug!("Starting actor TestActor!");
}
async fn post_stop(&mut self, _ctx: &mut ActorContext<TestEvent>) {
log::debug!("Stopped actor TestActor!");
}
}
#[derive(Clone, Debug)]
struct TestMessage(usize);
impl Message for TestMessage {
type Response = usize;
}
impl SystemEvent for TestMessage {}
#[async_trait]
impl Handler<TestEvent, TestMessage> for TestActor {
async fn handle(&mut self, msg: TestMessage, ctx: &mut ActorContext<TestEvent>) -> usize {
log::debug!("received message! {:?}", &msg);
self.counter += 1;
log::debug!("counter is now {}", &self.counter);
log::debug!("{} on system {}", &ctx.path, ctx.system.name());
ctx.system.publish(TestEvent("Message received!".to_string()));
self.counter
}
}
#[derive(Clone)]
struct OtherActor {
message: String,
child: Option<ActorRef<TestEvent, TestActor>>
}
#[async_trait]
impl Actor<TestEvent> for OtherActor {
async fn pre_start(&mut self, ctx: &mut ActorContext<TestEvent>) {
let child = TestActor { counter: 0 };
self.child = ctx.create_child("child", child).await.ok();
}
async fn post_stop(&mut self, _ctx: &mut ActorContext<TestEvent>) {
log::debug!("OtherActor stopped.");
}
}
#[derive(Clone, Debug)]
struct OtherMessage(String);
impl Message for OtherMessage {
type Response = String;
}
#[async_trait]
impl Handler<TestEvent, OtherMessage> for OtherActor {
async fn handle(&mut self, msg: OtherMessage, ctx: &mut ActorContext<TestEvent>) -> String {
log::debug!("OtherActor received message! {:?}", &msg);
log::debug!("original message is {}", &self.message);
self.message = msg.0;
log::debug!("message is now {}", &self.message);
log::debug!("{} on system {}", &ctx.path, ctx.system.name());
ctx.system.publish(TestEvent("Received message!".to_string()));
self.message.clone()
}
}
#[tokio::test]
async fn actor_create() {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "trace");
}
let _ = env_logger::builder().is_test(true).try_init();
let actor = TestActor { counter: 0 };
let msg = TestMessage(10);
let bus = EventBus::<TestEvent>::new(1000);
let system = ActorSystem::new("test", bus);
let mut actor_ref = system.create_actor("test-actor", actor).await.unwrap();
let result = actor_ref.ask(msg).await.unwrap();
assert_eq!(result, 1);
}
#[tokio::test]
async fn actor_stop() {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "trace");
}
let _ = env_logger::builder().is_test(true).try_init();
let actor = TestActor { counter: 0 };
let msg = TestMessage(10);
let bus = EventBus::<TestEvent>::new(1000);
let system = ActorSystem::new("test", bus);
{
let mut actor_ref = system.create_actor("test-actor", actor).await.unwrap();
let result = actor_ref.ask(msg).await.unwrap();
assert_eq!(result, 1);
system.stop_actor(actor_ref.get_path()).await;
}
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
}
#[tokio::test]
async fn actor_events() {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "trace");
}
let _ = env_logger::builder().is_test(true).try_init();
let actor = TestActor { counter: 0 };
let msg = TestMessage(10);
let bus = EventBus::<TestEvent>::new(1000);
let system = ActorSystem::new("test", bus);
let mut actor_ref = system.create_actor("test-actor", actor).await.unwrap();
let mut events = system.events();
tokio::spawn(async move {
loop {
match events.recv().await {
Ok(event) => println!("Received event! {:?}", event),
Err(err) => println!("Error receivng event!!! {:?}", err)
}
}
});
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
let result = actor_ref.ask(msg).await.unwrap();
assert_eq!(result, 1);
}
#[tokio::test]
async fn actor_get() {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "trace");
}
let _ = env_logger::builder().is_test(true).try_init();
let actor = TestActor { counter: 0 };
let bus = EventBus::<TestEvent>::new(1000);
let system = ActorSystem::new("test", bus);
let original = system.create_actor("test-actor", actor).await.unwrap();
if let Some(mut actor_ref) = system.get_actor::<TestActor>(original.get_path()).await {
let msg = TestMessage(10);
let result = actor_ref.ask(msg).await.unwrap();
assert_eq!(result, 1);
} else {
panic!("It should have retrieved the actor!")
}
if let Some(mut actor_ref) = system.get_actor::<OtherActor>(original.get_path()).await {
let msg = OtherMessage("Hello world!".to_string());
let result = actor_ref.ask(msg).await.unwrap();
println!("Result is: {}", result);
panic!("It should not go here!");
}
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
#[tokio::test]
async fn actor_parent_child() {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "trace");
}
let _ = env_logger::builder().is_test(true).try_init();
let actor = OtherActor {
message: "Initial".to_string(),
child: None
};
let bus = EventBus::<TestEvent>::new(1000);
let system = ActorSystem::new("test", bus);
{
let mut actor_ref = system.create_actor("test-actor", actor).await.unwrap();
let msg = OtherMessage("new message!".to_string());
let result = actor_ref.ask(msg).await.unwrap();
assert_eq!(result, "new message!".to_string());
tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await;
system.stop_actor(actor_ref.get_path()).await;
}
tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await;
let actors = system.actors.read().await;
for actor in actors.keys() {
println!("Still active!: {:?}", actor);
}
assert_eq!(actors.len(), 0);
}
}