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
346
347
348
349
350
351
352
353
354
355
356
357
use futures::Future;
use std::fmt;
use std::marker::PhantomData;

mod envelope;
mod message;
mod queue;

mod sync;
pub(crate) mod sync_channel;

mod unsync;
mod unsync_channel;

use actor::{Actor, AsyncContext};
use handler::{Handler, Message};

pub use self::envelope::{EnvelopeProxy, MessageEnvelope, SyncEnvelope,
                         SyncMessageEnvelope, ToEnvelope, UnsyncEnvelope};
pub use self::message::Request;

pub use self::sync::{Syn, SyncRecipientRequest};
pub(crate) use self::sync_channel::SyncAddressReceiver;
pub use self::unsync::{Unsync, UnsyncRecipientRequest};
pub(crate) use self::unsync_channel::UnsyncAddrReceiver;

pub enum SendError<T> {
    Full(T),
    Closed(T),
}

#[derive(Fail)]
/// Set of error that can occurred during message delivery process
pub enum MailboxError {
    #[fail(display = "Mailbox has closed")]
    Closed,
    #[fail(display = "Message delivery timed out")]
    Timeout,
}

impl<T> SendError<T> {
    pub fn into_inner(self) -> T {
        match self {
            SendError::Full(msg) | SendError::Closed(msg) => msg,
        }
    }
}

impl<T> fmt::Debug for SendError<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SendError::Full(_) => write!(fmt, "SendError::Full(..)"),
            SendError::Closed(_) => write!(fmt, "SendError::Closed(..)"),
        }
    }
}

impl<T> fmt::Display for SendError<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SendError::Full(_) => write!(fmt, "send failed because receiver is full"),
            SendError::Closed(_) => write!(fmt, "send failed because receiver is gone"),
        }
    }
}

impl fmt::Debug for MailboxError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "MailboxError({})", self)
    }
}

/// Trait give access to actor's address
pub trait ActorAddress<A, T>
where
    A: Actor,
{
    /// Returns actor's address for specific context
    fn get(ctx: &mut A::Context) -> T;
}

impl<A> ActorAddress<A, Addr<Unsync, A>> for A
where
    A: Actor,
    A::Context: AsyncContext<A>,
{
    fn get(ctx: &mut A::Context) -> Addr<Unsync, A> {
        ctx.unsync_address()
    }
}

impl<A> ActorAddress<A, Addr<Syn, A>> for A
where
    A: Actor,
    A::Context: AsyncContext<A>,
{
    fn get(ctx: &mut A::Context) -> Addr<Syn, A> {
        ctx.sync_address()
    }
}

impl<A> ActorAddress<A, (Addr<Unsync, A>, Addr<Syn, A>)> for A
where
    A: Actor,
    A::Context: AsyncContext<A>,
{
    fn get(ctx: &mut A::Context) -> (Addr<Unsync, A>, Addr<Syn, A>) {
        (ctx.unsync_address(), ctx.sync_address())
    }
}

impl<A> ActorAddress<A, ()> for A
where
    A: Actor,
{
    fn get(_: &mut A::Context) -> () {
        ()
    }
}

pub trait Destination<A>: Sized {
    type Transport: Clone;

    /// Indicates if destination is still alive
    fn connected(tx: &Self::Transport) -> bool;
}

#[allow(unused_variables)]
pub trait MessageDestination<A, M>: Destination<A>
where
    A: Handler<M>,
    A::Context: ToEnvelope<Self, A, M>,
    M: Message + 'static,
    Self::Transport: MessageDestinationTransport<Self, A, M>,
{
    type Envelope;
    type ResultSender;
    type ResultReceiver: Future<Item = M::Result>;

    /// Send message unconditionally
    fn do_send(tx: &Self::Transport, msg: M);

    /// Try send message
    fn try_send(tx: &Self::Transport, msg: M) -> Result<(), SendError<M>>;

    /// Send asynchronous message and wait for response.
    fn send(tx: &Self::Transport, msg: M) -> Request<Self, A, M>;

    /// Get recipient for specific message type.
    fn recipient(tx: <Self as Destination<A>>::Transport) -> Recipient<Self, M>
    where
        Self: MessageRecipient<M>;
}

pub trait MessageDestinationTransport<T: MessageDestination<A, M>, A, M>
where
    M: Message + 'static,
    A: Handler<M>,
    A::Context: ToEnvelope<T, A, M>,
    T::Transport: MessageDestinationTransport<T, A, M>,
{
    fn send(&self, msg: M) -> Result<T::ResultReceiver, SendError<M>>;
}

#[allow(unused_variables)]
pub trait MessageRecipient<M>: Sized
where
    M: Message + 'static,
{
    type Envelope: From<M>;
    type Transport;

    type SendError;
    type MailboxError;
    type Request: Future<Item = M::Result, Error = Self::MailboxError>;

    /// Send message unconditionally
    ///
    /// Deliver message even if recipient's mailbox is full
    fn do_send(tx: &Self::Transport, msg: M) -> Result<(), Self::SendError>;

    /// Try send message
    ///
    /// This method fails if actor's mailbox is full or closed. This method
    /// register current task in receivers queue.
    fn try_send(tx: &Self::Transport, msg: M) -> Result<(), Self::SendError>;

    /// Send asynchronous message and wait for response.
    ///
    /// Communication channel to the actor is bounded. if returned `Receiver`
    /// object get dropped, message cancels.
    fn send(tx: &Self::Transport, msg: M) -> Self::Request;

    /// Clone transport
    fn clone(tx: &Self::Transport) -> Self::Transport;
}

