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
use std::sync::atomic::AtomicUsize;
use std::sync::{Arc, Weak};
use futures::{stream, Stream, StreamExt};
use tokio::sync::{mpsc, oneshot, RwLock};
use crate::actor::Actor;
use crate::actor_id::ActorID;
use crate::actor_runner::sys_msg::SysMsg;
use crate::actor_runner::ActorRunner;
use crate::spawn_opts::SpawnOpts;
use crate::system_config::SystemConfig;
use crate::{ActorInfo, ExitReason};
mod actor_entry;
use actor_entry::ActorEntry;
mod actor_id_pool;
use actor_id_pool::ActorIDPool;
mod errors;
pub use errors::{SysChannelError, SysSpawnError};
#[derive(Debug, Clone)]
pub struct System(Arc<Inner>);
impl System {
pub(crate) fn rc_downgrade(&self) -> SystemOpt {
SystemOpt(Arc::downgrade(&self.0))
}
}
#[derive(Debug, Clone)]
pub(crate) struct SystemOpt(Weak<Inner>);
impl SystemOpt {
pub(crate) fn rc_upgrade(&self) -> Option<System> {
self.0.upgrade().map(System)
}
}
impl System {
pub fn new(config: SystemConfig) -> Self {
static NEXT_SYSTEM_ID: AtomicUsize = AtomicUsize::new(1);
let system_id = NEXT_SYSTEM_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let actor_id_pool = ActorIDPool::new(system_id, config.max_actors);
let actor_entries = (0..config.max_actors).map(|_| RwLock::new(None)).collect();
let inner = Inner { config, system_id, actor_id_pool, actor_entries };
Self(Arc::new(inner))
}
pub fn config(&self) -> &SystemConfig {
&self.0.config
}
}
impl System {
pub async fn spawn<Behaviour, Arg, Message>(
&self,
behaviour: Behaviour,
arg: Arg,
spawn_opts: SpawnOpts,
) -> Result<ActorID, SysSpawnError>
where
Arg: Send + Sync + 'static,
Message: Unpin + Send + Sync + 'static,
for<'a> Behaviour: Actor<'a, Arg, Message>,
{
let system = self.to_owned();
let actor_id_lease =
system.0.actor_id_pool.acquire_id().ok_or(SysSpawnError::MaxActorsLimit)?;
let actor_id = *actor_id_lease;
let (messages_tx, messages_rx) = mpsc::unbounded_channel::<Message>();
let (sys_msg_tx, sys_msg_rx) = mpsc::unbounded_channel();
let actor = ActorRunner {
actor_id,
system_opt: system.rc_downgrade(),
messages_rx,
sys_msg_rx,
sys_msg_tx: sys_msg_tx.to_owned(),
spawn_opts,
};
tokio::spawn(actor.run(behaviour, arg));
let entry = ActorEntry { actor_id_lease, messages_tx: Box::new(messages_tx), sys_msg_tx };
self.actor_entry_put(entry).await;
Ok(actor_id)
}
pub async fn exit(&self, actor_id: ActorID, exit_reason: ExitReason) {
self.send_sys_msg(actor_id, SysMsg::SigExit(actor_id, exit_reason)).await;
}
pub async fn wait(&self, actor_id: ActorID) -> ExitReason {
let (tx, rx) = oneshot::channel();
if self.send_sys_msg(actor_id, SysMsg::Wait(tx)).await {
rx.await.unwrap_or_else(|_| ExitReason::NoActor)
} else {
ExitReason::NoActor
}
}
pub(crate) async fn send_sys_msg(&self, to: ActorID, sys_msg: SysMsg) -> bool {
self.actor_entry_read(to, |entry| entry.sys_msg_tx.send(sys_msg).ok())
.await
.flatten()
.is_some()
}
pub async fn send<M>(&self, actor_id: ActorID, message: M)
where
M: 'static,
{
let _ = self
.actor_entry_read(actor_id, move |e| {
e.messages_tx
.downcast_ref::<mpsc::UnboundedSender<M>>()
.map(move |tx| tx.send(message))
})
.await;
}
pub async fn channel<M>(
&self,
actor_id: ActorID,
) -> Result<mpsc::UnboundedSender<M>, SysChannelError>
where
M: 'static,
{
let chan = self
.actor_entry_read(actor_id, |e| {
e.messages_tx.downcast_ref::<mpsc::UnboundedSender<M>>().map(ToOwned::to_owned)
})
.await
.ok_or(SysChannelError::NoActor)?
.ok_or(SysChannelError::InvalidMessageType)?;
Ok(chan)
}
pub async fn link(&self, left: ActorID, right: ActorID) {
let left_accepted_sys_msg = self.send_sys_msg(left, SysMsg::Link(right)).await;
let right_accepted_sys_msg = self.send_sys_msg(right, SysMsg::Link(left)).await;
if !right_accepted_sys_msg {
self.send_sys_msg(left, SysMsg::SigExit(right, ExitReason::NoActor)).await;
}
if !left_accepted_sys_msg {
self.send_sys_msg(right, SysMsg::SigExit(left, ExitReason::NoActor)).await;
}
}
pub fn all_actors<'a>(&'a self) -> impl Stream<Item = ActorID> + 'a {
stream::iter(&self.0.actor_entries[..]).filter_map(|slot| async move {
let locked = slot.read().await;
locked.as_ref().map(|entry| *entry.actor_id_lease)
})
}
pub async fn actor_info(&self, actor_id: ActorID) -> Option<ActorInfo> {
let (tx, rx) = oneshot::channel();
self.send_sys_msg(actor_id, SysMsg::GetInfo(tx)).await;
rx.await.ok()
}
}
#[derive(Debug)]
struct Inner {
config: SystemConfig,
system_id: usize,
actor_id_pool: ActorIDPool,
actor_entries: Box<[RwLock<Option<ActorEntry>>]>,
}