Skip to main content

wordval_actor/
lib.rs

1//! wordval-actor。
2//!
3//! 高性能单机内存 Actor 框架:
4//!
5//! | 场景 | 机制 |
6//! |---|---|
7//! | 遥测上行(100–1000Hz/机) | [`MailboxPolicy::LossTolerant`] 数据端口:单槽 latest-value-wins,内存 O(1) 与帧率解耦 |
8//! | 指令下行(不可丢、要 ACK) | 有界控制通道背压 + [`ActorRef::ask`](关联应答 + 超时) |
9//! | 失控保护(链路丢失 → 返航) | [`ActorContext::watchdog`] 一等滑动看门狗 + 控制面偏向(永不被遥测饿死) |
10//! | 多机集群 HUD | [`Topic`] 广播扇出 + [`SnapshotTopic`] 零拷贝快照拉取 |
11//! | 整机可靠性 | [`RestartPolicy`] 监督重启/指数退避 + [`ActorContext::watch`] 死亡通知 |
12//!
13//! # 快速上手
14//!
15//! ```
16//! use wordval_actor::{Actor, ActorAction, ActorContext, ActorSystem, MailboxPolicy};
17//!
18//! struct Counter(u64);
19//!
20//! impl Actor for Counter {
21//!     type Message = u64;
22//!     const POLICY: MailboxPolicy = MailboxPolicy::Reliable { capacity: 64 };
23//!
24//!     async fn handle(&mut self, n: u64, _ctx: &mut ActorContext<u64>) -> ActorAction {
25//!         self.0 += n;
26//!         ActorAction::Continue
27//!     }
28//! }
29//!
30//! # async fn run() {
31//! let system = ActorSystem::new();
32//! let counter = system.spawn_named("counter", Counter(0)).unwrap();
33//! counter.send(7).await.unwrap();
34//! counter.try_send(3).unwrap();
35//! # system.shutdown().await;
36//! # }
37//! ```
38//!
39//! ## 自调用约束(在 Actor 内部调用系统 API)
40//!
41//! 凡需等待目标 Actor 事件循环推进的 API —— [`ActorRef::ask`] /
42//! [`ask_send`](ActorRef::ask_send) / [`ActorSystem::stop_and_wait`] /
43//! [`stop_and_wait_timeout`](ActorSystem::stop_and_wait_timeout) —— 在目标
44//! Actor 自身的 `handle` 内对自身调用会**立即 panic**(自调用防护:这类
45//! 调用必然死锁或等满超时)。Actor 内部请求自身停止请用
46//! [`ActorContext::stop`] 并返回 [`ActorAction::Stop`]。
47//!
48//! [`ActorSystem::shutdown`] 是唯一例外:在 Actor 内调用被支持 —— 调用者
49//! 自身被排除出等待集(不白等宽限期、不被误判超时强制注销),其余 Actor
50//! 照常等待;调用者在 `handle` 返回后优雅退出。
51//!
52//! 以上识别基于世代任务的 task-local 标记,**不跨 `tokio::spawn` 继承**:
53//! 把调用转手给派生任务的写法不受防护,需自行避免。
54//!
55//! ## 链路会话:收原始帧 → 解码 → 写数据端口
56//!
57//! 解码任务(非 Actor)以任意速率覆盖写遥测帧;`LinkSession`
58//! 事件循环永远只消费最新帧,积压不会膨胀:
59//!
60//! ```
61//! use wordval_actor::{Actor, ActorAction, ActorContext, ActorError, ActorSystem, MailboxPolicy};
62//!
63//! struct LinkSession;
64//! #[derive(Default)]
65//! struct TelemetryFrame { attitude: [f32; 4] }
66//!
67//! impl Actor for LinkSession {
68//!     type Message = TelemetryFrame;
69//!     const POLICY: MailboxPolicy = MailboxPolicy::LossTolerant { capacity: 32 };
70//!
71//!     async fn handle(&mut self, frame: TelemetryFrame, _ctx: &mut ActorContext<TelemetryFrame>) -> ActorAction {
72//!         let _ = frame; // 实际为覆盖写入 VehicleState 的数据端口
73//!         ActorAction::Continue
74//!     }
75//! }
76//!
77//! # async fn read_modem() -> Vec<u8> { Vec::new() }
78//! # fn decode(raw: Vec<u8>) -> TelemetryFrame { let _ = raw; TelemetryFrame::default() }
79//! # fn demo(system: ActorSystem) -> Result<(), ActorError> {
80//! let session = system.spawn_named("link-uav1", LinkSession)?;
81//! let mut writer = session.data_port().unwrap(); // 交给解码任务
82//! tokio::spawn(async move {
83//!     loop {
84//!         let raw = read_modem().await;
85//!         writer.send(decode(raw)); // 覆盖式,永不阻塞
86//!     }
87//! });
88//! # Ok(())
89//! # }
90//! ```
91//!
92//! ## 机体状态机:心跳看门狗 → 超时自动返航
93//!
94//! ```
95//! use wordval_actor::{Actor, ActorAction, ActorContext};
96//! use std::time::Duration;
97//!
98//! struct VehicleState;
99//! struct Telemetry;
100//! enum VehicleMsg { Telemetry(Telemetry), LinkLost }
101//!
102//! impl Actor for VehicleState {
103//!     type Message = VehicleMsg;
104//!
105//!     async fn handle(&mut self, msg: VehicleMsg, ctx: &mut ActorContext<VehicleMsg>) -> ActorAction {
106//!         match msg {
107//!             VehicleMsg::Telemetry(t) => {
108//!                 // 每帧一行滑动重置 3s 看门狗:首次帧自动武装,
109//!                 // 触发后再次调用自动再武装,无需业务侧管理句柄
110//!                 ctx.watchdog(Duration::from_secs(3), VehicleMsg::LinkLost);
111//!                 self.apply(t);
112//!             }
113//!             VehicleMsg::LinkLost => {
114//!                 self.failsafe_rtl(); // 失控保护:发送返航指令
115//!             }
116//!         }
117//!         ActorAction::Continue
118//!     }
119//! }
120//! # impl VehicleState {
121//! #     fn apply(&mut self, _t: Telemetry) {}
122//! #     fn failsafe_rtl(&mut self) {}
123//! # }
124//! ```
125//!
126//! 看门狗度量**处理节奏**而非到达节奏:喂狗在 `handle` 内,`timeout`
127//! 内没有任何消息处理到喂狗点即触发(邮箱积压、慢处理、调度停顿都
128//! 算数)——阈值得按最坏处理时延选取;监督重启的新世代不自动武装,
129//! 保护自首帧喂狗起恢复。详见 [`ActorContext::watchdog`]。
130//!
131//! ## 机队监督:watch 全部机体,接收终止告警
132//!
133//! ```
134//! use wordval_actor::{Actor, ActorAction, ActorContext, ActorSignal, SpawnOptions};
135//!
136//! struct FleetSupervisor;
137//! struct FleetMsg;
138//!
139//! impl Actor for FleetSupervisor {
140//!     type Message = FleetMsg;
141//!
142//!     async fn handle(&mut self, _msg: FleetMsg, _ctx: &mut ActorContext<FleetMsg>) -> ActorAction {
143//!         ActorAction::Continue
144//!     }
145//!
146//!     async fn on_signal(&mut self, sig: ActorSignal, _ctx: &mut ActorContext<FleetMsg>) -> ActorAction {
147//!         if let ActorSignal::Terminated(t) = sig {
148//!             tracing::info!("机体 {:?} 已终止,原因 {}", t.name, t.cause);
149//!         }
150//!         ActorAction::Continue
151//!     }
152//! }
153//!
154//! let opts = SpawnOptions::named("fleet");
155//! // spawn 后在 on_start 中逐个 ctx.watch(vehicle_ref)
156//! # let _ = opts;
157//! ```
158
159//! ## Cargo 特性
160//!
161//! - `wordval-plugin`(默认开启):wordval 插件系统集成
162//!   (`ActorPlugin` / `actor_system` / `try_actor_system`),
163//!   会引入 `wordval-core` 依赖。独立使用本 crate 时可
164//!   `default-features = false` 裁掉该集成及其依赖子图。
165
166#![forbid(unsafe_code)]
167
168pub mod addr;
169pub mod actor;
170pub mod ctx;
171pub mod mailbox;
172pub mod msg;
173#[cfg(feature = "wordval-plugin")]
174pub mod plugin;
175pub mod refs;
176pub mod system;
177pub mod timer;
178pub mod topic;
179
180pub use addr::{ActorId, ActorName};
181pub use actor::{Actor, ActorAction};
182pub use ctx::ActorContext;
183pub use mailbox::{MailboxPolicy, SlotReader, SlotWriter, DEFAULT_MAILBOX_CAPACITY};
184pub use msg::{ActorMsg, ActorPhase, ActorSignal, StopCause, Terminated};
185#[cfg(feature = "wordval-plugin")]
186pub use plugin::{actor_system, try_actor_system, ActorPlugin};
187pub use refs::{ActorRef, AskError, Reply};
188pub use system::{ActorConfig, ActorError, ActorSystem, RestartPolicy, SpawnOptions};
189pub use timer::{Clock, TimerHandle, TokioClock};
190pub use topic::{SnapshotReader, SnapshotTopic, Subscriber, Topic};