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
use crate::context::{ActorControlHandle, ActorControlMessage, Context};
use crate::error::TheatreError;
use crate::mailbox::{Addr, Mailbox};
use async_trait::async_trait;
use futures::channel::oneshot;
use futures::SinkExt;
use tokio::task::{JoinError, JoinHandle};

/// Actor is one of the core traits of theatre.
///
/// To create an actor just implement the trait for your struct
///
/// Example:
/// ```rust
/// use theatre::prelude::*;
///
/// struct MyActor;
///
/// impl Actor for MyActor {}
/// ```
///
/// Actor has methods that can be optionally overriden to track actor lifecycle.
///
/// The actor's event loop is shutdown when all addresses to the actor are dropped.
#[async_trait]
pub trait Actor: Send {
    async fn starting(&mut self, _ctx: &mut Context<Self>)
    where
        Self: Sized,
    {
    }

    async fn stopping(&mut self, _ctx: &mut Context<Self>)
    where
        Self: Sized,
    {
    }

    async fn stopped(&mut self, _ctx: &mut Context<Self>)
    where
        Self: Sized,
    {
    }
}

/// ActorHandle is a method of `await`ing the actor's task. Dropping the [ActorHandle] will not
/// shutdown the actor.
///
/// #[ActorHandle](ActorHandle)
#[derive(Debug)]
pub struct ActorHandle {
    ctrl_handle: ActorControlHandle,
    task: JoinHandle<()>,
}

impl ActorHandle {
    pub(crate) fn new(ctrl_handle: ActorControlHandle, task: JoinHandle<()>) -> Self {
        Self { ctrl_handle, task }
    }

    /// Shutdown the actor
    pub fn shutdown(&mut self) -> Result<(), TheatreError> {
        self.ctrl_handle
            .try_send(ActorControlMessage::Shutdown)
            .map_err(|_| TheatreError::SendError)
    }

    /// Calling `join()` will `await` the actor until it has shutdown.
    pub async fn join(self) -> Result<(), JoinError> {
        self.task.await
    }

    /// Send a heartbeat message to the actor. The actor will response as soon as it can.
    /// This method returns true if the actor is still running or false if the actor has shutdown.
    pub async fn heartbeat(&mut self) -> bool {
        let (tx, rx) = oneshot::channel();
        if self
            .ctrl_handle
            .send(ActorControlMessage::Heartbeat(tx))
            .await
            .is_err()
        {
            return false;
        }

        let reply = rx.await;

        reply.is_ok()
    }
}

/// Start an actor in a dedicated task and return its address and handle.
pub async fn start<A>(actor: A) -> (Addr<A>, ActorHandle)
where
    A: 'static + Actor + Sized,
{
    let (addr_tx, addr_rx) = oneshot::channel();
    let task = tokio::spawn(async move {
        let mailbox = Mailbox::new(16);

        let addr = mailbox.new_addr();
        let (mut actor_ctx, handle) = Context::new(mailbox);

        addr_tx.send((addr, handle)).ok().unwrap();

        // Ignore any panics
        let _ = actor_ctx.run(actor).await;
    });

    let (addr, ctrl_handle) = addr_rx.await.unwrap();
    (addr, ActorHandle { ctrl_handle, task })
}

/// Extensions for Actors. This is blanket impl'd on any type that implements `Actor`.
#[async_trait]
pub trait ActorExt {
    /// Start a new actor. Return its address and discard the handle
    async fn spawn(self) -> Addr<Self>
    where
        Self: 'static + Actor + Sized;

    /// Start a new actor. Return its address and handle.
    async fn start(self) -> (Addr<Self>, ActorHandle)
    where
        Self: 'static + Actor + Sized;
}

#[async_trait]
impl<A> ActorExt for A
where
    A: Actor,
{
    async fn spawn(self) -> Addr<Self>
    where
        A: 'static + Actor + Sized,
    {
        start(self).await.0
    }

    async fn start(self) -> (Addr<Self>, ActorHandle)
    where
        Self: 'static + Actor + Sized,
    {
        start(self).await
    }
}

#[cfg(test)]
mod test {
    use super::Actor;
    use futures::channel::oneshot;
    use futures::channel::oneshot::Sender;

    struct A;
    impl Actor for A {}

    #[tokio::test]
    async fn start_actor_and_shutdown() {
        let mut handle = crate::actor::start(A).await.1;
        handle.shutdown().unwrap()
    }

    #[tokio::test]
    async fn start_actor_and_join() {
        let mut handle = crate::actor::start(A).await.1;
        handle.shutdown().unwrap();

        handle.join().await.unwrap()
    }

    #[tokio::test]
    async fn start_with_actor_ext() {
        use super::ActorExt;

        let mut handle = A.start().await.1;
        handle.shutdown().unwrap();
    }

    #[tokio::test]
    async fn spawn_with_actor_ext() {
        use super::ActorExt;

        let _ = A.spawn();
    }

    #[tokio::test]
    async fn actor_starting() {
        use crate::prelude::*;

        let (start, started) = oneshot::channel();

        struct ReplyOnStarting {
            start: Option<Sender<bool>>,
        }

        #[async_trait]
        impl Actor for ReplyOnStarting {
            async fn starting(&mut self, _: &mut Context<Self>) {
                self.start.take().unwrap().send(true).unwrap();
            }
        }

        let _ = ReplyOnStarting { start: Some(start) }.start().await;

        let started = started.await.unwrap();

        assert_eq!(started, true);
    }

    #[tokio::test]
    async fn actor_stopping() {
        use crate::prelude::*;

        let (stop, stopping) = oneshot::channel();

        struct ReplyOnStopping {
            stopping: Option<Sender<bool>>,
        }

        #[async_trait]
        impl Actor for ReplyOnStopping {
            async fn stopping(&mut self, _: &mut Context<Self>) {
                self.stopping.take().unwrap().send(true).unwrap();
            }
        }

        let addr = ReplyOnStopping {
            stopping: Some(stop),
        }
        .start()
        .await;
        drop(addr);

        let stopping = stopping.await.unwrap();

        assert_eq!(stopping, true);
    }

    #[tokio::test]
    async fn actor_stopped() {
        use crate::prelude::*;

        let (stop, stopped) = oneshot::channel();

        struct ReplyOnStopped {
            stopped: Option<Sender<bool>>,
        }

        #[async_trait]
        impl Actor for ReplyOnStopped {
            async fn stopped(&mut self, _: &mut Context<Self>) {
                self.stopped.take().unwrap().send(true).unwrap();
            }
        }

        let addr = ReplyOnStopped {
            stopped: Some(stop),
        }
        .start()
        .await;
        drop(addr);

        let stopped = stopped.await.unwrap();
        assert_eq!(stopped, true);
    }
}