Skip to main content

compio_actor/actor/
mod.rs

1//! Actor definitions, lifecycle results, and handles.
2
3mod deliver;
4mod handle;
5
6pub(crate) use deliver::{Delivering, finish, run};
7#[doc(inline)]
8pub use handle::{ActorExit, ActorHandle, ActorHandleError};
9
10use crate::Mailbox;
11
12/// A message that can cross into an actor cluster.
13pub trait Message: Send + 'static {}
14
15impl<T: Send + 'static> Message for T {}
16
17/// A single-threaded actor with serial access to its state.
18#[allow(async_fn_in_trait)]
19pub trait Actor: Sized + 'static {
20    /// State owned by the actor task.
21    type State: 'static;
22    /// Values moved to the worker to initialize the actor.
23    type Arguments: Send + 'static;
24    /// Errors reported across the cluster.
25    type Error: Send + 'static;
26
27    /// Initializes state on the actor's worker.
28    async fn pre_start(
29        &self,
30        myself: &Mailbox<Self>,
31        arguments: Self::Arguments,
32    ) -> Result<Self::State, Self::Error>;
33
34    /// Runs inside the actor task before it receives messages.
35    async fn post_start(
36        &self,
37        _myself: &Mailbox<Self>,
38        _state: &mut Self::State,
39    ) -> Result<(), Self::Error> {
40        Ok(())
41    }
42
43    /// Runs after message processing ends but before the mailbox is dropped.
44    async fn pre_stop(
45        &self,
46        _myself: &Mailbox<Self>,
47        _state: &mut Self::State,
48    ) -> Result<(), Self::Error> {
49        Ok(())
50    }
51
52    /// Runs after the mailbox has closed.
53    async fn post_stop(
54        &self,
55        _myself: &Mailbox<Self>,
56        _state: &mut Self::State,
57    ) -> Result<(), Self::Error> {
58        Ok(())
59    }
60}
61
62/// Handles messages of type `M` for an actor.
63#[allow(async_fn_in_trait)]
64pub trait Handler<M: Message>: Actor {
65    /// Handles one message at a time.
66    async fn handle(
67        &self,
68        myself: &Mailbox<Self>,
69        message: M,
70        state: &mut Self::State,
71    ) -> Result<(), Self::Error>;
72}