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
#[cfg(feature = "async-global-executor14")]
extern crate async_global_executor14 as async_global_executor;
#[cfg(feature = "tokio02")]
extern crate tokio02 as tokio;
#[cfg(feature = "tokio10")]
extern crate tokio10 as tokio;
use std::future::Future;
use futures_channel::{mpsc, oneshot};
use futures_util::{
future::{self, Either, FutureExt},
stream::StreamExt,
task::SpawnExt,
};
use thiserror::Error;
pub fn actor_with_executor<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)
}
#[cfg(feature = "__global_executor")]
pub fn actor<A, S, R, E>(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();
#[cfg(feature = "async-global-executor14")]
async_global_executor::spawn(actor_future(rx, initial_state)).detach();
#[cfg(feature = "__tokio")]
tokio::spawn(actor_future(rx, initial_state));
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, Error)]
pub enum ActorError {
#[error("Cannot send message to actor")]
InvokeError,
#[error("Cannot wait for an answer")]
WaitError,
}
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
}
}