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
use crate::addr::ActorEvent;
use crate::broker::{Subscribe, Unsubscribe};
use crate::{Addr, Broker, Error, Handler, Message, Result, Service};
use async_std::task;
use futures::channel::mpsc;
use futures::{Stream, StreamExt};
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
pub struct Context<A> {
actor_id: u64,
addr: Addr<A>,
}
impl<A> Context<A> {
pub(crate) fn new() -> (Arc<Self>, mpsc::UnboundedReceiver<ActorEvent<A>>) {
static ACTOR_ID: OnceCell<AtomicU64> = OnceCell::new();
let actor_id = ACTOR_ID
.get_or_init(|| Default::default())
.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::unbounded::<ActorEvent<A>>();
(
Arc::new(Self {
actor_id,
addr: Addr { actor_id, tx },
}),
rx,
)
}
pub fn address(&self) -> Addr<A> {
self.addr.clone()
}
pub fn actor_id(&self) -> u64 {
self.actor_id
}
pub fn stop(&self, err: Option<Error>) {
self.addr.tx.clone().start_send(ActorEvent::Stop(err)).ok();
}
pub fn add_stream<S>(&self, mut stream: S)
where
S: Stream + Unpin + Send + 'static,
S::Item: Message<Result = ()>,
A: Handler<S::Item>,
{
let mut addr = self.addr.clone();
task::spawn(async move {
while let Some(msg) = stream.next().await {
if let Err(_) = addr.send(msg) {
return;
}
}
});
}
pub fn send_later<T>(&self, msg: T, after: Duration)
where
A: Handler<T>,
T: Message<Result = ()>,
{
let mut addr = self.addr.clone();
task::spawn(async move {
task::sleep(after).await;
addr.send(msg).ok();
});
}
pub fn send_interval_with<T, F>(&self, f: F, dur: Duration)
where
A: Handler<T>,
F: Fn() -> T + Sync + Send + 'static,
T: Message<Result = ()>,
{
let mut addr = self.addr.clone();
task::spawn(async move {
loop {
task::sleep(dur).await;
if let Err(_) = addr.send(f()) {
break;
}
}
});
}
pub fn send_interval<T>(&self, msg: T, dur: Duration)
where
A: Handler<T>,
T: Message<Result = ()> + Clone + Sync,
{
self.send_interval_with(move || msg.clone(), dur);
}
pub async fn subscribe<T: Message<Result = ()>>(&self) -> Result<()>
where
A: Handler<T>,
{
let mut broker = Broker::<T>::from_registry().await;
broker.send(Subscribe {
id: self.actor_id,
sender: self.address().sender::<T>(),
})
}
pub async fn unsubscribe<T: Message<Result = ()>>(&self) -> Result<()> {
let mut broker = Broker::<T>::from_registry().await;
broker.send(Unsubscribe { id: self.actor_id })
}
}