use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{Notify, broadcast, mpsc, watch};
use tracing::debug;
pub trait Actor: Sized + Send + 'static {
type Cmd: Send + 'static;
type Event: Clone + Send + 'static;
type State: Clone + Send + Sync + 'static;
type Progress: Clone + Send + Sync + 'static;
const CMD_CAPACITY: usize = 16;
const EVENT_CAPACITY: usize = 16;
fn channel(
init_state: Self::State,
init_progress: Self::Progress,
) -> (ActorContext<Self>, ActorHandle<Self>) {
let (cmd_tx, cmd_rx) = mpsc::channel(Self::CMD_CAPACITY);
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 cancel = CancelToken::new();
let handle_cancel = CancelHandle { cancel };
let context_cancel = handle_cancel.clone();
let context = ActorContext {
cmd_rx,
event_tx: event_tx.clone(),
state_tx,
progress_tx,
cancel: context_cancel,
};
let handle = ActorHandle {
cmd_tx,
event_tx,
state_rx,
progress_rx,
cancel: handle_cancel,
};
(context, handle)
}
fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
fn spawn(self) -> ActorHandle<Self> {
let (init_state, init_progress) = self.init_state_and_progress();
let (context, handle) = Self::channel(init_state, init_progress);
tokio::spawn(self.run(context));
handle
}
fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static;
}
#[derive(Debug, Clone)]
pub struct ActorHandle<A: Actor> {
cmd_tx: mpsc::Sender<A::Cmd>,
state_rx: watch::Receiver<A::State>,
event_tx: broadcast::Sender<A::Event>,
progress_rx: watch::Receiver<A::Progress>,
cancel: CancelHandle,
}
impl<A: Actor> ActorHandle<A> {
pub async fn send_cmd(&self, cmd: A::Cmd) -> Result<(), mpsc::error::SendError<A::Cmd>> {
self.cmd_tx.send(cmd).await
}
pub fn get_state(&self) -> A::State {
self.state_rx.borrow().to_owned()
}
pub fn state_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
where
F: FnMut(A::State) -> Fut + Send + 'static,
Fut: Future<Output = bool> + Send,
{
let token = CancelToken::new();
let wait_token = token.clone();
let mut rx = self.state_rx.clone();
let listen = async move {
loop {
tokio::select! {
_ = wait_token.cancelled() => break,
result = rx.changed() => {
match result {
Ok(())=>{
let state = rx.borrow_and_update().to_owned();
if !op(state).await{
break;
}
}
Err(_) => {break}}
}
}
}
};
tokio::spawn(listen);
CancelHandle { cancel: token }
}
pub fn get_progress(&self) -> A::Progress {
self.progress_rx.borrow().to_owned()
}
pub fn progress_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
where
F: FnMut(A::Progress) -> Fut + Send + 'static,
Fut: Future<Output = bool> + Send,
{
let token = CancelToken::new();
let wait_token = token.clone();
let mut rx = self.progress_rx.clone();
let listen = async move {
loop {
tokio::select! {
_ = wait_token.cancelled() => break,
result = rx.changed() => {
match result {
Ok(())=>{
let progress = rx.borrow_and_update().to_owned();
if !op(progress).await{
break;
}
}
Err(_) => {break}}
} }
}
};
tokio::spawn(listen);
CancelHandle { cancel: token }
}
pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
self.event_tx.subscribe()
}
pub fn events_listen_async<F, Fut>(&self, mut op: F) -> CancelHandle
where
F: FnMut(A::Event) -> Fut + Send + 'static,
Fut: Future<Output = bool> + Send,
{
let mut rx = self.event_tx.subscribe();
let token = CancelToken::new();
let wait_token = token.clone();
let listen = async move {
loop {
tokio::select! {
_ = wait_token.cancelled() => break,
result = rx.recv() => {
match result {
Ok(e) => { if !op(e).await { break; } }
Err(broadcast::error::RecvError::Closed) => break,
Err(broadcast::error::RecvError::Lagged(n)) => {
debug!("事件监听落后 {n} 条");
break;
}
}}
}
}
};
tokio::spawn(listen);
CancelHandle { cancel: token }
}
pub fn stop(&self) {
self.cancel.cancel();
}
}
pub struct ActorContext<A: Actor> {
cmd_rx: mpsc::Receiver<A::Cmd>,
state_tx: watch::Sender<A::State>,
event_tx: broadcast::Sender<A::Event>,
progress_tx: watch::Sender<A::Progress>,
cancel: CancelHandle,
}
impl<A: Actor> 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) {
let _ = self.state_tx.send(state);
}
pub fn update_progress(&self, progress: A::Progress) {
let _ = self.progress_tx.send(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) -> CancelHandle {
self.cancel.clone()
}
}
#[derive(Clone, Debug)]
struct CancelToken {
cancelled: Arc<AtomicBool>,
notify: Arc<Notify>,
}
impl CancelToken {
pub fn new() -> Self {
Self {
cancelled: Arc::new(AtomicBool::new(false)),
notify: Arc::new(Notify::new()),
}
}
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(Ordering::Acquire)
}
pub async fn cancelled(&self) {
if self.is_cancelled() {
return;
}
let notified = self.notify.notified();
if self.is_cancelled() {
return;
}
notified.await;
}
pub fn cancel(&self) {
if !self.cancelled.swap(true, Ordering::AcqRel) {
self.notify.notify_waiters();
}
}
}
#[derive(Debug, Clone)]
pub struct CancelHandle {
cancel: CancelToken,
}
impl CancelHandle {
pub fn cancel(&self) {
self.cancel.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.cancel.is_cancelled()
}
pub async fn cancelled(&self) {
self.cancel.cancelled().await;
}
}
impl Drop for CancelHandle {
fn drop(&mut self) {
self.cancel.cancel();
}
}