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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! Xtra is a tiny, fast, and safe actor system.

#![cfg_attr(
    feature = "nightly",
    feature(
        generic_associated_types,
        specialization,
        type_alias_impl_trait,
        doc_cfg,
    )
)]
#![cfg_attr(doc, feature(doc_cfg, external_doc))]
#![deny(missing_docs, unsafe_code)]

mod message_channel;
pub use message_channel::{MessageChannel, MessageChannelExt, WeakMessageChannel};

mod envelope;

mod address;
pub use address::{Address, AddressExt, Disconnected, MessageResponseFuture, WeakAddress};

mod context;
pub use context::Context;

mod manager;
pub use manager::ActorManager;

/// Commonly used types from `xtra`
pub mod prelude {
    pub use crate::address::{Address, AddressExt};
    pub use crate::message_channel::{MessageChannel, MessageChannelExt};
    pub use crate::{Actor, Context, Handler, Message, SyncHandler};
}

#[cfg(feature = "nightly")]
use futures::future::{self, Ready};

/// A message that can be sent to an [`Actor`](trait.Actor.html) for processing. They are processed
/// one at a time. Only actors implementing the corresponding [`Handler<M>`](trait.Handler.html)
/// trait can be sent a given message.
///
/// # Example
///
/// ```no_run
/// # use xtra::Message;
/// struct MyResult;
/// struct MyMessage;
///
/// impl Message for MyMessage {
///     type Result = MyResult;
/// }
/// ```
pub trait Message: Send + 'static {
    /// The return type of the message. It will be returned when the [`Address::send`](struct.Address.html#method.send)
    /// method is called.
    type Result: Send;
}

/// A trait indicating that an [`Actor`](trait.Actor.html) can handle a given [`Message`](trait.Message.html)
/// synchronously, and the logic to handle the message. A `SyncHandler` implementation automatically
/// creates a corresponding [`Handler`](trait.Handler.html) impl. This, however, is not just sugar
/// over the asynchronous  [`Handler`](trait.Handler.html) trait -- it is also slightly faster than
/// it for handling due to how they get specialized under the hood.
///
/// # Example
///
/// ```
/// # use xtra::prelude::*;
/// # struct MyActor;
/// # impl Actor for MyActor {}
/// struct Msg;
///
/// impl Message for Msg {
///     type Result = u32;
/// }
///
/// impl SyncHandler<Msg> for MyActor {
///     fn handle(&mut self, message: Msg, ctx: &mut Context<Self>) -> u32 {
///         20
///     }
/// }
///
/// #[smol_potat::main]
/// async fn main() {
///     let addr = MyActor.spawn();
///     assert_eq!(addr.send(Msg).await, Ok(20));
/// }
/// ```
pub trait SyncHandler<M: Message>: Actor {
    /// Handle a given message, returning its result.
    fn handle(&mut self, message: M, ctx: &mut Context<Self>) -> M::Result;
}

/// A trait indicating that an [`Actor`](trait.Actor.html) can handle a given [`Message`](trait.Message.html)
/// asynchronously, and the logic to handle the message. If the message should be handled synchronously,
/// then the [`SyncHandler`](trait.SyncHandler.html) trait should rather be implemented.
///
/// Without the `nightly` feature enabled, this is an [`async_trait`](https://github.com/dtolnay/async-trait/),
/// so implementations should be annotated `#[async_trait]`.
///
/// # Example
///
/// ```
/// # use xtra::prelude::*;
/// # struct MyActor;
/// # impl Actor for MyActor {}
/// struct Msg;
///
/// impl Message for Msg {
///     type Result = u32;
/// }
///
/// #[async_trait::async_trait]
/// impl Handler<Msg> for MyActor {
///     async fn handle(&mut self, message: Msg, ctx: &mut Context<Self>) -> u32 {
///         20
///     }
/// }
///
/// #[smol_potat::main]
/// async fn main() {
///     let addr = MyActor.spawn();
///     assert_eq!(addr.send(Msg).await, Ok(20));
/// }
/// ```
#[cfg(not(feature = "nightly"))]
#[async_trait::async_trait]
pub trait Handler<M: Message>: Actor {
    /// Handle a given message, returning its result.
    ///
    /// Without the `nightly` feature enabled, this is an [`async_trait`](https://github.com/dtolnay/async-trait/).
    /// See the trait documentation to see an example of how this method can be declared.
    async fn handle(&mut self, message: M, ctx: &mut Context<Self>) -> M::Result;
}

