actor-lite 0.0.2

基于 tokio 的轻量 actor 抽象,提供命令通道、状态/进度广播和事件通知
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{Notify, broadcast, mpsc, watch};
use tracing::debug;
/// Actor 模型的核心 trait。
///
/// 实现此 trait 来定义一个 actor 的行为。每个 actor 有四个关联类型:
///
/// | 类型 | 说明 |
/// |------|------|
/// | [`Cmd`](Actor::Cmd) | 命令枚举,外部通过它向 actor 发送指令 |
/// | [`Event`](Actor::Event) | 事件类型,actor 对外广播的异步消息 |
/// | [`State`](Actor::State) | 低频状态,变化不频繁,可随时读取最新值 |
/// | [`Progress`](Actor::Progress) | 高频进度,适合进度条、实时指标等场景 |
///
/// # 生命周期
///
/// 1. 调用 [`Actor::spawn`] 启动 actor,得到 [`ActorHandle`]
/// 2. 通过 [`ActorHandle`] 发送命令、读取状态/进度、订阅事件
/// 3. 调用 [`ActorHandle::stop`] 或 drop handle 来停止 actor
///
/// # 示例
///
/// ```no_run
/// # use actor_lite::{Actor, ActorContext};
/// struct Counter {
///     target: u32,
/// }
///
/// enum CounterCmd {
///     Reset,
/// }
///
/// impl Actor 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)
///     }
///
///     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);
///             }
///         }
///     }
/// }
/// ```
pub trait Actor: Sized + Send + 'static {
    /// actor 命令枚举
    ///
    /// 例如:
    /// ```
    /// enum MyCmd {
    ///     Start,
    ///     Pause,
    ///     //...
    /// }
    /// ```
    type Cmd: Send + 'static;
    /// actor 里的事件结构体,需要实现`Clone`
    type Event: Clone + Send + 'static;
    /// actor 里的低频状态,如果不需要,用 `type State = ();`。
    type State: Clone + Send + Sync + 'static;
    /// actor 里的高频状态,如果没有高频进度时,用 `type Progress = ();`。
    type Progress: Clone + Send + Sync + 'static;

    /// actor 的命令通道容量
    const CMD_CAPACITY: usize = 16;
    /// actor 的事件通道容量
    const EVENT_CAPACITY: usize = 16;
    /// 创建 actor 的通道。
    /// ActorContext 是 actor 的后台端,ActorHandle 是 actor 的控制端。
    fn channel(
        init_state: Self::State,
        init_progress: Self::Progress,
    ) -> (ActorContext<Self>, ActorHandle<Self>) {
        let (cmd_tx, cmd_rx) = mpsc::channel(Self::CMD_CAPACITY);
        let (state_tx, state_rx) = watch::channel(init_state);
        let (event_tx, _) = broadcast::channel(Self::EVENT_CAPACITY);
        let (progress_tx, progress_rx) = watch::channel(init_progress);
        let cancel = CancelToken::new();

        let context_cancel = cancel.clone();

        let context = ActorContext {
            cmd_rx,
            event_tx: event_tx.clone(),
            state_tx,
            progress_tx,
            cancel: context_cancel,
        };
        let handle = ActorHandle {
            cmd_tx,
            event_tx,
            state_rx,
            progress_rx,
            cancel,
        };
        (context, handle)
    }

    fn init_state_and_progress(&self) -> (Self::State, Self::Progress);
    /// 启动 actor。
    ///
    /// 返回 actor 的控制端。
    ///
    ///  外部通过 [`ActorHandle`] 的方法发送命令、监听状态/进度、订阅事件。
    ///
    fn spawn(self) -> ActorHandle<Self> {
        let (init_state, init_progress) = self.init_state_and_progress();
        let (context, handle) = Self::channel(init_state, init_progress);
        tokio::spawn(self.run(context));
        debug!("spawn actor: {}", std::any::type_name::<Self>());
        handle
    }
    /// actor的主要循环
    ///
    /// 运行 actor 的主要逻辑。
    ///
    /// # 注意
    ///
    /// 接收后台端并自行决定循环和发送事件,更新状态的流程
    ///
    /// # 示例
    ///
    /// ```no_run
    ///  # use actor_lite::{Actor, ActorHandle, ActorContext};
    /// struct MyActor;
    /// impl Actor for MyActor {
    ///     type Cmd = ();
    ///     type Event = ();
    ///     type State = ();
    ///     type Progress = ();
    ///     fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
    ///         ((), ())
    ///     }
    ///     fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
    ///         let mut context = context;
    ///     async move {
    ///     
    ///         loop {
    ///         if let Some(cmd) = context.check_cmd() {
    ///             // ...处理命令
    ///             }
    ///          //...主要逻辑
    ///
    ///          //发送事件和进度,更新状态
    ///          context.send_event(());
    ///          context.update_progress(());
    ///          context.update_state(());
    ///       }
    ///     }
    ///   }
    /// }
    /// ```
    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static;
}
/// actor 的控制端。
///
/// 由 [`Actor::channel`] 创建,通常由外部控制方持有。
/// 用于发送命令、读取状态/进度、订阅事件,以及注册异步监听。
/// # 示例
///
/// ```no_run
/// # use actor_lite::{Actor, ActorHandle, ActorContext};
/// # struct MyActor;
/// # impl Actor for MyActor {
/// #    type Cmd = ();
/// #    type Event = ();
/// #    type State = ();
/// #    type Progress = ();
/// #    fn init_state_and_progress(&self) -> (Self::State, Self::Progress) {
/// #        ((), ())
/// #    }
/// #    fn run(self, context: ActorContext<Self>) -> impl Future<Output = ()> + Send + 'static {
/// #         async {}
/// #     }
/// # }
/// # async fn example() {
/// let (context, handle) = MyActor::channel( (), ());
///
/// handle.send_cmd(()).await.unwrap();
/// let state = handle.get_state();
///
/// let listener = handle.state_listen_async(|s| async move { });
/// listener.cancel();
/// # }
/// ```

