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
use crate::{
channel, Address, Controller, Envelope, Id, Operator, Supervisor, TerminationProgress,
Terminator,
};
use anyhow::Error;
use async_trait::async_trait;
use futures::channel::mpsc;
use futures::{select_biased, StreamExt};
use uuid::Uuid;
const MESSAGES_CHANNEL_DEPTH: usize = 32;
fn spawn<A: Actor>(actor: A, supervisor: Option<impl Into<Controller>>) -> Address<A> {
let id = Id::of_actor(&actor);
let supervisor = supervisor.map(Into::into);
let (controller, operator) = channel::pair(id, supervisor);
let id = controller.id();
let (msg_tx, msg_rx) = mpsc::channel(MESSAGES_CHANNEL_DEPTH);
let (hp_msg_tx, hp_msg_rx) = mpsc::unbounded();
let address = Address::new(controller, msg_tx, hp_msg_tx);
let context = Context {
address: address.clone(),
terminator: Terminator::new(id.clone()),
};
let runtime = ActorRuntime {
id,
actor,
context,
operator,
msg_rx,
hp_msg_rx,
};
tokio::spawn(runtime.entrypoint());
address
}
#[async_trait]
pub trait Actor: Sized + Send + 'static {
fn name(&self) -> String {
let uuid = Uuid::new_v4();
format!("Actor:{}({})", std::any::type_name::<Self>(), uuid)
}
fn start<T>(self, supervisor: Option<T>) -> Address<Self>
where
T: Into<Controller> + Send,
{
spawn(self, supervisor)
}
async fn initialize(&mut self, _ctx: &mut Context<Self>) -> Result<(), Error> {
Ok(())
}
async fn stop_signal(
&mut self,
child: Option<Id>,
ctx: &mut Context<Self>,
) -> TerminationProgress {
ctx.terminator().track_child_or_stop_signal(child)
}
async fn terminate(&mut self) {}
}
pub struct Context<A: Actor> {
address: Address<A>,
terminator: Terminator,
}
impl<A: Actor> Context<A> {
pub fn address(&mut self) -> &mut Address<A> {
&mut self.address
}
pub fn bind(&mut self) -> Supervisor {
Some(self.address.controller())
}
pub fn terminator(&mut self) -> &mut Terminator {
&mut self.terminator
}
}
pub struct ActorRuntime<A: Actor> {
id: Id,
actor: A,
context: Context<A>,
operator: Operator,
msg_rx: mpsc::Receiver<Envelope<A>>,
hp_msg_rx: mpsc::UnboundedReceiver<Envelope<A>>,
}
impl<A: Actor> ActorRuntime<A> {
async fn entrypoint(mut self) {
self.operator.initialize();
log::info!("Starting actor: {:?}", self.id);
if let Err(err) = self.actor.initialize(&mut self.context).await {
log::error!("Initialization failed: {:?}", err);
} else {
self.routine().await;
}
self.actor.terminate().await;
log::info!("Actor finished: {:?}", self.id);
self.operator.finalize();
}
async fn routine(&mut self) {
loop {
select_biased! {
event = self.operator.next() => {
log::trace!("Stop signal received: {:?} for {:?}", event, self.id);
let signal = event.expect("actor controller couldn't be closed");
let progress = self.actor.stop_signal(signal.into(), &mut self.context).await;
if progress == TerminationProgress::SafeToStop {
log::info!("Actor {:?} is completed.", self.id);
self.msg_rx.close();
break;
}
}
hp_envelope = self.hp_msg_rx.next() => {
if let Some(mut envelope) = hp_envelope {
let handle_res = envelope.handle(&mut self.actor, &mut self.context).await;
if let Err(err) = handle_res {
log::error!("Handler for {:?} (high-priority) failed: {}", self.id, err);
}
} else {
log::trace!("Messages stream of {:?} (high-priority) drained.", self.id);
}
}
lp_envelope = self.msg_rx.next() => {
if let Some(mut envelope) = lp_envelope {
let handle_res = envelope.handle(&mut self.actor, &mut self.context).await;
if let Err(err) = handle_res {
log::error!("Handler for {:?} failed: {}", self.id, err);
}
} else {
log::trace!("Messages stream of {:?} drained.", self.id);
}
}
}
}
}
}