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
use crate::{
    actor::Actor,
    request::{Request, RequestError, RequestTimeoutError},
};
use async_trait::async_trait;
use dyn_clone::DynClone;
use std::{
    error::Error,
    fmt::{Debug, Display},
    hash::Hash,
    time::Duration,
};
use tokio::{sync::mpsc, time::timeout};
use uuid::Uuid;

pub struct Addr<A>
where
    A: Actor,
{
    id: Uuid,
    sender: mpsc::Sender<A::Msg>,
}

impl<A> Addr<A>
where
    A: Actor,
{
    pub(crate) fn new(sender: mpsc::Sender<A::Msg>) -> Self {
        Self {
            id: Uuid::new_v4(),
            sender,
        }
    }

    /// Send a message to this actor.
    ///
    /// This will block (asynchronously) if the actor's buffer is full
    ///
    /// # Errors
    ///
    /// This will error if the actor is no longer running.
    pub async fn send(&self, msg: impl Into<A::Msg>) -> Result<(), SendError> {
        self.sender.send(msg.into()).await.map_err(|_| SendError)
    }

    pub fn recipient<M>(self) -> Recipient<M>
    where
        M: 'static + Into<A::Msg> + Send,
    {
        self.into()
    }

    /// Send a [`Request`](crate::Request) to this actor and await the response.
    ///
    /// This could wait indefinitely if the actor never responds, however it will error if the actor
    /// is stopped before or during the request, or if the response sender is otherwise dropped.
    pub async fn request<Req, Res>(&self, payload: Req) -> Result<Res, RequestError>
    where
        Request<Req, Res>: Into<A::Msg>,
    {
        let (request, receiver) = Request::new(payload);
        self.sender
            .send(request.into())
            .await
            .map_err(|_| RequestError::ActorStopped)?;
        let res = receiver.await.map_err(|_| RequestError::SenderDropped)?;
        Ok(res)
    }

    /// Send a [`Request`](crate::Request) to this actor and await the response.
    ///
    /// This will error if the timeout is reached, if the actor is stopped before or during the
    /// request, or if the response sender is otherwise dropped.
    pub async fn request_timeout<Req, Res>(
        &self,
        payload: Req,
        duration: Duration,
    ) -> Result<Res, RequestTimeoutError>
    where
        Request<Req, Res>: Into<A::Msg>,
    {
        let (request, receiver) = Request::new(payload);
        self.sender
            .send(request.into())
            .await
            .map_err(|_| RequestTimeoutError::ActorStopped)?;
        let res = timeout(duration, receiver)
            .await
            .map_err(|_| RequestTimeoutError::Timeout)?
            .map_err(|_| RequestTimeoutError::SenderDropped)?;
        Ok(res)
    }
}

impl<A> Clone for Addr<A>
where
    A: Actor,
{
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            sender: self.sender.clone(),
        }
    }
}

impl<A> Hash for Addr<A>
where
    A: Actor,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write(b"addr:");
        self.id.hash(state)
    }
}

impl<A> PartialEq for Addr<A>
where
    A: Actor,
{
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<A> Eq for Addr<A> where A: Actor {}

#[derive(Debug)]
pub struct SendError;

impl Display for SendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "actor stopped")
    }
}

impl Error for SendError {}

#[async_trait]
trait RecipientSender<M>: 'static + Send + Send + DynClone {
    async fn send_to_recipient(&self, msg: M) -> Result<(), SendError>;
}

dyn_clone::clone_trait_object!(<M> RecipientSender<M>);

#[async_trait]
impl<S, M> RecipientSender<M> for mpsc::Sender<S>
where
    S: 'static + Send,
    M: 'static + Send + Into<S>,
{
    async fn send_to_recipient(&self, msg: M) -> Result<(), SendError> {
        self.send(msg.into()).await.map_err(|_| SendError)
    }
}

impl<A, M> From<Addr<A>> for Recipient<M>
where
    A: Actor,
    M: 'static + Send + Into<A::Msg>,
{
    fn from(addr: Addr<A>) -> Self {
        Self {
            id: addr.id,
            sender: Box::new(addr.sender),
        }
    }
}

pub struct Recipient<M>
where
    M: 'static,
{
    id: Uuid,
    sender: Box<dyn RecipientSender<M> + Send + Sync>,
}

impl<M> Recipient<M> {
    /// Send a message to the recipient.
    ///
    /// This will block (asynchronously) if the recipient's buffer is full
    ///
    /// # Errors
    ///
    /// This will error if the recipient is no longer running.
    pub async fn send(&self, msg: impl Into<M>) -> Result<(), SendError> {
        self.sender.send_to_recipient(msg.into()).await
    }
}

impl<Req, Res> Recipient<Request<Req, Res>> {
    /// Send a [`Request`](crate::Request) to the actor and await the response.
    ///
    /// This could wait indefinitely if the actor never responds, however it will error if the actor
    /// is stopped before or during the request, or if the response sender is otherwise dropped.
    pub async fn request(&self, payload: Req) -> Result<Res, RequestError> {
        let (request, receiver) = Request::new(payload);
        self.sender
            .send_to_recipient(request)
            .await
            .map_err(|_| RequestError::ActorStopped)?;
        let res = receiver.await.map_err(|_| RequestError::SenderDropped)?;
        Ok(res)
    }

    /// Send a [`Request`](crate::Request) to the actor and await the response.
    ///
    /// This will error if the timeout is reached, if the actor is stopped before or during the
    /// request, or if the response sender is otherwise dropped.
    pub async fn request_timeout(
        &self,
        payload: Req,
        duration: Duration,
    ) -> Result<Res, RequestTimeoutError> {
        let (request, receiver) = Request::new(payload);
        self.sender
            .send_to_recipient(request)
            .await
            .map_err(|_| RequestTimeoutError::ActorStopped)?;
        let res = timeout(duration, receiver)
            .await
            .map_err(|_| RequestTimeoutError::Timeout)?
            .map_err(|_| RequestTimeoutError::SenderDropped)?;
        Ok(res)
    }
}

impl<M> Clone for Recipient<M> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            sender: self.sender.clone(),
        }
    }
}

impl<M> Hash for Recipient<M> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write(b"recipient:");
        self.id.hash(state)
    }
}

impl<M> PartialEq for Recipient<M> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl<M> Eq for Recipient<M> {}