use maiko::*;
#[derive(Event, SelfRouting, Clone, Debug, Hash, PartialEq, Eq)]
enum PingPongEvent {
Ping,
Pong,
}
struct PingPong {
ctx: Context<PingPongEvent>,
}
impl Actor for PingPong {
type Event = PingPongEvent;
async fn handle_event(&mut self, envelope: &Envelope<Self::Event>) -> Result {
println!(
"Event: {:?} received by {} actor",
envelope.event(),
self.ctx.actor_name()
);
let response = match envelope.event() {
PingPongEvent::Ping => PingPongEvent::Pong,
PingPongEvent::Pong => PingPongEvent::Ping,
};
self.ctx.send(response).await
}
}
struct Counter {
count: u32,
}
impl Actor for Counter {
type Event = PingPongEvent;
async fn handle_event(&mut self, _envelope: &Envelope<Self::Event>) -> Result {
self.count += 1;
Ok(())
}
async fn on_shutdown(&mut self) -> Result {
println!("Total events processed: {}", self.count);
Ok(())
}
}
#[tokio::main]
pub async fn main() -> Result {
let mut sup = Supervisor::<PingPongEvent, PingPongEvent>::default();
sup.add_actor("Ping", |ctx| PingPong { ctx }, [PingPongEvent::Pong])?;
sup.add_actor("Pong", |ctx| PingPong { ctx }, [PingPongEvent::Ping])?;
sup.add_actor(
"Counter",
|_ctx| Counter { count: 0 },
&[PingPongEvent::Ping, PingPongEvent::Pong],
)?;
sup.start().await?;
sup.send(PingPongEvent::Ping).await?;
tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;
sup.stop().await?;
println!("Done");
Ok(())
}