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
use crate::{Actor, Caller, Context, Handler, Message, Sender};
use anyhow::Result;
use futures::channel::{mpsc, oneshot};
use futures::lock::Mutex;
use futures::{Future, SinkExt};
use std::pin::Pin;
use std::sync::Arc;

type ExecFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;

pub(crate) type ExecFn<A> = Box<dyn FnOnce(Arc<Mutex<A>>) -> ExecFuture + Send + 'static>;

/// The address of an actor.
///
/// When all references to `Addr<A>` are dropped, the actor ends.
/// You can use `Clone` trait to create multiple copies of `Addr<A>`.
pub struct Addr<A>(pub(crate) mpsc::Sender<ExecFn<A>>);

impl<A> Clone for Addr<A> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<A: Actor> Addr<A> {
    /// Send a message to the actor and wait for the return value.
    pub async fn call<T: Message>(&mut self, msg: T) -> Result<T::Result>
    where
        A: Handler<T>,
    {
        let (tx, rx) = oneshot::channel();
        let ctx = Context { addr: self.clone() };

        self.0
            .send(Box::new(move |actor| {
                Box::pin(async move {
                    let mut actor = actor.lock().await;
                    let res = actor.handle(&ctx, msg).await;
                    let _ = tx.send(res);
                })
            }))
            .await?;

        Ok(rx.await?)
    }

    /// Send a message to the actor without waiting for the return value.
    pub async fn send<T: Message<Result = ()>>(&mut self, msg: T) -> Result<()>
    where
        A: Handler<T>,
    {
        let ctx = Context { addr: self.clone() };
        self.0
            .send(Box::new(move |actor| {
                Box::pin(async move {
                    let mut actor = actor.lock().await;
                    actor.handle(&ctx, msg).await;
                })
            }))
            .await?;
        Ok(())
    }

    /// Create a `Caller<T>` for a specific message type
    pub fn caller<T: Message>(&self) -> Caller<T>
    where
        A: Handler<T>,
    {
        let addr = self.clone();
        Caller(Box::new(move |msg| {
            let mut addr = addr.clone();
            Box::pin(async move { addr.call(msg).await })
        }))
    }

    /// Create a `Sender<T>` for a specific message type
    pub fn sender<T: Message<Result = ()>>(&self) -> Sender<T>
    where
        A: Handler<T>,
    {
        let addr = self.clone();
        Sender(Box::new(move |msg| {
            let mut addr = addr.clone();
            Box::pin(async move { addr.send(msg).await })
        }))
    }
}