pub struct ActorHandle<A: Actor> {
    cmd_tx: mpsc::Sender<A::Cmd>,
    state_rx: watch::Receiver<A::State>,
    event_tx: broadcast::Sender<A::Event>,
    progress_rx: watch::Receiver<A::Progress>,
    cancel: CancelToken,
}

impl<A: Actor> ActorHandle<A> {
    /// 向 actor 发送一条命令。
    pub async fn send_cmd(&self, cmd: A::Cmd) -> Result<(), mpsc::error::SendError<A::Cmd>> {
        self.cmd_tx.send(cmd).await
    }
    /// 获取 actor 的最新状态。
    pub fn get_state(&self) -> A::State {
        self.state_rx.borrow().to_owned()
    }
    /// 异步监听状态变化。
    ///
    /// 每次状态变化时会调用 `op`,传入最新状态。
    /// `op` 返回 `true` 继续监听,返回 `false` 停止。
    ///
    /// 返回的 [`ListenerHandle`] 被 drop 或调用 `cancel()` 时停止监听。

    pub fn state_listen_async<F, Fut>(&self, mut op: F) -> CancelToken
    where
        F: FnMut(A::State) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send,
    {
        let token = CancelToken::new();
        let wait_token = token.clone();
        let mut rx = self.state_rx.clone();
        let listen = async move {
            loop {
                tokio::select! {
                _ = wait_token.cancelled() => break,
                result = rx.changed() => {
                    match result {
                    Ok(())=>{
                        let state = rx.borrow_and_update().to_owned();
                         op(state).await;
                        }

                    Err(_) => break}
                }
                }
            }
        };
        tokio::spawn(listen);
        token
    }
    /// 获取 actor 的最新进度。
    pub fn get_progress(&self) -> A::Progress {
        self.progress_rx.borrow().to_owned()
    }
    pub fn progress_listen_async<F, Fut>(&self, mut op: F) -> CancelToken
    where
        F: FnMut(A::Progress) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send,
    {
        let token = CancelToken::new();
        let wait_token = token.clone();
        let mut rx = self.progress_rx.clone();
        let listen = async move {
            loop {
                tokio::select! {
                    _ = wait_token.cancelled() => break,
                    result = rx.changed() => {
                        match result {
                        Ok(())=>{
                            let progress = rx.borrow_and_update().to_owned();
                            op(progress).await;
                        }
                        Err(_) => break}
                    }// 幂等、同步、永不失败
                }
            }
        };
        tokio::spawn(listen);
        token
    }

