use crate::async_actor::AsyncActor;
use crate::core::{ActorContext, ActorCore, ActorHandle, CancelToken};
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::{broadcast, mpsc, oneshot};
use tokio::time::Duration;
use tracing::{debug, warn};
pub struct ActorManager<A: AsyncActor, const E: usize = 256> {
actors: HashMap<usize, ActorHandle<A>>,
next_id: AtomicUsize,
state: ManagerState<A::State>,
progress: ManagerProgress<A::Progress>,
listeners: HashMap<usize, CancelListeners>,
update_interval: Duration,
}
impl<A: AsyncActor, const E: usize> Default for ActorManager<A, E> {
fn default() -> Self {
Self::new()
}
}
impl<A: AsyncActor, const E: usize> ActorManager<A, E> {
pub fn new() -> Self {
Self {
actors: HashMap::new(),
next_id: AtomicUsize::new(1),
state: ManagerState {
actors: HashMap::new(),
},
progress: ManagerProgress {
actors: HashMap::new(),
},
listeners: HashMap::new(),
update_interval: Duration::from_millis(500),
}
}
pub fn set_update_interval(&mut self, interval: Duration) {
self.update_interval = interval;
}
fn get_id(&self) -> usize {
self.next_id.fetch_add(1, Ordering::SeqCst)
}
fn spawn_actor(
&mut self,
actor: A,
update_tx: mpsc::Sender<Update>,
event_tx: broadcast::Sender<ManagerEvent<A::Event>>,
) -> usize {
let id = self.get_id();
let handle = actor.spawn();
let progress = Self::listen_progress(&handle, id, update_tx.clone());
let state = Self::listen_state(&handle, id, update_tx);
let events = Self::listen_events(&handle, id, event_tx);
self.actors.insert(id, handle);
self.listeners.insert(
id,
CancelListeners {
state,
progress,
events,
},
);
id
}
fn stop_actor(&mut self, id: usize) {
if let Some(handle) = self.actors.remove(&id) {
handle.stop();
};
self.state.actors.remove(&id);
self.progress.actors.remove(&id);
if let Some(listeners) = self.listeners.remove(&id) {
listeners.stop_all();
}
}
fn listen_state(
handle: &ActorHandle<A>,
id: usize,
update_tx: mpsc::Sender<Update>,
) -> CancelToken {
handle.state_listen_async(move |_| {
let state_tx = update_tx.clone();
async move {
let _ = state_tx.send(Update::State(id)).await;
}
})
}
fn listen_progress(
handle: &ActorHandle<A>,
id: usize,
update_tx: mpsc::Sender<Update>,
) -> CancelToken {
handle.progress_listen_async(move |_| {
let progress_tx = update_tx.clone();
async move {
let _ = progress_tx.send(Update::Progress(id)).await;
}
})
}
fn listen_events(
handle: &ActorHandle<A>,
id: usize,
event_tx: broadcast::Sender<ManagerEvent<A::Event>>,
) -> CancelToken {
handle.events_listen_async(move |event| {
let events_tx = event_tx.clone();
async move {
let _ = events_tx.send(ManagerEvent::ChildEvent { id, event });
}
})
}
}
impl<A: AsyncActor, const E: usize> ActorCore for ActorManager<A, E> {
type Cmd = ManagerCmd<A>;
type State = ManagerState<A::State>;
type Progress = ManagerProgress<A::Progress>;
type Event = ManagerEvent<A::Event>;
const EVENT_CAPACITY: usize = E;
fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
(self.state.clone(), self.progress.clone())
}
}
impl<A: AsyncActor, const E: usize> AsyncActor for ActorManager<A, E> {
fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
let mut context = context;
let mut manager = self;
let cancel = context.cancel_clone();
async move {
let (update_tx, mut update_rx) = mpsc::channel::<Update>(256);
let mut push_interval = tokio::time::interval(manager.update_interval);
push_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = cancel.cancelled() => { debug!("Manager 被 cancel 了!");break},
Some(cmd) = context.wait_for_cmd() => {
match cmd {
ManagerCmd::SpawnActor{actor, id_tx} => {
let id = manager.spawn_actor(actor, update_tx.clone(), context.get_events_clone());
if let Some(tx) = id_tx{
let _ = tx.send(id);
}
context.send_event(ManagerEvent::Spawned { id });
}
ManagerCmd::StopActor(id) => {
manager.stop_actor(id);
context.update_state(manager.state.clone());
context.update_progress(manager.progress.clone());
context.send_event(ManagerEvent::Stopped { id });
}
ManagerCmd::Forward { id, cmd } => {
match manager.actors.get(&id) {
Some(handle) => {
if handle.send_cmd(cmd).is_err() {
warn!("子Actor已经停止了: id={id}");
}
}
None => warn!("没有找到id对应的子Actor: id={id}"),
}
}
}
}
Some(update) = update_rx.recv() => {
match update {
Update::State(id) => {
if let Some(handle) = manager.actors.get(&id) {
let state = handle.get_state();
manager.state.actors.insert(id, state);
context.update_state(manager.state.clone());
}
}
Update::Progress(id) => {
if let Some(handle) = manager.actors.get(&id) {
let progress = handle.get_progress();
manager.progress.actors.insert(id, progress);
}
}
}
}
_ = push_interval.tick() => {
context.update_progress(manager.progress.clone());
}
}
}
}
}
}
enum Update {
State(usize),
Progress(usize),
}
struct CancelListeners {
state: CancelToken,
progress: CancelToken,
events: CancelToken,
}
impl CancelListeners {
fn stop_all(self) {
self.state.cancel();
self.progress.cancel();
self.events.cancel();
}
}
pub enum ManagerCmd<A: AsyncActor> {
SpawnActor {
actor: A,
id_tx: Option<oneshot::Sender<usize>>,
},
StopActor(usize),
Forward { id: usize, cmd: A::Cmd },
}
#[derive(Debug, Clone)]
pub struct ManagerState<State> {
actors: HashMap<usize, State>,
}
impl<State> ManagerState<State> {
pub fn get(&self, id: usize) -> Option<&State> {
self.actors.get(&id)
}
pub fn iter(&self) -> impl Iterator<Item = (usize, &State)> {
self.actors.iter().map(|(&id, s)| (id, s))
}
pub fn len(&self) -> usize {
self.actors.len()
}
pub fn is_empty(&self) -> bool {
self.actors.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct ManagerProgress<Progress> {
actors: HashMap<usize, Progress>,
}
impl<Progress> ManagerProgress<Progress> {
pub fn get(&self, id: usize) -> Option<&Progress> {
self.actors.get(&id)
}
pub fn iter(&self) -> impl Iterator<Item = (usize, &Progress)> {
self.actors.iter().map(|(&id, s)| (id, s))
}
pub fn len(&self) -> usize {
self.actors.len()
}
pub fn is_empty(&self) -> bool {
self.actors.is_empty()
}
}
#[derive(Debug, Clone)]
pub enum ManagerEvent<Event> {
ChildEvent { id: usize, event: Event },
Spawned { id: usize },
Stopped { id: usize },
}