/// A trait indicating that an [`Actor`](trait.Actor.html) can handle a given [`Message`](trait.Message.html)
/// asynchronously, and the logic to handle the message. If the message should be handled synchronously,
/// then the [`SyncHandler`](trait.SyncHandler.html) trait should rather be implemented.
///
/// For an example, see `examples/nightly.rs`.
#[cfg(feature = "nightly")]
pub trait Handler<M: Message>: Actor {
    /// The responding future of the asynchronous actor. This should probably look like:
    /// ```not_a_test
    /// type Responder<'a>: Future<Output = M::Result> + Send
    /// ```
    type Responder<'a>: Future<Output = M::Result> + Send;

    /// Handle a given message, returning a future eventually resolving to its result. The signature
    /// of this function should probably look like:
    /// ```not_a_test
    /// fn handle(&mut self, message: M, ctx: &mut Context<Self>) -> Self::Responder<'_>
    /// ```
    /// or:
    /// ```not_a_test
    /// fn handle<'a>(&'a mut self, message: M, ctx: &'a mut Context<Self>) -> Self::Responder<'a>
    /// ```
    fn handle<'a>(&'a mut self, message: M, ctx: &'a mut Context<Self>) -> Self::Responder<'a>;
}

#[async_trait::async_trait]
impl<M: Message, T: SyncHandler<M>> Handler<M> for T {
    #[cfg(not(feature = "nightly"))]
    async fn handle(&mut self, message: M, ctx: &mut Context<Self>) -> M::Result {
        let res: M::Result = SyncHandler::handle(self, message, ctx);
        res
    }

    #[cfg(feature = "nightly")]
    type Responder<'a> = Ready<M::Result>;

    #[cfg(feature = "nightly")]
    fn handle(&mut self, message: M, ctx: &mut Context<Self>) -> Self::Responder<'_> {
        let res: M::Result = SyncHandler::handle(self, message, ctx);
        future::ready(res)
    }
}