/// Address of the actor
pub struct Addr<T: Destination<A>, A> {
    tx: T::Transport,
    act: PhantomData<A>,
}

unsafe impl<A: Actor> Send for Addr<Syn, A> {}
unsafe impl<A: Actor> Sync for Addr<Syn, A> {}

impl<T: Destination<A>, A> Addr<T, A> {
    pub fn new(tx: T::Transport) -> Addr<T, A> {
        Addr {
            tx,
            act: PhantomData,
        }
    }

    /// Indicates if actor is still alive
    pub fn connected(&self) -> bool {
        T::connected(&self.tx)
    }

    /// Send message unconditionally
    ///
    /// This method ignores actor's mailbox capacity, it silently fails if
    /// mailbox is closed.
    pub fn do_send<M>(&self, msg: M)
    where
        T: MessageDestination<A, M>,
        T::Transport: MessageDestinationTransport<T, A, M>,
        M: Message + 'static,
        A: Handler<M>,
        A::Context: ToEnvelope<T, A, M>,
    {
        T::do_send(&self.tx, msg)
    }

    /// Send asynchronous message and wait for response.
    ///
    /// Communication channel to the actor is bounded. if returned `Future`
    /// object get dropped, message cancels.
    pub fn send<M>(&self, msg: M) -> Request<T, A, M>
    where
        T: MessageDestination<A, M>,
        T::Transport: MessageDestinationTransport<T, A, M>,
        M: Message + 'static,
        A: Handler<M>,
        A::Context: ToEnvelope<T, A, M>,
    {
        T::send(&self.tx, msg)
    }

    /// Try to send message
    ///
    /// This method fails if actor's mailbox is full or closed. This method
    /// register current task in receivers queue.
    pub fn try_send<M>(&self, msg: M) -> Result<(), SendError<M>>
    where
        T: MessageDestination<A, M>,
        T::Transport: MessageDestinationTransport<T, A, M>,
        M: Message + 'static,
        A: Handler<M>,
        A::Context: ToEnvelope<T, A, M>,
    {
        T::try_send(&self.tx, msg)
    }

    /// Get `Recipient` for specific message type
    pub fn recipient<M>(self) -> Recipient<T, M>
    where
        T: MessageDestination<A, M> + MessageRecipient<M>,
        A: Handler<M>,
        A::Context: ToEnvelope<T, A, M>,
        <T as Destination<A>>::Transport: MessageDestinationTransport<T, A, M>,
        M: Message + 'static,
    {
        T::recipient(self.tx)
    }
}

impl<T: Destination<A>, A> Clone for Addr<T, A> {
    fn clone(&self) -> Addr<T, A> {
        Addr {
            tx: self.tx.clone(),
            act: PhantomData,
        }
    }
}

/// `Recipient` type allows to send one specific message to an actor.
///
/// You can get recipient with `Addr<_, _>::recipient()` method.
/// It is possible to use `Clone::clone()` method to get cloned recipient.
pub struct Recipient<T: MessageRecipient<M>, M: Message + 'static> {
    tx: T::Transport,
    msg: PhantomData<M>,
}

unsafe impl<M> Send for Recipient<Syn, M>
where
    M: Message + Send + 'static,
    M::Result: Send,
{
}
unsafe impl<M> Sync for Recipient<Syn, M>
where
    M: Message + Send + 'static,
    M::Result: Send,
{
}

impl<T, M> Recipient<T, M>
where
    T: MessageRecipient<M>,
    M: Message + 'static,
{
    /// Create new recipient
    pub fn new(tx: T::Transport) -> Recipient<T, M> {
        Recipient {
            tx,
            msg: PhantomData,
        }
    }

    /// Send message
    ///
    /// Deliver message even if recipient's mailbox is full
    pub fn do_send(&self, msg: M) -> Result<(), T::SendError> {
        T::do_send(&self.tx, msg)
    }

    /// Try send message
    ///
    /// This method fails if recipient's mailbox is full or closed. This method
    /// register current task in receivers queue.
    pub fn try_send(&self, msg: M) -> Result<(), T::SendError> {
        T::try_send(&self.tx, msg)
    }

    /// Send message and asynchronously wait for response.
    ///
    /// Communication channel to the actor is bounded. if returned `Request`
    /// object get dropped, message cancels.
    pub fn send(&self, msg: M) -> T::Request {
        T::send(&self.tx, msg)
    }
}

impl<T, M> Clone for Recipient<T, M>
where
    T: MessageRecipient<M>,
    M: Message + 'static,
{
    fn clone(&self) -> Recipient<T, M> {
        Recipient {
            tx: T::clone(&self.tx),
            msg: PhantomData,
        }
    }
}