use crate::addr::{ActorId, ActorName};
use crate::msg::{ActorMsg, ActorPhase, ActorSignal, Signal, StopCause, Terminated, request_stop};
use crate::refs::ActorRef;
use crate::system::{ActorError, ActorSystem, SpawnOptions};
use crate::timer::{TimerHandle, WATCHDOG_FIRED, deadline_after, rel_nanos};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::time::Duration;
use tokio::sync::{mpsc, watch};
pub struct ActorContext<M: ActorMsg> {
system: ActorSystem,
id: ActorId,
name: Option<ActorName>,
ctl: mpsc::Sender<M>,
sig: mpsc::Sender<Signal>,
stop: Arc<watch::Sender<ActorPhase>>,
watched: Vec<ActorId>,
watchdog: Option<WatchdogArm<M>>,
watchdog_arm: u64,
generation: u32,
restarts: u32,
}
struct WatchdogArm<M: ActorMsg> {
handle: TimerHandle,
base: tokio::time::Instant,
deadline_ns: Arc<AtomicU64>,
msg: Option<M>,
}
impl<M: ActorMsg> WatchdogArm<M> {
fn arm(
system: &ActorSystem,
arm: u64,
timeout: Duration,
sig: mpsc::Sender<Signal>,
msg: M,
) -> Self {
let base = system.now();
let deadline_ns = Arc::new(AtomicU64::new(rel_nanos(base, deadline_after(base, timeout))));
let handle = system.inner.timer.schedule_watchdog(
base,
deadline_ns.clone(),
timeout,
sig,
Signal::WatchdogFire { arm },
);
Self {
handle,
base,
deadline_ns,
msg: Some(msg),
}
}
}
impl<M: ActorMsg> ActorContext<M> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
system: ActorSystem,
id: ActorId,
name: Option<ActorName>,
ctl: mpsc::Sender<M>,
stop: Arc<watch::Sender<ActorPhase>>,
sig: mpsc::Sender<Signal>,
generation: u32,
restarts: u32,
) -> Self {
Self {
system,
id,
name,
ctl,
sig,
stop,
watched: Vec::new(),
watchdog: None,
watchdog_arm: 0,
generation,
restarts,
}
}
pub fn generation(&self) -> u32 {
self.generation
}
pub fn restarts(&self) -> u32 {
self.restarts
}
pub fn id(&self) -> ActorId {
self.id
}
pub fn name(&self) -> Option<&ActorName> {
self.name.as_ref()
}
pub fn system(&self) -> &ActorSystem {
&self.system
}
pub fn is_stopping(&self) -> bool {
matches!(&*self.stop.borrow(), ActorPhase::Stopped { .. })
}
pub fn stop(&self) {
let _ = request_stop(&self.stop, StopCause::Requested);
}
pub fn send_self(&self, msg: M) -> Result<(), ActorError> {
self.ctl.try_send(msg).map_err(|e| match e {
mpsc::error::TrySendError::Full(_) => ActorError::MailboxFull(self.id),
mpsc::error::TrySendError::Closed(_) => ActorError::Closed(self.id),
})
}
pub fn schedule_once(&self, delay: Duration, msg: M) -> TimerHandle {
self.system
.inner
.timer
.schedule_message(delay, self.ctl.clone(), msg)
}
pub fn schedule_interval(&self, interval: Duration, msg: M) -> TimerHandle
where
M: Clone,
{
self.system
.inner
.timer
.schedule_interval(interval, self.ctl.clone(), msg)
}
pub fn watchdog(&mut self, timeout: Duration, msg: M) {
let mut msg = Some(msg);
if let Some(arm) = self.watchdog.as_mut() {
if !arm.handle.has_fired() {
let new_rel = rel_nanos(arm.base, deadline_after(self.system.now(), timeout));
let prev = arm.deadline_ns.swap(new_rel, AtomicOrdering::AcqRel);
if prev != WATCHDOG_FIRED {
arm.msg = msg.take();
return; }
}
}
if let Some(old) = self.watchdog.take() {
old.handle.cancel();
}
let seq = self.system.inner.next_watchdog_arm();
let sig = self.sig.clone();
self.watchdog_arm = seq;
self.watchdog = Some(WatchdogArm::arm(
&self.system,
seq,
timeout,
sig,
msg.take().expect("msg 未被滑动分支消费"),
));
}
pub fn disarm_watchdog(&mut self) {
if let Some(arm) = self.watchdog.take() {
arm.handle.cancel();
self.watchdog_arm = self.system.inner.next_watchdog_arm();
}
}
pub(crate) fn take_watchdog_fire(&mut self, arm: u64) -> Option<M> {
if arm != self.watchdog_arm {
tracing::debug!(
actor = %self.id,
arm,
current = self.watchdog_arm,
"看门狗触发已陈旧(已被喂狗/再武装/解除取代),丢弃"
);
return None;
}
self.watchdog.as_mut()?.msg.take()
}
pub fn watch<T: ActorMsg>(&mut self, target: &ActorRef<T>) {
self.watch_id(target.id());
}
pub fn watch_id(&mut self, target: ActorId) {
if target == self.id {
return; }
if self.watched.contains(&target) {
return; }
self.watched.push(target);
self.system.inner.register_watch(self.id, target);
if !self.system.is_alive(target) {
self.watched.retain(|&t| t != target);
if self.system.inner.unregister_watch(self.id, target) {
let notice = ActorSignal::Terminated(Terminated {
actor: target,
name: None,
cause: StopCause::Missing,
detail: None,
});
let tx = self.sig.clone();
tokio::spawn(async move {
if tx.send(Signal::System(notice)).await.is_err() {
tracing::warn!("watch 竞态复核:补发 Terminated 失败(信号通道已关闭)")
}
});
}
}
}
pub(crate) fn reap_watch(&mut self, target: ActorId) {
self.watched.retain(|&t| t != target);
self.system.inner.unregister_watch(self.id, target);
}
pub fn unwatch<T: ActorMsg>(&mut self, target: &ActorRef<T>) {
self.unwatch_id(target.id());
}
pub fn unwatch_id(&mut self, target: ActorId) {
self.watched.retain(|&t| t != target);
self.system.inner.unregister_watch(self.id, target);
}
pub fn spawn_child<A: crate::Actor>(
&self,
opts: impl Into<SpawnOptions>,
actor: A,
) -> Result<ActorRef<A::Message>, ActorError> {
let opts = opts.into().with_parent(self.id);
self.system.spawn(opts, actor)
}
pub fn spawn_child_supervised<A, F>(
&self,
opts: impl Into<SpawnOptions>,
factory: F,
) -> Result<ActorRef<A::Message>, ActorError>
where
A: crate::Actor,
F: Fn() -> A + Send + Sync + 'static,
{
let opts = opts.into().with_parent(self.id);
self.system.spawn_supervised(opts, factory)
}
}
impl<M: ActorMsg> Drop for ActorContext<M> {
fn drop(&mut self) {
if let Some(arm) = self.watchdog.take() {
arm.handle.cancel();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::timer::WATCHDOG_FIRED;
use std::sync::atomic::Ordering as AO;
#[tokio::test]
async fn refeed_in_driver_claim_window_rearms_without_panic() {
let system = ActorSystem::new();
let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
let mut ctx: ActorContext<u32> = ActorContext::new(
system.clone(),
ActorId::new(1),
None,
ctl_tx,
Arc::new(stop_tx),
sig_tx,
1,
0,
);
ctx.watchdog(Duration::from_secs(60), 7u32);
let old_arm = ctx.watchdog_arm;
{
let arm = ctx.watchdog.as_ref().expect("已武装");
arm.deadline_ns.store(WATCHDOG_FIRED, AO::Relaxed);
assert!(!arm.handle.has_fired(), "前置:fired 未置位");
}
ctx.watchdog(Duration::from_secs(60), 8u32);
assert_ne!(ctx.watchdog_arm, old_arm, "必须换代,旧在途触发作废");
assert_eq!(
system.inner.timer.active_entries().await,
1,
"换代再武装必须收敛旧条目(驱动内仅余新条目)"
);
assert_eq!(
ctx.take_watchdog_fire(old_arm),
None,
"旧世代触发应判陈旧丢弃"
);
assert_eq!(
ctx.take_watchdog_fire(ctx.watchdog_arm),
Some(8u32),
"新世代触发应投递最新消息"
);
system.shutdown().await;
}
#[tokio::test]
async fn watchdog_extreme_timeout_does_not_panic() {
let system = ActorSystem::new();
let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
let mut ctx: ActorContext<u32> = ActorContext::new(
system.clone(),
ActorId::new(1),
None,
ctl_tx,
Arc::new(stop_tx),
sig_tx,
1,
0,
);
ctx.watchdog(Duration::MAX, 7u32); ctx.watchdog(Duration::MAX, 8u32); ctx.disarm_watchdog();
system.shutdown().await;
}
#[tokio::test]
async fn watchdog_entry_retires_when_ctx_dropped() {
let system = ActorSystem::new();
let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
let mut ctx: ActorContext<u32> = ActorContext::new(
system.clone(),
ActorId::new(1),
None,
ctl_tx,
Arc::new(stop_tx),
sig_tx,
1,
0,
);
ctx.watchdog(Duration::from_secs(3600), 7u32);
assert_eq!(
system.inner.timer.active_entries().await,
1,
"武装后看门狗条目应在驱动内"
);
drop(ctx);
assert_eq!(
system.inner.timer.active_entries().await,
0,
"ctx 析构必须取消看门狗条目(不得滞留至超时)"
);
system.shutdown().await;
}
}