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
335
336
337
338
339
340
341
342
343
344
345
use crate::envelope::{MessageEnvelope, NonReturningEnvelope};
use crate::manager::{ContinueManageLoop, ManagerMessage};
use crate::{Actor, Address, Handler, KeepRunning, Message, WeakAddress};
use futures::channel::mpsc::UnboundedReceiver;
use futures::future::{self, Either, Future};
use futures::StreamExt;
use std::sync::Arc;
#[cfg(any(
doc,
feature = "with-tokio-0_2",
feature = "with-async_std-1",
feature = "with-wasm_bindgen-0_2",
feature = "with-smol-0_1"
))]
use {crate::AddressExt, std::time::Duration};
pub struct Context<A: Actor> {
pub(crate) running: bool,
address: WeakAddress<A>,
pub(crate) immediate_notifications: Vec<Box<dyn MessageEnvelope<Actor = A>>>,
pub(crate) receiver: UnboundedReceiver<ManagerMessage<A>>,
ref_counter: Arc<()>,
}
impl<A: Actor> Context<A> {
pub(crate) fn new(
address: WeakAddress<A>,
receiver: UnboundedReceiver<ManagerMessage<A>>,
ref_counter: Arc<()>,
) -> Self {
Context {
running: true,
address,
immediate_notifications: Vec::new(),
receiver,
ref_counter,
}
}
pub fn stop(&mut self) {
self.running = false;
}
pub fn address(&self) -> Option<Address<A>> {
if self.running {
let strong = Address {
sender: self.address.sender.clone(),
ref_counter: self.address.ref_counter.upgrade().unwrap(),
};
Some(strong)
} else {
None
}
}
pub(crate) fn check_running(&mut self, actor: &mut A) -> bool {
if !self.running {
let keep_running = actor.stopping(self);
if keep_running == KeepRunning::Yes {
self.running = true;
} else {
return false;
}
}
true
}
async fn handle_immediate_notification(&mut self, actor: &mut A) -> Option<bool> {
if let Some(notification) = self.immediate_notifications.pop() {
notification.handle(actor, self).await;
return Some(self.check_running(actor));
}
None
}
async fn handle_immediate_notifications(&mut self, actor: &mut A) -> bool {
while let Some(continue_running) = self.handle_immediate_notification(actor).await {
if !continue_running {
return false;
}
}
true
}
pub(crate) async fn handle_message(
&mut self,
msg: ManagerMessage<A>,
actor: &mut A,
) -> ContinueManageLoop {
match msg {
ManagerMessage::Message(msg) | ManagerMessage::LateNotification(msg) => {
msg.handle(actor, self).await;
if !self.check_running(actor) {
return ContinueManageLoop::ExitImmediately;
}
if !self.handle_immediate_notifications(actor).await {
return ContinueManageLoop::ExitImmediately;
}
}
ManagerMessage::LastAddress => {
if Arc::strong_count(&self.ref_counter) == 1 {
self.stop();
return ContinueManageLoop::ProcessNotifications;
}
}
}
ContinueManageLoop::Yes
}
pub async fn yield_once(&mut self, act: &mut A) {
if let Some(keep_running) = self.handle_immediate_notification(act).await {
if !keep_running {
self.stop();
}
return;
}
match self.receiver.next().await {
Some(msg) => {
self.handle_message(msg, act).await;
}
None => self.stop(),
}
}
#[cfg_attr(doc, doc(include = "../examples/interleaved_messages.rs"))]
pub async fn handle_while<F, R>(&mut self, act: &mut A, mut fut: F) -> R
where
F: Future<Output = R> + Unpin,
{
if !self.handle_immediate_notifications(act).await {
self.stop();
}
let mut next_msg = self.receiver.next();
loop {
match future::select(fut, next_msg).await {
Either::Left((res, _)) => break res,
Either::Right((manager_message, unfinished_fut)) => {
match manager_message {
Some(msg) => {
self.handle_message(msg, act).await;
}
None => self.stop(),
}
next_msg = self.receiver.next();
fut = unfinished_fut;
}
}
}
}
pub fn notify_immediately<M>(&mut self, msg: M)
where
M: Message,
A: Handler<M>,
{
let envelope = Box::new(NonReturningEnvelope::<A, M>::new(msg));
self.immediate_notifications.push(envelope);
}
pub fn notify_later<M>(&mut self, msg: M)
where
M: Message,
A: Handler<M>,
{
let envelope = NonReturningEnvelope::<A, M>::new(msg);
let _ = self
.address
.sender
.unbounded_send(ManagerMessage::LateNotification(Box::new(envelope)));
}
#[cfg(any(
doc,
feature = "with-tokio-0_2",
feature = "with-async_std-1",
feature = "with-wasm_bindgen-0_2",
feature = "with-smol-0_1"
))]
#[cfg_attr(doc, doc(cfg(feature = "with-tokio-0_2")))]
#[cfg_attr(doc, doc(cfg(feature = "with-async_std-1")))]
#[cfg_attr(doc, doc(cfg(feature = "with-wasm_bindgen-0_2")))]
#[cfg_attr(doc, doc(cfg(feature = "with-smol-0_1")))]
pub fn notify_interval<F, M>(&mut self, duration: Duration, constructor: F)
where
F: Send + 'static + Fn() -> M,
M: Message,
A: Handler<M>,
{
let addr = self.address.clone();
#[cfg(feature = "with-tokio-0_2")]
tokio::spawn(async move {
let mut timer = tokio::time::interval(duration);
loop {
timer.tick().await;
if let Err(_) = addr.do_send(constructor()) {
break;
}
}
});
#[cfg(feature = "with-async_std-1")]
{
use async_std::prelude::FutureExt;
async_std::task::spawn(async move {
loop {
futures::future::ready(()).delay(duration.clone()).await;
if let Err(_) = addr.do_send(constructor()) {
break;
}
}
});
}
#[cfg(feature = "with-wasm_bindgen-0_2")]
{
use futures_timer::Delay;
wasm_bindgen_futures::spawn_local(async move {
loop {
Delay::new(duration.clone()).await;
if let Err(_) = addr.do_send(constructor()) {
break;
}
}
})
}
#[cfg(feature = "with-smol-0_1")]
{
use smol::Timer;
smol::Task::spawn(async move {
loop {
Timer::after(duration.clone()).await;
if let Err(_) = addr.do_send(constructor()) {
break;
}
}
})
.detach();
}
}
#[cfg(any(
doc,
feature = "with-tokio-0_2",
feature = "with-async_std-1",
feature = "with-wasm_bindgen-0_2",
feature = "with-smol-0_1"
))]
#[cfg_attr(doc, doc(cfg(feature = "with-tokio-0_2")))]
#[cfg_attr(doc, doc(cfg(feature = "with-async_std-1")))]
#[cfg_attr(doc, doc(cfg(feature = "with-wasm_bindgen-0_2")))]
#[cfg_attr(doc, doc(cfg(feature = "with-smol-0_1")))]
pub fn notify_after<M>(&mut self, duration: Duration, notification: M)
where
M: Message,
A: Handler<M>,
{
let addr = self.address.clone();
#[cfg(feature = "with-tokio-0_2")]
tokio::spawn(async move {
tokio::time::delay_for(duration).await;
let _ = addr.do_send(notification);
});
#[cfg(feature = "with-async_std-1")]
{
use async_std::prelude::FutureExt;
async_std::task::spawn(async move {
futures::future::ready(()).delay(duration.clone()).await;
let _ = addr.do_send(notification);
});
}
#[cfg(feature = "with-wasm_bindgen-0_2")]
{
use futures_timer::Delay;
wasm_bindgen_futures::spawn_local(async move {
Delay::new(duration.clone()).await;
let _ = addr.do_send(notification);
})
}
#[cfg(feature = "with-smol-0_1")]
{
use smol::Timer;
smol::Task::spawn(async move {
Timer::after(duration.clone()).await;
let _ = addr.do_send(notification);
})
.detach();
}
}
}