use core::fmt;
use tokio::sync::{broadcast, mpsc, watch};
use tracing::warn;
use crate::wait::{self, SharedWaker};
pub trait ActorCore: Sized {
type Cmd: Send + 'static;
type Event: Clone + Send + 'static;
type State: Clone + Send + Sync + 'static;
type Progress: Clone + Send + Sync + 'static;
const EVENT_CAPACITY: usize = 32;
fn channel(
init_state: Self::State,
init_progress: Self::Progress,
) -> (ActorContext<Self>, ActorHandle<Self>) {
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
let (state_tx, state_rx) = watch::channel(init_state);
let (event_tx, _) = broadcast::channel(Self::EVENT_CAPACITY);
let (progress_tx, progress_rx) = watch::channel(init_progress);
let waker = SharedWaker::default();
let cancel = CancelToken::with_waker(waker.clone());
let context_cancel = cancel.clone();
let (alive_tx, alive_rx) = watch::channel(true);
let context = ActorContext {
cmd_rx,
event_tx: event_tx.clone(),
state_tx,
progress_tx,
cancel: context_cancel,
waker: waker.clone(),
_alive: AliveGuard(alive_tx),
};
let handle = ActorHandle {
cmd_tx,
event_tx,
state_rx,
progress_rx,
cancel,
waker,
alive_rx,
};
(context, handle)
}
fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
}
pub struct ActorHandle<A: ActorCore> {
cmd_tx: mpsc::UnboundedSender<A::Cmd>,
pub(crate) state_rx: watch::Receiver<A::State>,
pub(crate) event_tx: broadcast::Sender<A::Event>,
pub(crate) progress_rx: watch::Receiver<A::Progress>,
cancel: CancelToken,
pub(crate) waker: SharedWaker,
pub(crate) alive_rx: watch::Receiver<bool>,
}
impl<A: ActorCore> ActorHandle<A> {
pub fn send_cmd(&self, cmd: A::Cmd) -> Result<(), SendCmdError> {
if self.cancel.is_cancelled() {
warn!("send cmd failed: actor stopped");
return Err(SendCmdError::Closed);
}
self.cmd_tx.send(cmd).map_err(|_| {
warn!("send cmd failed: channel closed");
SendCmdError::Stopped
})?;
self.waker.wake();
Ok(())
}
pub fn get_state(&self) -> A::State {
self.state_rx.borrow().to_owned()
}
pub fn get_progress(&self) -> A::Progress {
self.progress_rx.borrow().to_owned()
}
pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
self.event_tx.subscribe()
}
pub fn stop(&self) {
self.cancel.cancel();
}
pub fn is_alive(&self) -> bool {
*self.alive_rx.borrow()
}
pub fn alive_rx(&self) -> watch::Receiver<bool> {
self.alive_rx.clone()
}
}
impl<A: ActorCore> Clone for ActorHandle<A> {
fn clone(&self) -> Self {
Self {
cmd_tx: self.cmd_tx.clone(),
state_rx: self.state_rx.clone(),
event_tx: self.event_tx.clone(),
progress_rx: self.progress_rx.clone(),
cancel: self.cancel.clone(),
waker: self.waker.clone(),
alive_rx: self.alive_rx.clone(),
}
}
}
pub struct ActorContext<A: ActorCore> {
pub(crate) cmd_rx: mpsc::UnboundedReceiver<A::Cmd>,
state_tx: watch::Sender<A::State>,
event_tx: broadcast::Sender<A::Event>,
progress_tx: watch::Sender<A::Progress>,
pub(crate) cancel: CancelToken,
pub(crate) waker: SharedWaker,
_alive: AliveGuard,
}
impl<A: ActorCore> ActorContext<A> {
pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
self.event_tx.clone()
}
pub fn send_event(&self, event: A::Event) {
let _ = self.event_tx.send(event);
}
pub fn update_state(&self, state: A::State) {
self.state_tx.send_replace(state);
}
pub fn update_progress(&self, progress: A::Progress) {
self.progress_tx.send_replace(progress);
}
pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
self.cmd_rx.recv()
}
pub fn check_cmd(&mut self) -> Option<A::Cmd> {
self.cmd_rx.try_recv().ok()
}
pub fn cancel_clone(&self) -> CancelToken {
self.cancel.clone()
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_cancelled()
}
}
#[derive(Clone, Debug)]
pub struct CancelToken {
tx: watch::Sender<bool>,
waker: SharedWaker,
}
impl Default for CancelToken {
fn default() -> Self {
Self::new()
}
}
impl CancelToken {
pub fn new() -> Self {
let tx = watch::channel(false).0;
let waker = SharedWaker::default();
Self { tx, waker }
}
pub(crate) fn with_waker(waker: SharedWaker) -> Self {
Self {
tx: watch::channel(false).0,
waker,
}
}
pub fn is_cancelled(&self) -> bool {
*self.tx.borrow()
}
pub async fn cancelled(&self) {
let mut rx = self.tx.subscribe();
let _ = rx.wait_for(|cancelled| *cancelled).await;
}
pub fn cancel(&self) {
self.tx.send_replace(true);
self.waker.wake();
}
pub fn cancelled_blocking(&self) {
if self.is_cancelled() {
return;
}
let waker = self.waker.waker();
let _ = wait::drive_until(self.cancelled(), None, &waker);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SendCmdError {
Stopped,
Closed,
}
impl fmt::Display for SendCmdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Stopped => "actor has been stopped",
Self::Closed => "actor is closed",
})
}
}
impl std::error::Error for SendCmdError {}
struct AliveGuard(watch::Sender<bool>);
impl Drop for AliveGuard {
fn drop(&mut self) {
self.0.send_replace(false);
}
}