use std::{fmt, future::Future, pin::Pin, sync::Arc, sync::Weak};
use crate::{ActorAddress, DeactivationReason};
use super::core::ServerInner;
use super::session::SessionHandle;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub struct ActorRuntime<S> {
pub(crate) address: ActorAddress,
pub(crate) state: Arc<S>,
pub(crate) runtime: Weak<ServerInner<S>>,
}
impl<S> Clone for ActorRuntime<S> {
fn clone(&self) -> Self {
Self {
address: self.address.clone(),
state: self.state.clone(),
runtime: self.runtime.clone(),
}
}
}
impl<S> fmt::Debug for ActorRuntime<S> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ActorRuntime")
.field("address", &self.address)
.finish_non_exhaustive()
}
}
impl<S: Send + Sync + 'static> ActorRuntime<S> {
pub fn actor_id(&self) -> &str {
self.address.actor_id()
}
pub fn actor_address(&self) -> &ActorAddress {
&self.address
}
pub fn state(&self) -> &S {
&self.state
}
pub async fn broadcast(&self, msg: Vec<u8>) {
let Some(runtime) = self.runtime.upgrade() else {
return;
};
runtime.broadcast_event(&self.address, msg).await;
}
}
pub struct MessageContext {
pub(crate) address: ActorAddress,
pub(crate) session: SessionHandle,
}
impl MessageContext {
pub fn actor_id(&self) -> &str {
self.address.actor_id()
}
pub fn actor_address(&self) -> &ActorAddress {
&self.address
}
pub fn session(&self) -> &SessionHandle {
&self.session
}
pub async fn send(&self, msg: Vec<u8>) -> Result<(), crate::SendError> {
self.session.send(msg).await
}
}
#[allow(async_fn_in_trait)]
pub trait Actor<S>: Send + 'static {
fn new(runtime: ActorRuntime<S>) -> Self;
async fn on_message(&mut self, ctx: &MessageContext, msg: &[u8]);
async fn on_activate(&mut self) -> Result<(), String> {
Ok(())
}
async fn on_deactivate(&mut self, _reason: DeactivationReason) {}
async fn on_session_opened(&mut self, _ctx: &MessageContext) {}
async fn on_session_closed(&mut self, _ctx: &MessageContext) {}
}
pub enum MessageOutcome {
Completed,
Panicked,
}
pub trait ErasedActor: Send + 'static {
fn activate<'a>(actor: &'a mut (dyn std::any::Any + Send))
-> BoxFuture<'a, Result<(), String>>;
fn deactivate<'a>(
actor: &'a mut (dyn std::any::Any + Send),
reason: DeactivationReason,
) -> BoxFuture<'a, ()>;
fn handle<'a>(
actor: &'a mut (dyn std::any::Any + Send),
ctx: &'a MessageContext,
payload: &'a [u8],
) -> BoxFuture<'a, MessageOutcome>;
fn session_opened<'a>(
actor: &'a mut (dyn std::any::Any + Send),
ctx: &'a MessageContext,
) -> BoxFuture<'a, ()>;
fn session_closed<'a>(
actor: &'a mut (dyn std::any::Any + Send),
ctx: &'a MessageContext,
) -> BoxFuture<'a, ()>;
}
pub trait ActorType<S>: ErasedActor + Send + 'static {
fn create(runtime: ActorRuntime<S>) -> Self;
}