Skip to main content

Crate wordval_actor

Crate wordval_actor 

Source
Expand description

wordval-actor。

高性能单机内存 Actor 框架:

场景机制
遥测上行(100–1000Hz/机)MailboxPolicy::LossTolerant 数据端口:单槽 latest-value-wins,内存 O(1) 与帧率解耦
指令下行(不可丢、要 ACK)有界控制通道背压 + ActorRef::ask(关联应答 + 超时)
失控保护(链路丢失 → 返航)ActorContext::watchdog 一等滑动看门狗 + 控制面偏向(永不被遥测饿死)
多机集群 HUDTopic 广播扇出 + SnapshotTopic 零拷贝快照拉取
整机可靠性RestartPolicy 监督重启/指数退避 + ActorContext::watch 死亡通知

§快速上手

use wordval_actor::{Actor, ActorAction, ActorContext, ActorSystem, MailboxPolicy};

struct Counter(u64);

impl Actor for Counter {
    type Message = u64;
    const POLICY: MailboxPolicy = MailboxPolicy::Reliable { capacity: 64 };

    async fn handle(&mut self, n: u64, _ctx: &mut ActorContext<u64>) -> ActorAction {
        self.0 += n;
        ActorAction::Continue
    }
}

let system = ActorSystem::new();
let counter = system.spawn_named("counter", Counter(0)).unwrap();
counter.send(7).await.unwrap();
counter.try_send(3).unwrap();

§自调用约束(在 Actor 内部调用系统 API)

凡需等待目标 Actor 事件循环推进的 API —— ActorRef::ask / ask_send / ActorSystem::stop_and_wait / stop_and_wait_timeout —— 在目标 Actor 自身的 handle 内对自身调用会立即 panic(自调用防护:这类 调用必然死锁或等满超时)。Actor 内部请求自身停止请用 ActorContext::stop 并返回 ActorAction::Stop。

ActorSystem::shutdown 是唯一例外:在 Actor 内调用被支持 —— 调用者 自身被排除出等待集(不白等宽限期、不被误判超时强制注销),其余 Actor 照常等待;调用者在 handle 返回后优雅退出。

以上识别基于世代任务的 task-local 标记,不跨 tokio::spawn 继承: 把调用转手给派生任务的写法不受防护,需自行避免。

§链路会话:收原始帧 → 解码 → 写数据端口

解码任务(非 Actor)以任意速率覆盖写遥测帧;LinkSession 事件循环永远只消费最新帧,积压不会膨胀:

use wordval_actor::{Actor, ActorAction, ActorContext, ActorError, ActorSystem, MailboxPolicy};

struct LinkSession;
#[derive(Default)]
struct TelemetryFrame { attitude: [f32; 4] }

impl Actor for LinkSession {
    type Message = TelemetryFrame;
    const POLICY: MailboxPolicy = MailboxPolicy::LossTolerant { capacity: 32 };

    async fn handle(&mut self, frame: TelemetryFrame, _ctx: &mut ActorContext<TelemetryFrame>) -> ActorAction {
        let _ = frame; // 实际为覆盖写入 VehicleState 的数据端口
        ActorAction::Continue
    }
}

let session = system.spawn_named("link-uav1", LinkSession)?;
let mut writer = session.data_port().unwrap(); // 交给解码任务
tokio::spawn(async move {
    loop {
        let raw = read_modem().await;
        writer.send(decode(raw)); // 覆盖式,永不阻塞
    }
});

§机体状态机:心跳看门狗 → 超时自动返航

use wordval_actor::{Actor, ActorAction, ActorContext};
use std::time::Duration;

struct VehicleState;
struct Telemetry;
enum VehicleMsg { Telemetry(Telemetry), LinkLost }

impl Actor for VehicleState {
    type Message = VehicleMsg;

