crb_actor/
lib.rs

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
pub mod event;
pub mod interrupt;
pub mod message;
pub mod runtime;

pub use event::OnEvent;
pub use runtime::{ActorContext, ActorSession, Standalone};

use anyhow::Error;
use async_trait::async_trait;
use crb_runtime::context::ManagedContext;
use crb_runtime::interruptor::Interruptor;
use std::fmt::Debug;
use std::hash::Hash;

#[async_trait]
pub trait Actor: Sized + Send + 'static {
    type Context: ActorContext<Self>;

    async fn initialize(&mut self, _ctx: &mut Self::Context) -> Result<(), Error> {
        Ok(())
    }

    async fn interrupt(&mut self, ctx: &mut Self::Context) -> Result<(), Error> {
        // Closes the channel
        ctx.session().shutdown();
        Ok(())
    }

    async fn event(&mut self, ctx: &mut Self::Context) -> Result<(), Error> {
        if let Some(envelope) = ctx.session().next_envelope().await {
            envelope.handle(self, ctx).await?;
        } else {
            // Terminates the runtime when the channel has drained
            ctx.session().controller().stop(false)?;
        }
        Ok(())
    }

    async fn finalize(&mut self, _ctx: &mut Self::Context) -> Result<(), Error> {
        Ok(())
    }
}