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
pub(crate) mod handler; pub mod runner; use thiserror::Error; use async_trait::async_trait; use uuid::Uuid; use crate::system::{ActorSystem, SystemEvent}; pub struct ActorContext<E: SystemEvent> { pub id: Uuid, pub system: ActorSystem<E> } pub trait Message: Clone + Send + Sync + 'static { type Response: std::fmt::Debug + Send + Sync + 'static; } #[async_trait] pub trait Handler<M: Message, E: SystemEvent>: Send + Sync { async fn handle(&mut self, msg: M, ctx: &mut ActorContext<E>) -> M::Response; } pub trait Actor: Clone + Send + Sync + 'static {} #[derive(Clone)] pub struct ActorRef<A: Actor, E: SystemEvent> { id: Uuid, sender: handler::HandlerRef<A, E> } impl<A: Actor, E: SystemEvent> ActorRef<A, E> { pub fn get_id(&self) -> &Uuid { &self.id } pub fn tell<M>(&mut self, msg: M) -> Result<(), ActorError> where M: Message, A: Handler<M, E> { self.sender.tell(msg) } pub async fn ask<M>(&mut self, msg: M) -> Result<M::Response, ActorError> where M: Message, A: Handler<M, E> { self.sender.ask(msg).await } pub(crate) fn get_any(&self) -> AnyActorRef { AnyActorRef { id: self.id, sender: self.sender.clone().into() } } pub fn new(id: Uuid, sender: handler::MailboxSender<A, E>) -> Self { let handler = handler::HandlerRef::new(sender); ActorRef { id, sender: handler } } } #[derive(Clone)] pub(crate) struct AnyActorRef { id: Uuid, sender: handler::AnyHandlerRef } impl AnyActorRef { pub fn get_ref<A: Actor, E: SystemEvent>(&self) -> ActorRef<A, E> { let handler: handler::HandlerRef<A, E> = self.sender.clone().into(); ActorRef { id: self.id, sender: handler } } } #[derive(Error, Debug)] pub enum ActorError { #[error("Actor runtime error")] Runtime(String) }