crb_actor/
actor.rs

1use crate::runtime::{ActorContext, DoActor};
2use anyhow::Result;
3use async_trait::async_trait;
4use crb_runtime::kit::{Context, InteractiveTask, ManagedContext};
5
6#[async_trait]
7pub trait Actor: Sized + Send + 'static {
8    type Context: ActorContext<Self>;
9
10    async fn initialize(&mut self, _ctx: &mut Self::Context) -> Result<()> {
11        Ok(())
12    }
13
14    async fn interrupt(&mut self, ctx: &mut Self::Context) -> Result<()> {
15        // Closes the channel
16        ctx.session().shutdown();
17        Ok(())
18    }
19
20    async fn event(&mut self, ctx: &mut Self::Context) -> Result<()> {
21        let envelope = ctx.session().joint().next_envelope();
22        if let Some(envelope) = envelope.await {
23            envelope.handle(self, ctx).await?;
24        } else {
25            // Terminates the runtime when the channel has drained
26            ctx.session().controller().stop(false)?;
27        }
28        Ok(())
29    }
30
31    async fn finalize(&mut self, _ctx: &mut Self::Context) -> Result<()> {
32        Ok(())
33    }
34}
35
36pub trait Standalone: Actor {
37    fn spawn(self) -> <Self::Context as Context>::Address
38    where
39        Self::Context: Default,
40    {
41        DoActor::new(self).spawn_connected()
42    }
43
44    // TODO: spawn_with_context()
45}