    async fn handle(&mut self, msg: VehicleMsg, ctx: &mut ActorContext<VehicleMsg>) -> ActorAction {
        match msg {
            VehicleMsg::Telemetry(t) => {
                // 每帧一行滑动重置 3s 看门狗:首次帧自动武装,
                // 触发后再次调用自动再武装,无需业务侧管理句柄
                ctx.watchdog(Duration::from_secs(3), VehicleMsg::LinkLost);
                self.apply(t);
            }
            VehicleMsg::LinkLost => {
                self.failsafe_rtl(); // 失控保护:发送返航指令
            }
        }
        ActorAction::Continue
    }
}

看门狗度量处理节奏而非到达节奏:喂狗在 handle 内,timeout 内没有任何消息处理到喂狗点即触发(邮箱积压、慢处理、调度停顿都 算数)——阈值得按最坏处理时延选取;监督重启的新世代不自动武装, 保护自首帧喂狗起恢复。详见 ActorContext::watchdog。

§机队监督:watch 全部机体,接收终止告警

use wordval_actor::{Actor, ActorAction, ActorContext, ActorSignal, SpawnOptions};

struct FleetSupervisor;
struct FleetMsg;

impl Actor for FleetSupervisor {
    type Message = FleetMsg;

    async fn handle(&mut self, _msg: FleetMsg, _ctx: &mut ActorContext<FleetMsg>) -> ActorAction {
        ActorAction::Continue
    }

    async fn on_signal(&mut self, sig: ActorSignal, _ctx: &mut ActorContext<FleetMsg>) -> ActorAction {
        if let ActorSignal::Terminated(t) = sig {
            tracing::info!("机体 {:?} 已终止,原因 {}", t.name, t.cause);
        }
        ActorAction::Continue
    }
}

let opts = SpawnOptions::named("fleet");
// spawn 后在 on_start 中逐个 ctx.watch(vehicle_ref)

§Cargo 特性

  • wordval-plugin(默认开启):wordval 插件系统集成 (ActorPlugin / actor_system / try_actor_system), 会引入 wordval-core 依赖。独立使用本 crate 时可 default-features = false 裁掉该集成及其依赖子图。

Re-exports§

pub use addr::ActorId;
pub use addr::ActorName;
pub use actor::Actor;
pub use actor::ActorAction;
pub use ctx::ActorContext;
pub use mailbox::MailboxPolicy;
pub use mailbox::SlotReader;
pub use mailbox::SlotWriter;
pub use mailbox::DEFAULT_MAILBOX_CAPACITY;
pub use msg::ActorMsg;
pub use msg::ActorPhase;
pub use msg::ActorSignal;
pub use msg::StopCause;
pub use msg::Terminated;
pub use plugin::actor_system;
pub use plugin::try_actor_system;
pub use plugin::ActorPlugin;
pub use refs::ActorRef;
pub use refs::AskError;
pub use refs::Reply;
pub use system::ActorConfig;
pub use system::ActorError;
pub use system::ActorSystem;
pub use system::RestartPolicy;
pub use system::SpawnOptions;
pub use timer::Clock;
pub use timer::TimerHandle;
pub use timer::TokioClock;
pub use topic::SnapshotReader;
pub use topic::SnapshotTopic;
pub use topic::Subscriber;
pub use topic::Topic;

Modules§

actor
Actor trait —— 消息驱动的生命周期抽象。
addr
Actor 寻址 —— 唯一 ID 与命名标识。
ctx
运行时上下文 —— Actor 的自引用能力(定时器 / watch / 停止 / 子 Actor)。
mailbox
邮箱层 —— 双通道模型:有界控制通道 + 单槽数据通道。
msg
消息定义 —— Actor 消息契约与系统信号。
plugin
ActorPlugin —— wordval 插件系统集成。
refs
类型化引用 —— ActorRef<M>:热路径零类型擦除的 Actor 句柄。
system
ActorSystem —— 命名注册表、监督者与优雅关闭。
timer
定时器 —— 全局单一驱动任务,所有 schedule_* 复用一条 tokio 任务。
topic
Topic —— 广播扇出与快照拉取(多机集群 HUD 场景)。