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
use std::{error::Error, fmt, future::Future};
use futures_channel::{mpsc, oneshot};
use futures_util::{
future::{self, Either, FutureExt},
stream::StreamExt,
task::SpawnExt,
};
pub fn actor<A, S, R, E>(executor: impl SpawnExt, initial_state: S) -> ActorSender<A, R, E>
where
A: Action<State = S, Result = R, Error = E> + Send + 'static,
S: Send + 'static,
R: Send + 'static,
E: Send + 'static,
{
let (tx, rx) = mpsc::unbounded();
executor
.spawn(actor_future(rx, initial_state))
.expect("Cannot schedule actor on executor");
ActorSender(tx)
}
type ActorSenderInner<A, R, E> = mpsc::UnboundedSender<(A, oneshot::Sender<Result<R, E>>)>;
#[derive(Debug)]
pub struct ActorSender<A, R, E>(ActorSenderInner<A, R, E>);
impl<A, R, E> Clone for ActorSender<A, R, E> {
fn clone(&self) -> Self {
ActorSender(self.0.clone())
}
}
impl<A, R, E> ActorSender<A, R, E>
where
A: Send + 'static,
R: Send + 'static,
E: Send + From<ActorError> + 'static,
{
pub fn invoke(&self, action: A) -> impl Future<Output = ActResult<R, E>> {
let (tx, rx) = oneshot::channel();
if let Err(e) = self.0.unbounded_send((action, tx)) {
Either::Right(future::err(ActorError::from(e).into()))
} else {
Either::Left(rx.then(|result| match result {
Ok(Ok(r)) => future::ok(r),
Ok(Err(e)) => future::err(e),
Err(e) => future::err(ActorError::from(e).into()),
}))
}
}
}
async fn actor_future<A, S, R, E>(
mut receiver: mpsc::UnboundedReceiver<(A, oneshot::Sender<Result<R, E>>)>,
mut state: S,
) where
A: Action<State = S, Result = R, Error = E>,
{
while let Some((a, tx)) = receiver.next().await {
let _ = tx.send(a.act(&mut state));
}
}
pub trait Action {
type State;
type Result;
type Error;
fn act(self, s: &mut Self::State) -> Result<Self::Result, Self::Error>;
}
pub type ActResult<R, E> = Result<R, E>;
#[derive(Debug)]
pub enum ActorError {
InvokeError,
WaitError,
}
impl Error for ActorError {
fn description(&self) -> &str {
match self {
ActorError::InvokeError => "Cannot send message to actor",
ActorError::WaitError => "Cannot wait for an answer",
}
}
}
impl fmt::Display for ActorError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.description())
}
}
impl<T> From<mpsc::TrySendError<T>> for ActorError {
fn from(_from: mpsc::TrySendError<T>) -> Self {
ActorError::InvokeError
}
}
impl From<oneshot::Canceled> for ActorError {
fn from(_from: oneshot::Canceled) -> Self {
ActorError::WaitError
}
}