/// An actor which can handle [`Message`s](trait.Message.html) one at a time. Actors can only be
/// communicated with by sending [`Message`s](trait.Message.html) through their [`Address`es](struct.Address.html).
/// They can modify their private state, respond to messages, and spawn other actors. They can also
/// stop themselves through their [`Context`](struct.Context.html) by calling [`Context::stop`](struct.Context.html#method.stop).
/// This will result in any attempt to send messages to the actor in future failing.
///
/// # Example
///
/// ```rust
/// # use xtra::{KeepRunning, prelude::*};
/// # use std::time::Duration;
/// # use smol::Timer;
/// struct MyActor;
///
/// impl Actor for MyActor {
///     fn started(&mut self, ctx: &mut Context<Self>) {
///         println!("Started!");
///     }
///
///     fn stopping(&mut self, ctx: &mut Context<Self>) -> KeepRunning {
///         println!("Decided not to keep running");
///         KeepRunning::No
///     }
///
///     fn stopped(&mut self, ctx: &mut Context<Self>) {
///         println!("Finally stopping.");
///     }
/// }
///
/// struct Goodbye;
///
/// impl Message for Goodbye {
///     type Result = ();
/// }
///
/// impl SyncHandler<Goodbye> for MyActor {
///     fn handle(&mut self, _: Goodbye, ctx: &mut Context<Self>) {
///         println!("Goodbye!");
///         ctx.stop();
///     }
/// }
///
/// // Will print "Started!", "Goodbye!", "Decided not to keep running", and then "Finally stopping."
/// #[smol_potat::main]
/// async fn main() {
///     let addr = MyActor.spawn();
///     addr.send(Goodbye).await;
///
///     Timer::after(Duration::from_secs(1)).await; // Give it time to run
/// }
/// ```
///
/// For longer examples, see the `examples` directory.
pub trait Actor: 'static + Send + Sized {
    /// Called as soon as the actor has been started.
    #[allow(unused_variables)]
    fn started(&mut self, ctx: &mut Context<Self>) {}

    /// Called when the actor calls the [`Context::stop`](struct.Context.html#method.stop). This method
    /// can prevent the actor from stopping by returning [`KeepRunning::Yes`](enum.KeepRunning.html#variant.Yes).
    ///
    /// **Note:** this method will *only* be called when `Context::stop` is called. Other, general
    /// destructor behaviour should be encapsulated in the [`Actor::stopped`](trait.Actor.html#method.stopped)
    /// method.
    ///
    /// # Example
    /// ```no_run
    /// # use xtra::prelude::*;
    /// # use xtra::KeepRunning;
    /// # struct MyActor { is_running: bool };
    /// # impl Actor for MyActor {
    /// fn stopping(&mut self, ctx: &mut Context<Self>) -> KeepRunning {
    ///     self.is_running.into() // bool can be converted to KeepRunning with Into
    /// }
    /// # }
    /// ```
    #[allow(unused_variables)]
    fn stopping(&mut self, ctx: &mut Context<Self>) -> KeepRunning {
        KeepRunning::No
    }

    /// Called when the actor is in the process of stopping. This could be because
    /// [`KeepRunning::No`](enum.KeepRunning.html#variant.No) was returned from the
    /// [`Actor::stopping`](trait.Actor.html#method.stopping) method, or because there are no more
    /// strong addresses ([`Address`](struct.Address.html), as opposed to [`WeakAddress`](struct.WeakAddress.html).
    /// This should be used for any final cleanup before the actor is dropped.
    #[allow(unused_variables)]
    fn stopped(&mut self, ctx: &mut Context<Self>) {}

    /// Spawns the actor onto the global runtime executor (i.e, `tokio` or `async_std`'s executors).
    ///
    /// # Example
    ///
    /// ```rust
    /// # use xtra::{KeepRunning, prelude::*};
    /// # use std::time::Duration;
    /// # use smol::Timer;
    /// struct MyActor;
    ///
    /// impl Actor for MyActor {
    ///     fn started(&mut self, ctx: &mut Context<Self>) {
    ///         println!("Started!");
    ///     }
    /// }
    ///
    /// # struct Msg;
    /// # impl Message for Msg {
    /// #    type Result = ();
    /// # }
    /// # impl SyncHandler<Msg> for MyActor {
    /// #     fn handle(&mut self, _: Msg, _ctx: &mut Context<Self>) {}
    /// # }
    ///
    /// #[smol_potat::main]
    /// async fn main() {
    ///     let addr: Address<MyActor> = MyActor.spawn(); // Will print "Started!"
    ///     addr.do_send(Msg).unwrap();
    ///
    ///     Timer::after(Duration::from_secs(1)).await; // Give it time to run
    /// }
    /// ```
    #[cfg(any(
        doc,
        feature = "with-tokio-0_2",
        feature = "with-async_std-1",
        feature = "with-wasm_bindgen-0_2",
        feature = "with-smol-0_1"
    ))]
    #[cfg_attr(doc, doc(cfg(feature = "with-tokio-0_2")))]
    #[cfg_attr(doc, doc(cfg(feature = "with-async_std-1")))]
    #[cfg_attr(doc, doc(cfg(feature = "with-wasm_bindgen-0_2")))]
    #[cfg_attr(doc, doc(cfg(feature = "with-smol-0_1")))]
    fn spawn(self) -> Address<Self>
    where
        Self: Send,
    {
        let (addr, mgr) = ActorManager::start(self);

        #[cfg(feature = "with-tokio-0_2")]
        tokio::spawn(mgr.manage());

        #[cfg(feature = "with-async_std-1")]
        async_std::task::spawn(mgr.manage());

        #[cfg(feature = "with-wasm_bindgen-0_2")]
        wasm_bindgen_futures::spawn_local(mgr.manage());

        #[cfg(feature = "with-smol-0_1")]
        smol::Task::spawn(mgr.manage()).detach();

        addr
    }

    /// Returns the actor's address and manager in a ready-to-start state. To spawn the actor, the
    /// [`ActorManager::manage`](struct.ActorManager.html#method.manage) method must be called and
    /// the future it returns spawned onto an executor.
    /// # Example
    ///
    /// ```rust
    /// # use xtra::{KeepRunning, prelude::*};
    /// # use std::time::Duration;
    /// # use smol::Timer;
    /// # struct MyActor;
    /// # impl Actor for MyActor {}
    /// #[smol_potat::main]
    /// async fn main() {
    ///     let (addr, mgr) = MyActor.create();
    ///     smol::Task::spawn(mgr.manage()).detach(); // Actually spawn the actor onto an executor
    ///
    ///     Timer::after(Duration::from_secs(1)).await; // Give it time to run
    /// }
    /// ```
    fn create(self) -> (Address<Self>, ActorManager<Self>) {
        ActorManager::start(self)
    }
}

/// Whether to keep the actor running after it has been put into a stopping state.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum KeepRunning {
    /// Keep the actor running and prevent it from being stopped
    Yes,
    /// Stop the actor
    No,
}

impl From<bool> for KeepRunning {
    fn from(b: bool) -> Self {
        if b {
            KeepRunning::Yes
        } else {
            KeepRunning::No
        }
    }
}

impl Into<bool> for KeepRunning {
    fn into(self) -> bool {
        match self {
            KeepRunning::Yes => true,
            KeepRunning::No => false,
        }
    }
}

impl From<()> for KeepRunning {
    fn from(_: ()) -> KeepRunning {
        KeepRunning::Yes
    }
}