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
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::default::Default;
use std::sync::{Arc, Mutex};
use actor::{Actor, Supervised};
use arbiter::Arbiter;
use address::{Address, SyncAddress};
use context::Context;
use supervisor::Supervisor;
pub struct Registry {
registry: RefCell<HashMap<TypeId, Box<Any>>>,
}
#[allow(unused_variables)]
pub trait ArbiterService: Actor<Context=Context<Self>> + Supervised + Default {
fn service_started(&mut self, ctx: &mut Context<Self>) {}
}
#[allow(unused_variables)]
pub trait SystemService: Actor<Context=Context<Self>> + Supervised + Default {
fn service_started(&mut self, ctx: &mut Context<Self>) {}
}
impl Registry {
pub(crate) fn new() -> Self {
Registry{registry: RefCell::new(HashMap::new())}
}
pub fn get<A: ArbiterService + Actor<Context=Context<A>>>(&self) -> Address<A> {
let id = TypeId::of::<A>();
if let Some(addr) = self.registry.borrow().get(&id) {
if let Some(addr) = addr.downcast_ref::<Address<A>>() {
return addr.clone()
}
}
let addr: Address<_> = A::create(|ctx| {
let mut act = A::default();
act.service_started(ctx);
act
});
self.registry.borrow_mut().insert(id, Box::new(addr.clone()));
addr
}
}
pub struct SystemRegistry {
#[cfg_attr(feature="cargo-clippy", allow(type_complexity))]
registry: Arc<Mutex<RefCell<HashMap<TypeId, Box<Any>>>>>,
}
unsafe impl Send for SystemRegistry {}
impl SystemRegistry {
pub(crate) fn new() -> Self {
SystemRegistry{registry: Arc::new(Mutex::new(RefCell::new(HashMap::new())))}
}
pub fn get<A: SystemService + Actor<Context=Context<A>>>(&self) -> SyncAddress<A> {
if let Ok(hm) = self.registry.lock() {
if let Some(addr) = hm.borrow().get(&TypeId::of::<A>()) {
match addr.downcast_ref::<SyncAddress<A>>() {
Some(addr) => {
return addr.clone()
},
None =>
error!("Got unknown value: {:?}", addr),
}
}
let addr = Supervisor::start_in(&Arbiter::system_arbiter(), false, |ctx| {
let mut act = A::default();
act.service_started(ctx);
act
}).expect("System is dead");
hm.borrow_mut().insert(TypeId::of::<A>(), Box::new(addr.clone()));
return addr
}
panic!("System registry lock is poisoned");
}
}
impl Clone for SystemRegistry {
fn clone(&self) -> Self {
SystemRegistry{registry: Arc::clone(&self.registry)}
}
}