1use crate::addr::{ActorId, ActorName};
19use crate::actor::{Actor, ActorAction};
20use crate::ctx::ActorContext;
21use crate::mailbox::{latest_slot, SlotReader, DEFAULT_MAILBOX_CAPACITY};
22use crate::msg::{
23 ActorMsg, ActorPhase, ActorSignal, Signal, StopCause, Terminated, publish_phase, request_stop,
24};
25use crate::refs::{new_ref, ActorRef};
26use crate::timer::{Clock, ClockSource, TimerDriver, deadline_after};
27use dashmap::DashMap;
28use std::fmt;
29use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering as AtomicOrdering};
30use std::sync::Arc;
31use std::time::Duration;
32use tokio::sync::{mpsc, oneshot, watch};
33
34const SELF_BATCH_LIMIT: usize = 64;
36
37tokio::task_local! {
38 pub(crate) static GENERATION_ACTOR: ActorId;
44}
45
46pub(crate) fn assert_not_self_call(target: ActorId, what: &str) {
55 if let Ok(caller) = GENERATION_ACTOR.try_with(|id| *id) {
56 assert_ne!(
57 caller, target,
58 "检测到 Actor {target} 的 {what} 自调用:该 API 需等待目标事件循环\
59 推进,而事件循环正阻塞在此调用上,必然死锁或等满超时。\
60 请求自身停止请改用 ActorContext::stop() 并返回 ActorAction::Stop;\
61 确有异步需要时请在 tokio::spawn 出的独立任务中调用\
62 (子任务不带世代身份,不在本检测范围内)"
63 );
64 }
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum ActorError {
70 DuplicateName(ActorName),
72 MailboxFull(ActorId),
74 Closed(ActorId),
76 Timeout(ActorId),
79 SystemShutdown,
81}
82
83impl fmt::Display for ActorError {
84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 match self {
86 ActorError::DuplicateName(n) => write!(f, "Actor 名称 \"{n}\" 已被占用"),
87 ActorError::MailboxFull(id) => write!(f, "Actor {id} 邮箱已满,请稍后重试"),
88 ActorError::Closed(id) => write!(f, "Actor {id} 通道已关闭"),
89 ActorError::Timeout(id) => write!(f, "Actor {id} 未在期限内退出"),
90 ActorError::SystemShutdown => f.write_str("ActorSystem 已关闭"),
91 }
92 }
93}
94
95impl std::error::Error for ActorError {}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
99pub enum RestartPolicy {
100 #[default]
102 Permanent,
103 Transient {
109 max_restarts: u32,
110 backoff: Duration,
111 reset_after: Duration,
112 },
113}
114
115#[derive(Debug, Clone)]
117pub struct SpawnOptions {
118 pub(crate) name: Option<ActorName>,
119 pub(crate) restart: RestartPolicy,
120 pub(crate) parent: Option<ActorId>,
121}
122
123impl SpawnOptions {
124 pub fn void() -> Self {
126 Self {
127 name: None,
128 restart: RestartPolicy::default(),
129 parent: None,
130 }
131 }
132
133 pub fn named(name: impl Into<ActorName>) -> Self {
135 Self {
136 name: Some(name.into()),
137 ..Self::void()
138 }
139 }
140
141 pub fn with_name(mut self, name: impl Into<ActorName>) -> Self {
143 self.name = Some(name.into());
144 self
145 }
146
147 pub fn with_restart(mut self, policy: RestartPolicy) -> Self {
149 self.restart = policy;
150 self
151 }
152
153 pub(crate) fn with_parent(mut self, parent: ActorId) -> Self {
154 self.parent = Some(parent);
155 self
156 }
157}
158
159impl Default for SpawnOptions {
160 fn default() -> Self {
161 Self::void()
162 }
163}
164
165impl From<&str> for SpawnOptions {
166 fn from(n: &str) -> Self {
167 Self::named(n)
168 }
169}
170
171impl From<String> for SpawnOptions {
172 fn from(n: String) -> Self {
173 Self::named(n)
174 }
175}
176
177impl From<ActorName> for SpawnOptions {
178 fn from(n: ActorName) -> Self {
179 Self::named(n)
180 }
181}
182
183#[derive(Debug, Clone)]
185pub struct ActorConfig {
186 pub mailbox_capacity: usize,
188 pub signal_channel_capacity: usize,
190 pub shutdown_grace: Duration,
197 pub abort_on_grace_timeout: bool,
210}
211
212impl Default for ActorConfig {
213 fn default() -> Self {
214 Self {
215 mailbox_capacity: DEFAULT_MAILBOX_CAPACITY,
216 signal_channel_capacity: SIGNAL_CHANNEL_CAPACITY,
217 shutdown_grace: Duration::from_secs(2),
218 abort_on_grace_timeout: false,
219 }
220 }
221}
222
223const SIGNAL_CHANNEL_CAPACITY: usize = 64;
230
231trait SignalSink: Send + Sync {
233 fn push_signal(&self, sig: Signal);
238}
239
240impl SignalSink for mpsc::Sender<Signal> {
241 fn push_signal(&self, sig: Signal) {
242 match self.try_send(sig) {
248 Ok(()) => {}
249 Err(mpsc::error::TrySendError::Full(sig)) => {
250 let Ok(handle) = tokio::runtime::Handle::try_current() else {
253 tracing::warn!("信号通道满载且无异步上下文(系统收尾),Terminated 通知丢弃");
254 return;
255 };
256 let tx = self.clone();
257 handle.spawn(async move {
258 if tx.send(sig).await.is_err() {
259 tracing::debug!("Terminated 投递中止:信号通道已关闭(目标已终止)")
260 }
261 });
262 }
263 Err(mpsc::error::TrySendError::Closed(_)) => {
264 tracing::debug!("Terminated 投递中止:信号通道已关闭(目标已终止)")
265 }
266 }
267 }
268}
269
270trait AnyRef: Send + Sync {
272 fn as_any(&self) -> &dyn std::any::Any;
273}
274
275impl<M: ActorMsg> AnyRef for ActorRef<M> {
276 fn as_any(&self) -> &dyn std::any::Any {
277 self
278 }
279}
280
281struct Entry {
283 id: ActorId,
284 name: Option<ActorName>,
285 kind: &'static str,
287 sig: Box<dyn SignalSink>,
288 stop: Arc<watch::Sender<ActorPhase>>,
291 exit: watch::Sender<bool>,
293 abort: Arc<std::sync::Mutex<Option<tokio::task::AbortHandle>>>,
297 typed: Box<dyn AnyRef>,
298}
299
300pub(crate) struct SystemInner {
302 registry: DashMap<ActorId, Entry>,
303 by_name: DashMap<ActorName, ActorId>,
304 watched_by: DashMap<ActorId, Vec<ActorId>>,
306 watching: DashMap<ActorId, Vec<ActorId>>,
309 next_id: AtomicU64,
310 next_arm: AtomicU64,
312 tracked_handles: AtomicUsize,
314 shutdown: AtomicBool,
315 shutdown_tx: watch::Sender<bool>,
316 pub(crate) timer: TimerDriver,
317 clock: ClockSource,
318 config: ActorConfig,
319}
320
321impl SystemInner {
322 pub(crate) fn next_watchdog_arm(&self) -> u64 {
324 self.next_arm.fetch_add(1, AtomicOrdering::Relaxed)
325 }
326
327 fn register_name(&self, name: &ActorName, id: ActorId) -> Result<(), ActorError> {
337 use dashmap::mapref::entry::Entry as NameEntry;
338 match self.by_name.entry(name.clone()) {
339 NameEntry::Vacant(v) => {
340 v.insert(id);
341 Ok(())
342 }
343 NameEntry::Occupied(occupied) => {
344 let cur = *occupied.get();
345 drop(occupied);
346 if self.registry.contains_key(&cur) {
347 return Err(ActorError::DuplicateName(name.clone()));
348 }
349 self.by_name.remove_if(name, |_, &cur_id| cur_id == cur);
354 match self.by_name.entry(name.clone()) {
355 NameEntry::Vacant(v) => {
356 v.insert(id);
357 Ok(())
358 }
359 NameEntry::Occupied(_) => Err(ActorError::DuplicateName(name.clone())),
360 }
361 }
362 }
363 }
364
365 pub(crate) fn register_watch(&self, watcher: ActorId, target: ActorId) {
372 let mut list = self.watched_by.entry(target).or_default();
373 if !list.contains(&watcher) {
374 list.push(watcher);
375 }
376 drop(list);
377 let mut rev = self.watching.entry(watcher).or_default();
378 if !rev.contains(&target) {
379 rev.push(target);
380 }
381 }
382
383 pub(crate) fn unregister_watch(&self, watcher: ActorId, target: ActorId) -> bool {
387 let removed = match self.watched_by.get_mut(&target) {
388 Some(mut list) => {
389 let before = list.len();
390 list.retain(|&w| w != watcher);
391 let removed = list.len() != before;
392 let now_empty = list.is_empty();
393 drop(list);
394 if now_empty {
395 self.watched_by
398 .remove_if(&target, |_, watchers| watchers.is_empty());
399 }
400 removed
401 }
402 None => false,
403 };
404 if let Some(mut rev) = self.watching.get_mut(&watcher) {
407 rev.retain(|&t| t != target);
408 let now_empty = rev.is_empty();
409 drop(rev);
410 if now_empty {
411 self.watching
412 .remove_if(&watcher, |_, targets| targets.is_empty());
413 }
414 }
415 removed
416 }
417
418 pub(crate) fn cleanup_watcher(&self, watcher: ActorId) {
421 if let Some((_, targets)) = self.watching.remove(&watcher) {
422 for target in targets {
423 if let Some(mut list) = self.watched_by.get_mut(&target) {
424 list.retain(|&w| w != watcher);
425 let now_empty = list.is_empty();
426 drop(list);
427 if now_empty {
428 self.watched_by
429 .remove_if(&target, |_, watchers| watchers.is_empty());
430 }
431 }
432 }
433 }
434 }
435
436 fn push_signal(&self, id: ActorId, sig: ActorSignal) {
437 if let Some(e) = self.registry.get(&id) {
438 e.sig.push_signal(Signal::System(sig));
439 }
440 }
441}
442
443struct SpawnRollback {
454 inner: Arc<SystemInner>,
455 id: ActorId,
456 name: Option<ActorName>,
457 parent: Option<ActorId>,
458 armed: bool,
459}
460
461impl SpawnRollback {
462 fn disarm(&mut self) {
463 self.armed = false;
464 }
465}
466
467impl Drop for SpawnRollback {
468 fn drop(&mut self) {
469 if !self.armed {
470 return;
471 }
472 self.inner.registry.remove(&self.id);
473 if let Some(n) = &self.name {
474 self.inner.by_name.remove_if(n, |_, &cur| cur == self.id);
475 }
476 if let Some(parent) = self.parent {
477 self.inner.unregister_watch(parent, self.id);
478 }
479 tracing::debug!(actor = %self.id, "spawn 未完成,已回滚注册表与名称登记");
482 }
483}
484
485pub struct ActorSystem {
494 pub(crate) inner: Arc<SystemInner>,
495 tracked: bool,
500}
501
502impl Clone for ActorSystem {
503 fn clone(&self) -> Self {
504 if self.tracked {
505 self.inner
506 .tracked_handles
507 .fetch_add(1, AtomicOrdering::Relaxed);
508 }
509 Self {
510 inner: self.inner.clone(),
511 tracked: self.tracked,
512 }
513 }
514}
515
516impl Drop for ActorSystem {
517 fn drop(&mut self) {
518 if !self.tracked || self.inner.tracked_handles.fetch_sub(1, AtomicOrdering::AcqRel) != 1 {
519 return; }
521 let alive = self.inner.registry.len();
522 if alive > 0 && !self.inner.shutdown.load(AtomicOrdering::Acquire) {
523 tracing::warn!(
524 actor_count = alive,
525 "ActorSystem 的最后一个句柄在未调用 shutdown 的情况下被丢弃:\
526 {alive} 个 Actor 任务将继续运行(监督者恒持邮箱发送端)\
527 直至 tokio 运行时销毁,请改调 ActorSystem::shutdown"
528 );
529 }
530 }
531}
532
533impl ActorSystem {
534 pub fn new() -> Self {
541 Self::with_config(ActorConfig::default())
542 }
543
544 pub fn with_config(config: ActorConfig) -> Self {
550 Self::with_clock_source(config, ClockSource::Tokio)
551 }
552
553 pub fn with_clock(config: ActorConfig, clock: Arc<dyn Clock>) -> Self {
559 Self::with_clock_source(config, ClockSource::Custom(clock))
560 }
561
562 fn with_clock_source(config: ActorConfig, clock: ClockSource) -> Self {
563 let timer = TimerDriver::spawn(clock.clone());
564 let (shutdown_tx, _) = watch::channel(false);
565 Self {
566 inner: Arc::new(SystemInner {
567 registry: DashMap::new(),
568 by_name: DashMap::new(),
569 watched_by: DashMap::new(),
570 watching: DashMap::new(),
571 next_id: AtomicU64::new(1),
572 next_arm: AtomicU64::new(1),
573 tracked_handles: AtomicUsize::new(1),
574 shutdown: AtomicBool::new(false),
575 shutdown_tx,
576 timer,
577 clock,
578 config,
579 }),
580 tracked: true,
581 }
582 }
583
584 pub(crate) fn from_inner(inner: Arc<SystemInner>) -> Self {
586 Self {
587 inner,
588 tracked: false,
589 }
590 }
591
592 fn internal(&self) -> Self {
593 Self::from_inner(self.inner.clone())
594 }
595
596 pub fn config(&self) -> &ActorConfig {
598 &self.inner.config
599 }
600
601 pub fn now(&self) -> tokio::time::Instant {
603 self.inner.clock.now()
604 }
605
606 pub fn is_shutdown(&self) -> bool {
608 self.inner.shutdown.load(AtomicOrdering::Acquire)
609 }
610
611 pub fn spawn<A>(
629 &self,
630 opts: impl Into<SpawnOptions>,
631 actor: A,
632 ) -> Result<ActorRef<A::Message>, ActorError>
633 where
634 A: Actor,
635 {
636 self.spawn_inner(opts.into(), ActorSource::Once(Some(actor)))
637 }
638
639 pub fn spawn_anonymous<A>(&self, actor: A) -> Result<ActorRef<A::Message>, ActorError>
645 where
646 A: Actor,
647 {
648 self.spawn(SpawnOptions::void(), actor)
649 }
650
651 pub fn spawn_named<A>(
657 &self,
658 name: impl Into<ActorName>,
659 actor: A,
660 ) -> Result<ActorRef<A::Message>, ActorError>
661 where
662 A: Actor,
663 {
664 self.spawn(SpawnOptions::named(name), actor)
665 }
666
667 pub fn spawn_supervised<A, F>(
679 &self,
680 opts: impl Into<SpawnOptions>,
681 factory: F,
682 ) -> Result<ActorRef<A::Message>, ActorError>
683 where
684 A: Actor,
685 F: Fn() -> A + Send + Sync + 'static,
686 {
687 self.spawn_inner(opts.into(), ActorSource::Factory(Arc::new(factory)))
688 }
689
690 fn spawn_inner<A>(
691 &self,
692 opts: SpawnOptions,
693 source: ActorSource<A>,
694 ) -> Result<ActorRef<A::Message>, ActorError>
695 where
696 A: Actor,
697 {
698 let inner = self.inner.clone();
699 if self.is_shutdown() {
700 return Err(ActorError::SystemShutdown);
701 }
702 if matches!(source, ActorSource::Once(_))
704 && matches!(opts.restart, RestartPolicy::Transient { .. })
705 {
706 tracing::warn!(
707 "spawn 使用一次性实例但声明了 Transient 策略;panic 后将无法重启(请改用 spawn_supervised)"
708 );
709 }
710 let id = ActorId::new(inner.next_id.fetch_add(1, AtomicOrdering::Relaxed));
711 let name = opts.name.clone();
712
713 let policy = A::mailbox_policy().resolve(inner.config.mailbox_capacity);
714 let (ctl_tx, ctl_rx) = mpsc::channel::<A::Message>(policy.capacity());
715 let (sig_tx, sig_rx) = mpsc::channel::<Signal>(inner.config.signal_channel_capacity.max(1));
716 let (stop_tx, stop_rx) = watch::channel(ActorPhase::Running);
717 let stop_tx = Arc::new(stop_tx);
718 let (slot_tx, slot_rx) = if policy.has_data_port() {
719 let (w, r) = latest_slot::<A::Message>();
720 (Some(w), Some(r))
721 } else {
722 (None, None)
723 };
724 let (exit_tx, _) = watch::channel(false);
725 let abort_slot: Arc<std::sync::Mutex<Option<tokio::task::AbortHandle>>> =
728 Arc::new(std::sync::Mutex::new(None));
729
730 let aref = new_ref(
731 id,
732 name.clone(),
733 ctl_tx.clone(),
734 stop_tx.clone(),
735 slot_tx,
736 inner.clock.clone(),
737 Arc::downgrade(&inner),
738 );
739 tracing::debug!(actor = %id, kind = std::any::type_name::<A::Message>(), capacity = policy.capacity(), "Actor 已注册");
740 inner.registry.insert(
745 id,
746 Entry {
747 id,
748 name: name.clone(),
749 kind: std::any::type_name::<A::Message>(),
750 sig: Box::new(sig_tx.clone()),
751 stop: stop_tx.clone(),
752 exit: exit_tx.clone(),
753 abort: abort_slot.clone(),
754 typed: Box::new(aref.clone()),
755 },
756 );
757 let mut rollback = SpawnRollback {
760 inner: inner.clone(),
761 id,
762 name: name.clone(),
763 parent: opts.parent,
764 armed: true,
765 };
766 if let Some(n) = &name {
767 inner.register_name(n, id)?;
768 }
769 if let Some(parent) = opts.parent {
770 inner.register_watch(parent, id);
771 }
772
773 let guard = FinalizeGuard {
776 system: self.internal(),
777 id,
778 name: name.clone(),
779 exit_tx,
780 stop_tx: stop_tx.clone(),
781 done: false,
782 };
783 let supervisor = Supervisor {
784 system: self.internal(),
785 id,
786 name: name.clone(),
787 source,
788 policy: opts.restart,
789 ctl_tx,
790 stop_tx,
791 stop_rx,
792 slot_rx,
793 generation: 0, restarts: 0,
795 mailbox: Arc::new(tokio::sync::Mutex::new(ctl_rx)),
796 sigbox: Arc::new(tokio::sync::Mutex::new(sig_rx)),
797 sig_tx: sig_tx.clone(),
798 abort: abort_slot,
799 guard,
800 shutdown_rx: inner.shutdown_tx.subscribe(),
801 };
802 tokio::spawn(async move { supervisor.run().await });
803 rollback.disarm();
804 Ok(aref)
805 }
806
807 pub fn find<M: ActorMsg>(&self, name: impl AsRef<str>) -> Option<ActorRef<M>> {
816 let id = *self.inner.by_name.get(name.as_ref())?;
817 self.find_by_id::<M>(id)
818 }
819
820 pub fn find_by_id<M: ActorMsg>(&self, id: ActorId) -> Option<ActorRef<M>> {
822 self.inner.registry.get(&id).and_then(|e| {
823 e.typed
824 .as_any()
825 .downcast_ref::<ActorRef<M>>()
826 .cloned()
827 })
828 }
829
830 pub fn resolve_name(&self, name: impl AsRef<str>) -> Option<ActorId> {
832 self.inner.by_name.get(name.as_ref()).map(|r| *r)
833 }
834
835 pub fn is_alive(&self, id: ActorId) -> bool {
837 self.inner.registry.contains_key(&id)
838 }
839
840 pub fn actor_count(&self) -> usize {
842 self.inner.registry.len()
843 }
844
845 pub fn actor_ids(&self) -> Vec<ActorId> {
847 self.inner.registry.iter().map(|e| *e.key()).collect()
848 }
849
850 #[must_use = "返回是否成功送达停止请求(false 表示 Actor 不存在)"]
861 pub fn stop(&self, id: ActorId) -> bool {
862 match self.inner.registry.get(&id) {
863 Some(e) => request_stop(&e.stop, StopCause::Requested),
864 None => false,
865 }
866 }
867
868 #[must_use = "按名称停止的结果可能被静默忽略(false 表示未找到)"]
870 pub fn stop_named(&self, name: impl AsRef<str>) -> bool {
871 match self.resolve_name(name) {
872 Some(id) => self.stop(id),
873 None => false,
874 }
875 }
876
877 pub async fn stop_and_wait(&self, id: ActorId) -> bool {
894 assert_not_self_call(id, "stop_and_wait");
895 let rx = self.inner.registry.get(&id).map(|e| e.exit.subscribe());
896 let _ = self.stop(id);
897 match rx {
898 Some(mut rx) => {
899 let _ = rx.changed().await;
901 true
902 }
903 None => false,
904 }
905 }
906
907 pub async fn stop_and_wait_timeout(
920 &self,
921 id: ActorId,
922 timeout: Duration,
923 ) -> Result<bool, ActorError> {
924 assert_not_self_call(id, "stop_and_wait_timeout");
925 let rx = self.inner.registry.get(&id).map(|e| e.exit.subscribe());
926 let _ = self.stop(id);
927 let Some(mut rx) = rx else {
928 return Ok(false);
929 };
930 let deadline = deadline_after(self.inner.clock.now(), timeout);
931 tokio::select! {
932 _ = rx.changed() => Ok(true),
933 _ = self.inner.clock.sleep_until(deadline) => Err(ActorError::Timeout(id)),
934 }
935 }
936
937 pub async fn shutdown(&self) {
965 if self
966 .inner
967 .shutdown
968 .compare_exchange(
969 false,
970 true,
971 AtomicOrdering::AcqRel,
972 AtomicOrdering::Acquire,
973 )
974 .is_err()
975 {
976 return; }
978 tracing::info!(actor_count = self.actor_count(), "ActorSystem 开始优雅关闭");
979 let _ = self.inner.shutdown_tx.send(true);
980 let caller = GENERATION_ACTOR.try_with(|id| *id).ok();
983
984 let pending: Vec<(ActorId, Option<ActorName>, watch::Receiver<bool>)> = self
986 .inner
987 .registry
988 .iter()
989 .map(|e| (e.id, e.name.clone(), e.exit.subscribe()))
990 .collect();
991 for (id, _, _) in &pending {
992 if let Some(e) = self.inner.registry.get(id) {
993 let _ = request_stop(&e.stop, StopCause::SystemShutdown);
997 }
998 }
999
1000 let grace = self.inner.config.shutdown_grace;
1004 let clock = self.inner.clock.clone();
1005 let mut waits = tokio::task::JoinSet::new();
1006 for (id, name, rx) in pending {
1007 if Some(id) == caller {
1008 tracing::debug!(actor = %id, "shutdown 由该 Actor 自身发起,跳过其退出等待");
1009 continue;
1010 }
1011 let clock = clock.clone();
1012 waits.spawn(async move {
1013 let mut rx = rx;
1014 let deadline = deadline_after(clock.now(), grace);
1015 let timed_out = tokio::select! {
1016 _ = rx.changed() => false,
1017 _ = clock.sleep_until(deadline) => true,
1018 };
1019 (id, name, timed_out)
1020 });
1021 }
1022 while let Some(joined) = waits.join_next().await {
1023 match joined {
1024 Ok((id, name, timed_out)) => {
1025 if timed_out {
1026 tracing::warn!(%id, ?name, "Actor 未在宽限期内退出,强制注销");
1027 self.force_deregister(id, name.as_ref());
1028 }
1029 }
1030 Err(e) => tracing::warn!("关闭等待任务异常:{e}"),
1031 }
1032 }
1033 tracing::info!("ActorSystem 已完全关闭");
1034 }
1035
1036 fn force_deregister(&self, id: ActorId, name: Option<&ActorName>) {
1049 if let Some((_, entry)) = self.inner.registry.remove(&id) {
1050 if self.inner.config.abort_on_grace_timeout {
1051 let handle = entry.abort.lock().unwrap_or_else(|e| e.into_inner()).take();
1052 if let Some(h) = handle {
1053 h.abort();
1054 tracing::warn!(
1055 actor = %id,
1056 kind = entry.kind,
1057 "宽限超时:已硬终止卡死的事件循环任务(实例 Drop 立即执行,on_stop 已跳过)"
1058 );
1059 }
1060 }
1061 tracing::debug!(actor = %id, kind = entry.kind, "强制注销已捕获条目");
1062 drop(entry); }
1064 if let Some(n) = name {
1065 self.inner.by_name.remove_if(n, |_, &cur| cur == id);
1066 }
1067 self.inner.cleanup_watcher(id);
1071 let terminated = Terminated {
1072 actor: id,
1073 name: name.cloned(),
1074 cause: StopCause::SystemShutdown,
1075 detail: None,
1076 };
1077 if let Some((_, watchers)) = self.inner.watched_by.remove(&id) {
1078 for w in watchers {
1079 self.inner
1080 .push_signal(w, ActorSignal::Terminated(terminated.clone()));
1081 }
1082 }
1083 }
1084}
1085
1086impl Default for ActorSystem {
1087 fn default() -> Self {
1088 Self::new()
1089 }
1090}
1091
1092enum ActorSource<A: Actor> {
1097 Once(Option<A>),
1099 Factory(Arc<dyn Fn() -> A + Send + Sync>),
1101}
1102
1103impl<A: Actor> ActorSource<A> {
1104 fn take(&mut self) -> Option<A> {
1105 match self {
1106 ActorSource::Once(slot) => slot.take(),
1107 ActorSource::Factory(f) => Some(f()),
1108 }
1109 }
1110
1111 fn is_renewable(&self) -> bool {
1112 match self {
1113 ActorSource::Once(slot) => slot.is_some(),
1114 ActorSource::Factory(_) => true,
1115 }
1116 }
1117}
1118
1119enum SourceTaken<A: Actor> {
1121 Ready(A),
1123 Exhausted,
1125 FactoryPanicked(Option<String>),
1127}
1128
1129struct GenDone {
1134 cause: StopCause,
1135}
1136
1137enum GenOutcome {
1138 Exited(GenDone),
1140 Panicked { detail: Option<String> },
1142}
1143
1144fn payload_text(payload: Box<dyn std::any::Any + Send>) -> Option<String> {
1147 if let Some(s) = payload.downcast_ref::<&'static str>() {
1148 Some((*s).to_string())
1149 } else if let Some(s) = payload.downcast_ref::<String>() {
1150 Some(s.clone())
1151 } else {
1152 Some("panicked(非文本 panic 载荷)".to_string())
1153 }
1154}
1155
1156fn panic_detail(je: tokio::task::JoinError) -> Option<String> {
1158 payload_text(je.into_panic())
1159}
1160
1161struct Supervisor<A: Actor> {
1166 system: ActorSystem,
1167 id: ActorId,
1168 name: Option<ActorName>,
1169 source: ActorSource<A>,
1170 policy: RestartPolicy,
1171 ctl_tx: mpsc::Sender<A::Message>,
1172 stop_tx: Arc<watch::Sender<ActorPhase>>,
1173 stop_rx: watch::Receiver<ActorPhase>,
1174 slot_rx: Option<SlotReader<A::Message>>,
1175 generation: u32,
1177 restarts: u32,
1179 mailbox: Arc<tokio::sync::Mutex<mpsc::Receiver<A::Message>>>,
1182 sigbox: Arc<tokio::sync::Mutex<mpsc::Receiver<Signal>>>,
1184 sig_tx: mpsc::Sender<Signal>,
1187 abort: Arc<std::sync::Mutex<Option<tokio::task::AbortHandle>>>,
1192 guard: FinalizeGuard,
1195 shutdown_rx: watch::Receiver<bool>,
1196}
1197
1198impl<A: Actor> Supervisor<A> {
1199 async fn run(mut self) {
1200 let mut last_failure: Option<tokio::time::Instant> = None;
1201 let last_cause;
1202 let mut last_detail: Option<String> = None;
1206
1207 loop {
1208 if self.is_shutdown() {
1209 if self.generation == 0 {
1212 tracing::warn!(
1213 actor = %self.id,
1214 name = ?self.name,
1215 "Actor 在系统关闭流程中注册,未执行 on_start/on_stop 即退出"
1216 );
1217 }
1218 last_cause = StopCause::SystemShutdown;
1219 last_detail = None;
1220 break;
1221 }
1222 if matches!(
1223 &*self.stop_rx.borrow_and_update(),
1224 ActorPhase::Stopped { .. }
1225 ) {
1226 last_cause = StopCause::Requested;
1227 last_detail = None;
1228 break;
1229 }
1230 let outcome = match self.take_actor() {
1231 SourceTaken::Ready(actor) => {
1232 self.generation += 1;
1233 self.run_one_generation(actor).await
1234 }
1235 SourceTaken::Exhausted => {
1236 last_cause = if self.restarts > 0 {
1241 StopCause::ResourceLimit
1242 } else {
1243 StopCause::Panicked
1244 };
1245 break;
1246 }
1247 SourceTaken::FactoryPanicked(detail) => GenOutcome::Panicked { detail },
1251 };
1252 match outcome {
1253 GenOutcome::Exited(done) => {
1254 last_cause = if done.cause == StopCause::Requested && self.is_shutdown() {
1258 StopCause::SystemShutdown
1259 } else {
1260 done.cause
1261 };
1262 last_detail = None;
1263 break;
1264 }
1265 GenOutcome::Panicked { detail } => {
1266 last_detail = detail;
1267 match self.policy {
1268 RestartPolicy::Permanent => {
1269 last_cause = StopCause::Panicked;
1270 break;
1271 }
1272 RestartPolicy::Transient {
1273 max_restarts,
1274 backoff,
1275 reset_after,
1276 } => {
1277 let now = self.system.now();
1278 if last_failure.is_some_and(|t| now - t >= reset_after) {
1279 self.restarts = 0; }
1281 self.restarts += 1;
1282 last_failure = Some(now);
1283 if !self.source.is_renewable() || self.restarts > max_restarts {
1284 last_cause = StopCause::ResourceLimit;
1285 break;
1286 }
1287 let shift = (self.restarts - 1).min(10);
1288 let delay = backoff.saturating_mul(1u32 << shift);
1289 tracing::warn!(
1290 actor = %self.id,
1291 restart = self.restarts,
1292 ?delay,
1293 "Actor 事件循环 panic,按监督策略重启"
1294 );
1295 publish_phase(
1297 &self.stop_tx,
1298 ActorPhase::Restarting {
1299 generation: self.generation + 1,
1300 attempt: self.restarts,
1301 },
1302 );
1303 if !self.wait_backoff(delay).await {
1304 last_cause = if self.is_shutdown() {
1305 StopCause::SystemShutdown
1306 } else {
1307 StopCause::Requested
1308 };
1309 last_detail = None;
1310 break;
1311 }
1312 continue;
1313 }
1314 }
1315 }
1316 }
1317 }
1318
1319 self.guard.finalize(last_cause, last_detail);
1320 }
1321
1322 fn take_actor(&mut self) -> SourceTaken<A> {
1328 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.source.take())) {
1329 Ok(Some(a)) => SourceTaken::Ready(a),
1330 Ok(None) => SourceTaken::Exhausted,
1331 Err(payload) => SourceTaken::FactoryPanicked(payload_text(payload)),
1332 }
1333 }
1334
1335 async fn run_one_generation(&mut self, actor: A) -> GenOutcome {
1337 publish_phase(&self.stop_tx, ActorPhase::Running);
1340 let ctx = ActorContext::new(
1341 self.system.clone(),
1342 self.id,
1343 self.name.clone(),
1344 self.ctl_tx.clone(),
1345 self.stop_tx.clone(),
1346 self.sig_tx.clone(),
1347 self.generation,
1348 self.restarts,
1349 );
1350 let gen = Generation {
1351 actor,
1352 ctx,
1353 mailbox: self.mailbox.clone(),
1354 sigbox: self.sigbox.clone(),
1355 slot_rx: self.slot_rx.clone(),
1356 stop_rx: self.stop_rx.clone(),
1357 };
1358 let (done_tx, done_rx) = oneshot::channel::<GenDone>();
1359 let jh = tokio::spawn(async move {
1360 let done = gen.run().await;
1361 let _ = done_tx.send(done);
1362 });
1363 *self.abort.lock().unwrap_or_else(|e| e.into_inner()) = Some(jh.abort_handle());
1366 let outcome = match done_rx.await {
1367 Ok(done) => GenOutcome::Exited(done),
1368 Err(_) => {
1369 match jh.await {
1371 Err(je) if je.is_panic() => GenOutcome::Panicked {
1372 detail: panic_detail(je),
1373 },
1374 _ => GenOutcome::Exited(GenDone {
1375 cause: StopCause::Requested,
1376 }),
1377 }
1378 }
1379 };
1380 *self.abort.lock().unwrap_or_else(|e| e.into_inner()) = None;
1381 outcome
1382 }
1383
1384 async fn wait_backoff(&mut self, delay: Duration) -> bool {
1388 let deadline = deadline_after(self.system.now(), delay);
1389 let clock = self.system.inner.clock.clone();
1390 if matches!(
1394 &*self.stop_rx.borrow_and_update(),
1395 ActorPhase::Stopped { .. }
1396 ) {
1397 return false;
1398 }
1399 tokio::select! {
1400 biased;
1401 _ = self.stop_rx.changed() => !matches!(
1402 &*self.stop_rx.borrow_and_update(),
1403 ActorPhase::Stopped { .. }
1404 ),
1405 _ = self.shutdown_rx.changed() => !self.is_shutdown(),
1406 _ = clock.sleep_until(deadline) => true,
1407 }
1408 }
1409
1410 fn is_shutdown(&self) -> bool {
1411 self.system.is_shutdown()
1412 }
1413}
1414
1415struct FinalizeGuard {
1422 system: ActorSystem,
1423 id: ActorId,
1424 name: Option<ActorName>,
1425 exit_tx: watch::Sender<bool>,
1426 stop_tx: Arc<watch::Sender<ActorPhase>>,
1428 done: bool,
1429}
1430
1431impl FinalizeGuard {
1432 fn finalize(&mut self, cause: StopCause, detail: Option<String>) {
1433 if self.done {
1434 return;
1435 }
1436 self.done = true;
1437 let inner = self.system.inner.clone();
1438 inner.registry.remove(&self.id);
1442 if let Some(n) = &self.name {
1443 inner.by_name.remove_if(n, |_, &cur| cur == self.id);
1444 }
1445 inner.cleanup_watcher(self.id);
1448 let terminated = Terminated {
1449 actor: self.id,
1450 name: self.name.clone(),
1451 cause,
1452 detail,
1453 };
1454 if let Some((_, watchers)) = inner.watched_by.remove(&self.id) {
1455 for w in watchers {
1456 inner.push_signal(w, ActorSignal::Terminated(terminated.clone()));
1457 }
1458 }
1459 tracing::debug!(actor = %self.id, %cause, "Actor 已最终退出");
1460 let _ = self.stop_tx.send_replace(ActorPhase::Stopped {
1464 cause,
1465 detail: terminated.detail.clone(),
1466 });
1467 let _ = self.exit_tx.send(true);
1468 }
1469}
1470
1471impl Drop for FinalizeGuard {
1472 fn drop(&mut self) {
1473 self.finalize(
1474 StopCause::Panicked,
1475 Some("监督任务异常退出(未捕获 panic 或 runtime 关闭)".to_string()),
1476 );
1477 }
1478}
1479
1480struct Generation<A: Actor> {
1485 actor: A,
1486 ctx: ActorContext<A::Message>,
1487 mailbox: Arc<tokio::sync::Mutex<mpsc::Receiver<A::Message>>>,
1488 sigbox: Arc<tokio::sync::Mutex<mpsc::Receiver<Signal>>>,
1489 slot_rx: Option<SlotReader<A::Message>>,
1490 stop_rx: watch::Receiver<ActorPhase>,
1491}
1492
1493impl<A: Actor> Generation<A> {
1494 async fn run(self) -> GenDone {
1495 let id = self.ctx.id();
1496 GENERATION_ACTOR.scope(id, self.run_scoped()).await
1499 }
1500
1501 async fn run_scoped(self) -> GenDone {
1503 let Generation {
1504 mut actor,
1505 mut ctx,
1506 mailbox,
1507 sigbox,
1508 mut slot_rx,
1509 mut stop_rx,
1510 } = self;
1511 let mut rx = mailbox.lock().await;
1513 let mut sig = sigbox.lock().await;
1514
1515 if ctx.restarts() > 0 {
1516 let attempt = ctx.restarts();
1518 actor.on_restart(attempt, &mut ctx).await;
1519 }
1520 actor.on_start(&mut ctx).await;
1521
1522 let cause;
1524 'gen: loop {
1525 if matches!(&*stop_rx.borrow_and_update(), ActorPhase::Stopped { .. }) {
1527 cause = StopCause::Requested;
1528 break 'gen;
1529 }
1530 while let Ok(s) = sig.try_recv() {
1533 if deliver_signal(&mut actor, &mut ctx, s).await == ActorAction::Stop {
1534 cause = StopCause::Requested;
1535 break 'gen;
1536 }
1537 }
1538 if let Some(frame) = slot_rx.as_mut().and_then(|r| r.take_latest()) {
1540 if actor.handle(frame, &mut ctx).await == ActorAction::Stop {
1541 cause = StopCause::Requested;
1542 break 'gen;
1543 }
1544 }
1545 tokio::select! {
1546 biased;
1547 _ = stop_rx.changed() => continue 'gen,
1549 s = sig.recv() => {
1551 if let Some(s) = s {
1552 if deliver_signal(&mut actor, &mut ctx, s).await == ActorAction::Stop {
1553 cause = StopCause::Requested;
1554 break 'gen;
1555 }
1556 } else {
1557 tracing::error!(actor = %ctx.id(), "信号通道意外关闭(理论不可达)");
1563 }
1564 }
1565 msg = rx.recv() => {
1567 let Some(mut msg) = msg else {
1568 cause = StopCause::MailboxClosed;
1569 break 'gen;
1570 };
1571 let mut drained = 1usize;
1572 loop {
1573 if actor.handle(msg, &mut ctx).await == ActorAction::Stop {
1574 cause = StopCause::Requested;
1575 break 'gen;
1576 }
1577 if drained >= SELF_BATCH_LIMIT {
1579 break;
1580 }
1581 while let Ok(s) = sig.try_recv() {
1585 if deliver_signal(&mut actor, &mut ctx, s).await == ActorAction::Stop {
1586 cause = StopCause::Requested;
1587 break 'gen;
1588 }
1589 }
1590 if matches!(&*stop_rx.borrow(), ActorPhase::Stopped { .. }) {
1594 cause = StopCause::Requested;
1595 break 'gen;
1596 }
1597 if let Some(frame) = slot_rx.as_mut().and_then(|r| r.take_latest()) {
1601 if actor.handle(frame, &mut ctx).await == ActorAction::Stop {
1602 cause = StopCause::Requested;
1603 break 'gen;
1604 }
1605 if matches!(&*stop_rx.borrow(), ActorPhase::Stopped { .. }) {
1608 cause = StopCause::Requested;
1609 break 'gen;
1610 }
1611 }
1612 drained += 1;
1613 match rx.try_recv() {
1614 Ok(m) => msg = m,
1615 Err(_) => break,
1616 }
1617 }
1618 }
1619 _ = wait_slot(&mut slot_rx) => {
1621 if let Some(frame) = slot_rx.as_mut().and_then(|r| r.take_latest()) {
1622 if actor.handle(frame, &mut ctx).await == ActorAction::Stop {
1623 cause = StopCause::Requested;
1624 break 'gen;
1625 }
1626 }
1627 }
1628 }
1629 }
1630
1631 drop(rx);
1633 drop(sig);
1634 actor.on_stop(&mut ctx).await;
1635 GenDone { cause }
1636 }
1637}
1638
1639async fn deliver_signal<A: Actor>(
1641 actor: &mut A,
1642 ctx: &mut ActorContext<A::Message>,
1643 signal: Signal,
1644) -> ActorAction {
1645 match signal {
1646 Signal::WatchdogFire { arm } => match ctx.take_watchdog_fire(arm) {
1650 Some(msg) => actor.handle(msg, ctx).await,
1651 None => ActorAction::Continue,
1652 },
1653 Signal::System(sig) => {
1654 let ActorSignal::Terminated(t) = &sig;
1662 ctx.reap_watch(t.actor);
1663 actor.on_signal(sig, ctx).await
1664 }
1665 }
1666}
1667
1668async fn wait_slot<M: ActorMsg>(slot_rx: &mut Option<SlotReader<M>>) -> bool {
1686 match slot_rx {
1687 Some(r) => {
1688 if r.changed().await.is_ok() {
1689 return true;
1690 }
1691 if r.take_latest().is_some() {
1692 return true;
1693 }
1694 std::future::pending::<()>().await;
1695 unreachable!("pending() 永不完成")
1696 }
1697 None => {
1698 std::future::pending::<()>().await;
1699 unreachable!("pending() 永不完成")
1700 }
1701 }
1702}
1703
1704#[cfg(test)]
1705mod tests {
1706 use super::*;
1707 use crate::ctx::ActorContext;
1708
1709 #[tokio::test]
1712 async fn reap_watch_clears_both_indexes() {
1713 let system = ActorSystem::new();
1714 let watcher = ActorId::new(900);
1715 let target = ActorId::new(901);
1716 system.inner.register_watch(watcher, target);
1717 assert_eq!(
1718 system.inner.watching.get(&watcher).map(|l| l.len()),
1719 Some(1),
1720 "登记后 watching 应持有目标"
1721 );
1722 assert_eq!(
1723 system.inner.watched_by.get(&target).map(|l| l.len()),
1724 Some(1),
1725 "登记后 watched_by 应持有 watcher"
1726 );
1727
1728 let (ctl_tx, _ctl_rx) = mpsc::channel::<u64>(1);
1729 let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
1730 let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(1);
1731 let mut ctx: ActorContext<u64> = ActorContext::new(
1732 system.clone(),
1733 watcher,
1734 None,
1735 ctl_tx,
1736 Arc::new(stop_tx),
1737 sig_tx,
1738 1,
1739 0,
1740 );
1741 ctx.reap_watch(target);
1742 ctx.reap_watch(target); assert!(
1745 system.inner.watching.get(&watcher).is_none(),
1746 "reap 后 watching 登记应被清除"
1747 );
1748 assert!(
1749 system.inner.watched_by.get(&target).is_none(),
1750 "reap 后 watched_by 登记应被清除"
1751 );
1752 system.shutdown().await;
1753 }
1754
1755 #[test]
1761 fn dropping_last_handle_without_shutdown_warns() {
1762 #[derive(Clone)]
1764 struct Buf(Arc<std::sync::Mutex<Vec<u8>>>);
1765 impl Buf {
1766 fn text(&self) -> String {
1767 String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
1768 }
1769 }
1770 impl std::io::Write for Buf {
1771 fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
1772 self.0.lock().unwrap().extend_from_slice(data);
1773 Ok(data.len())
1774 }
1775 fn flush(&mut self) -> std::io::Result<()> {
1776 Ok(())
1777 }
1778 }
1779 impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
1780 type Writer = Buf;
1781 fn make_writer(&'a self) -> Buf {
1782 self.clone()
1783 }
1784 }
1785
1786 struct Nop;
1787 impl Actor for Nop {
1788 type Message = u32;
1789 async fn handle(&mut self, _m: u32, _c: &mut ActorContext<u32>) -> ActorAction {
1790 ActorAction::Continue
1791 }
1792 }
1793
1794 let buf = Buf(Arc::new(std::sync::Mutex::new(Vec::new())));
1795 let subscriber = tracing_subscriber::fmt()
1796 .with_writer(buf.clone())
1797 .with_ansi(false)
1798 .with_max_level(tracing::Level::WARN)
1799 .finish();
1800 let rt = tokio::runtime::Builder::new_current_thread()
1801 .enable_all()
1802 .build()
1803 .unwrap();
1804
1805 tracing::subscriber::with_default(subscriber, || {
1806 rt.block_on(async {
1807 let system = ActorSystem::new();
1809 let leaked = system.spawn_anonymous(Nop).unwrap();
1810 drop(system);
1811
1812 let system = ActorSystem::new();
1814 let graceful = system.spawn_anonymous(Nop).unwrap();
1815 system.shutdown().await;
1816 drop(graceful);
1817 drop(system);
1818
1819 drop(leaked);
1820 });
1821 });
1822
1823 let logs = buf.text();
1824 assert_eq!(
1825 logs.matches("未调用 shutdown").count(),
1826 1,
1827 "仅未 shutdown 的丢弃应告警一次;实际日志:{logs}"
1828 );
1829 }
1830
1831 #[tokio::test]
1834 async fn wait_slot_on_closed_port_drains_last_frame_then_hangs() {
1835 let (w, r) = latest_slot::<u32>();
1836 w.send(7);
1837 drop(w);
1838
1839 let mut slot = Some(r);
1840 assert!(wait_slot(&mut slot).await, "关闭前最后一帧必须被补取");
1841 assert_eq!(slot.as_mut().unwrap().take_latest(), Some(7));
1842
1843 let hung = tokio::time::timeout(Duration::from_millis(50), wait_slot(&mut slot)).await;
1844 assert!(hung.is_err(), "空槽 + 写端消失必须永久挂起而非返回");
1845
1846 let mut none: Option<SlotReader<u32>> = None;
1847 let hung = tokio::time::timeout(Duration::from_millis(50), wait_slot(&mut none)).await;
1848 assert!(hung.is_err(), "无数据端口的 Actor 必须永久挂起");
1849 }
1850}