    pub fn get_events_rx(&self) -> broadcast::Receiver<A::Event> {
        self.event_tx.subscribe()
    }
    pub fn events_listen_async<F, Fut>(&self, mut op: F) -> CancelToken
    where
        F: FnMut(A::Event) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send,
    {
        let mut rx = self.event_tx.subscribe();
        let token = CancelToken::new();
        let wait_token = token.clone();
        let listen = async move {
            loop {
                tokio::select! {
                    _ = wait_token.cancelled() => break,
                    result = rx.recv() => {
                        match result {
                            Ok(e) => { op(e).await; }
                            Err(broadcast::error::RecvError::Closed) => break,
                            Err(broadcast::error::RecvError::Lagged(n)) => {
                                debug!("事件监听落后 {n} 条");
                                continue;
                        }
                    }}
                }
            }
        };
        tokio::spawn(listen);
        token
    }
    pub fn stop(&self) {
        self.cancel.cancel();
    }
}
impl<A: Actor> Clone for ActorHandle<A> {
    fn clone(&self) -> Self {
        Self {
            cmd_tx: self.cmd_tx.clone(),
            state_rx: self.state_rx.clone(),
            event_tx: self.event_tx.clone(),
            progress_rx: self.progress_rx.clone(),
            cancel: self.cancel.clone(),
        }
    }
}
/// actor 的后台端。
///
/// 由 [`Actor::channel`] 创建,通常由后台任务持有。
/// 用于接收命令、更新状态/进度、广播事件。
pub struct ActorContext<A: Actor> {
    cmd_rx: mpsc::Receiver<A::Cmd>,
    state_tx: watch::Sender<A::State>,
    event_tx: broadcast::Sender<A::Event>,
    progress_tx: watch::Sender<A::Progress>,
    cancel: CancelToken,
}
impl<A: Actor> ActorContext<A> {
    /// 获取额外的事件发送端。
    pub fn get_events_clone(&self) -> broadcast::Sender<A::Event> {
        self.event_tx.clone()
    }
    /// 发送事件。
    pub fn send_event(&self, event: A::Event) {
        let _ = self.event_tx.send(event);
    }
    /// 更新状态。
    pub fn update_state(&self, state: A::State) {
        let _ = self.state_tx.send(state);
    }
    /// 更新进度。
    pub fn update_progress(&self, progress: A::Progress) {
        let _ = self.progress_tx.send(progress);
    }
    /// 阻塞等待命令。
    pub fn wait_for_cmd(&mut self) -> impl Future<Output = Option<A::Cmd>> {
        self.cmd_rx.recv()
    }
    /// 非阻塞检查命令。
    pub fn check_cmd(&mut self) -> Option<A::Cmd> {
        self.cmd_rx.try_recv().ok()
    }

    pub fn cancel_clone(&self) -> CancelToken {
        self.cancel.clone()
    }
}
/// 取消信号。
///
/// 可在多个任务间 clone 共享。任意一份调用 [`CancelToken::cancel`],
/// 所有通过 [`CancelToken::cancelled`] 等待的任务都会收到通知。
/// `cancel` 是幂等的。
/// ...
/// # 注意
///
/// `CancelToken` 是 `Clone` 的,clone 出来的所有副本共享同一个取消信号。
/// 任意一份 `cancel()` 都会让所有副本的 `cancelled()` 返回。
#[derive(Clone, Debug)]
pub struct CancelToken {
    cancelled: Arc<AtomicBool>,
    notify: Arc<Notify>,
}

impl CancelToken {
    pub fn new() -> Self {
        Self {
            cancelled: Arc::new(AtomicBool::new(false)),
            notify: Arc::new(Notify::new()),
        }
    }
    /// 检查取消信号。
    pub fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::Acquire)
    }
    /// 等待取消信号。
    pub async fn cancelled(&self) {
        if self.is_cancelled() {
            return;
        }
        let notified = self.notify.notified();
        if self.is_cancelled() {
            return;
        }
        notified.await;
    }
    /// 发送取消信号。
    pub fn cancel(&self) {
        if !self.cancelled.swap(true, Ordering::AcqRel) {
            self.notify.notify_waiters();
        }
    }
}