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
#[doc(hidden)] pub use ::tokio;
#[doc(hidden)] pub use ::futures;
#[doc(hidden)] pub use ::tracing;
#[doc(hidden)] pub use ::crossbeam;
#[doc(hidden)] pub use ::async_trait;
#[doc(hidden)] pub use ::async_channel;
#[doc(hidden)] pub use ::anyhow;
#[doc(hidden)] pub use ::downcast_rs;
use async_trait::async_trait;
use lazy_static::lazy_static;
use downcast_rs::{Downcast, DowncastSync};
use tokio::sync::{Notify, futures::Notified};
use std::{
sync::atomic::{AtomicUsize, Ordering::*},
time::Duration,
fmt::Debug,
collections::HashMap,
};
pub trait Message: Downcast + Send {}
impl<T: Send + 'static> Message for T {}
downcast_rs::impl_downcast!(Message);
#[async_trait]
pub trait Forwarder<M: Message> {
async fn forward(&self, msg: M);
}
#[async_trait]
pub trait Handler<M: Message> {
async fn handle(&self, msg: M) -> anyhow::Result<()>;
}
pub struct HandlerError {
inner: anyhow::Error,
msg_name: &'static str,
}
impl HandlerError {
pub fn new(msg_name: &'static str, err: anyhow::Error) -> Self {
Self { msg_name, inner: err }
}
pub fn msg_name(&self) -> &'static str {
self.msg_name
}
}
impl ::core::fmt::Debug for HandlerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum StartError {
#[error("the actor has already been started")]
AlreadyStarted,
#[error("the id ({0}) is already taken")]
AlreadyTakenId(ActorId),
}
#[async_trait]
pub trait Actor: Addr + LifecycleHook {
type Context;
fn new<Id: Into<ActorId> + Send>(id: Id, ctx: Self::Context) -> StrongAddr<Self>;
async fn ctx(&self) -> tokio::sync::RwLockReadGuard<Self::Context>;
async fn ctx_mut(&self) -> tokio::sync::RwLockWriteGuard<Self::Context>;
async fn start(self: &StrongAddr<Self>) -> Result<StrongAddr<Self>, StartError>
where Self: Sized;
}
#[async_trait]
pub trait Addr: DowncastSync + Sync {
async fn send<M: Message>(&self, msg: M) where Self: Forwarder<M> + Sized;
async fn send_erased(&self, msg: BoxedMessage);
fn state(&self) -> State;
fn close(&self);
fn id(&self) -> &str;
fn is_started(&self) -> bool {
self.state() != State::Pending
}
fn is_closed(&self) -> bool {
self.state() == State::Closing || self.state() == State::Closed
}
}
downcast_rs::impl_downcast!(sync Addr);
pub async fn send_to<Id: AsRef<str>, M: Message>(actor_id: Id, msg: M) {
let addr = query_actor_erased(actor_id).await.unwrap(); addr.send_erased(Box::new(msg)).await;
}
pub async fn send<A: Addr + Forwarder<M>, M: Message>(addr: StrongAddr<A>, msg: M) {
addr.send(msg).await;
}
pub async fn send_erased<M: Message>(addr: StrongErasedAddr, msg: M) {
addr.send_erased(Box::new(msg)).await;
}
#[async_trait]
pub trait LifecycleHook {
async fn on_started(&self) {}
async fn on_closed(&self) {}
}
#[async_trait]
pub trait ErasedTx: Send + Sync {
async fn send_erased(&self, msg: BoxedMessage);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Pending,
Starting,
Running,
Closing,
Closed,
}
impl Default for State {
fn default() -> Self {
Self::Pending
}
}
pub type ActorId = std::borrow::Cow<'static, str>;
pub type StrongAddr<A> = std::sync::Arc<A>;
pub type WeakAddr<A> = std::sync::Weak<A>;
pub type StrongErasedAddr = std::sync::Arc<dyn Addr>;
pub type WeakErasedAddr = std::sync::Weak<dyn Addr>;
pub type BoxedMessage = Box<dyn Message>;
pub type BoxedErasedTx = Box<dyn ErasedTx>;
pub static SHUTDOWN_SIGNAL: Notify = Notify::const_new();
pub static ACTORS_ALIVE: AtomicUsize = AtomicUsize::new(0);
lazy_static! {
pub static ref REGISTRY: tokio::sync::Mutex<HashMap<ActorId, WeakErasedAddr>> = Default::default();
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ActorQueryError {
#[error("actor has expired and is either closing or closed")]
Expired,
#[error("actor is not found in the registry")]
NotFound,
#[error("invalid type of actor queried")]
InvalidType,
}
pub async fn query_actor<A: Addr, Id: AsRef<str>>(id: Id) -> Result<StrongAddr<A>, ActorQueryError> {
let addr = query_actor_erased(id).await?;
let addr = if let Ok(addr) = addr.downcast_arc::<A>() {
addr
} else {
return Err(ActorQueryError::InvalidType);
};
Ok(addr)
}
pub async fn query_actor_erased<Id: AsRef<str>>(id: Id) -> Result<StrongErasedAddr, ActorQueryError> {
let reg = REGISTRY.lock().await;
let addr = reg.get(id.as_ref());
let addr = match addr {
Some(addr) => if let Some(addr) = addr.upgrade() {
if addr.is_closed() {
return Err(ActorQueryError::Expired);
} else {
addr
}
} else {
return Err(ActorQueryError::Expired);
},
None => {
return Err(ActorQueryError::NotFound);
},
};
Ok(addr)
}
pub fn shutdown() {
SHUTDOWN_SIGNAL.notify_waiters();
}
pub fn shutdown_future<'a>() -> Notified<'a> {
SHUTDOWN_SIGNAL.notified()
}
pub fn add_actor() {
ACTORS_ALIVE.fetch_add(1, Release);
}
pub fn remove_actor() {
ACTORS_ALIVE.fetch_sub(1, Release);
}
pub async fn wait_for_shutdowns() {
while ACTORS_ALIVE.load(Acquire) != 0 {
tokio::time::sleep(Duration::from_millis(500)).await;
}
}