pub trait ActorCore: Sized {
type Cmd: Send + 'static;
type Event: Clone + Send + 'static;
type State: Clone + Send + Sync + 'static;
type Progress: Clone + Send + Sync + 'static;
const EVENT_CAPACITY: usize = 32;
// Required method
fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
// Provided method
fn channel(
init_state: Self::State,
init_progress: Self::Progress,
) -> (ActorContext<Self>, ActorHandle<Self>) { ... }
}Expand description
Actor 的数据面 trait。
ActorCore 只定义 actor「有什么」,不定义「怎么跑」。每个 actor 有四个关联类型:
| 类型 | 说明 |
|---|---|
Cmd | 命令枚举,外部通过它向 actor 发送指令 |
Event | 事件类型,actor 对外广播的异步消息 |
State | 低频状态,变化不频繁,可随时读取最新值 |
Progress | 高频进度,适合进度条、实时指标等场景 |
实现之后,ActorCore::channel 会给你两端:ActorContext(后台端,收命令、更新状态、
广播事件)和 ActorHandle(控制端,发命令、读状态、订阅事件)。
§怎么跑
「怎么跑」由壳 trait 决定,ActorCore 自己不关心:
AsyncActor:run返回一个 future,AsyncActor::spawn用tokio::spawn起任务;- 也可以完全不用壳:自己调用
ActorCore::channel,再把ActorContext交给任意 runtime 或线程驱动 —— 本 crate 不规定 actor 怎么运行。
§生命周期
- 启动 actor(如
AsyncActor::spawn),得到ActorHandle - 通过
ActorHandle发送命令、读取状态/进度、订阅事件 - 调用
ActorHandle::stop显式停止;所有 handle 都被 drop 后命令通道关闭,run里的等待会返回None,actor 自然退出
§与其他 trait 的关系
0.1.0 起原 Actor 拆成两层:关联类型与初始化留在 ActorCore,
run/spawn 移到壳 trait(AsyncActor)。因此定义一个 actor 需要两段 impl。
§示例
struct Counter {
target: u32,
}
enum CounterCmd {
Reset,
}
impl ActorCore for Counter {
type Cmd = CounterCmd;
type Event = u32;
type State = u32;
type Progress = f32;
fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
(0, 0.0)
}
}
impl AsyncActor for Counter {
fn run(self, context: ActorContext<Self>) -> impl std::future::Future<Output = ()> + Send + 'static {
let mut context = context;
async move {
let mut count = 0u32;
loop {
if let Some(cmd) = context.check_cmd() {
match cmd {
CounterCmd::Reset => {
count = 0;
context.update_state(count);
context.update_progress(0.0);
}
}
}
if count >= self.target {
break;
}
count += 1;
context.update_state(count);
context.update_progress(count as f32 / self.target as f32);
context.send_event(count);
}
}
}
}Provided Associated Constants§
Sourceconst EVENT_CAPACITY: usize = 32
const EVENT_CAPACITY: usize = 32
actor 的事件通道容量
Required Associated Types§
Required Methods§
fn init_state_and_progress(&self) -> (Self::State, Self::Progress)
Provided Methods§
Sourcefn channel(
init_state: Self::State,
init_progress: Self::Progress,
) -> (ActorContext<Self>, ActorHandle<Self>)
fn channel( init_state: Self::State, init_progress: Self::Progress, ) -> (ActorContext<Self>, ActorHandle<Self>)
创建 actor 的通道。 ActorContext 是 actor 的后台端,ActorHandle 是 actor 的控制端。
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".