Section 9 of 25
Actors: slices with state
Contents
9.1. When to use an actor
Use an actor only when all three are true:
- the state lives longer than one command call;
- several sources change it concurrently (the window, processes, timers, the network);
- the window watches it live.
In every other case, use a plain service.rs. Not every NgRx feature needs effects, and not every SLAT slice needs an actor.
| Candidate | 1 | 2 | 3 | Verdict |
|---|---|---|---|---|
| an agent run with steps and processes | yes | window, processes, timers | yes | actor |
| a live recording | yes | window, audio device, timer | yes | actor |
| a conversation with a model | yes | window, model process, remote device | yes | actor |
| generating a draft once and returning it | yes | window (start/stop) | no, one result | service + kit::Jobs |
| a cache of model prices | yes | none | no | a field of the slice's service |
9.2. Files
core/src/<slice>/actor/
mod.rs pub use Deps, Handle, Msg, Snapshot, spawn
msg.rs enum Msg: everything that can happen (from the window, a process, a timer)
state.rs struct State: the only place where the state exists
update.rs fn update(state: &mut State, msg: Msg) -> Vec<Effect>; pure, no I/O, no async
effect.rs enum Effect + async fn execute(effect, &Deps) -> Option<Msg>
run.rs the loop: recv → update → execute → snapshot.send; started with tokio::spawn
handle.rs struct Handle { tx, snapshot }: send(), current(), subscribe(); ask() with a oneshot only when a caller needs a reply
snapshot.rs struct Snapshot: what the window sees; From<&State>
9.3. The contract
updateis pure. It receives the state and a message and returns a list of effects. Every business rule about that state can be tested without tokio, processes or a database.- An effect that produces a result returns it as a new
Msg. The actor never waits for a long effect inside its loop. A long effect goes totokio::spawn, and its result comes back through the mailbox. - Cancellation is a message with a generation, not a flag:
Msg::Cancel { generation }. The state holdsgeneration: u64, and a late answer with an old generation is ignored inupdate. A globalAtomicBoolleaks between operations; a generation cannot. - A result is a value:
enum Outcome<T> { Done(T), Cancelled }, neverErr(Cancelled). Cancelling is something the user asked for, not a failure. - A time limit is
Effect::StartTimer, and its end isMsg::TimedOut. Killing a process after a time limit is done by a driver. A baretokio::time::timeoutcancels the Rust future, not the operating-system process. - No
std::sync::Mutexinside an actor. Its state has one owner, so it needs no lock. - One actor per instance of state: one per run, one per conversation. The registry of live instances is a small actor of its own, or a service with a map of handles.
9.4. A complete small actor
A recording actor that starts a recorder process, enforces a time limit, and can be stopped (the file is kept) or cancelled (the file is discarded). All type and function names are illustrative.
msg.rs:
pub enum Msg {
Start { title: String, limit: Duration },
Started { generation: u64, pid: ProcessId },
Level { generation: u64, db: f32 },
Stop { generation: u64 },
Cancel { generation: u64 },
TimedOut { generation: u64 },
Ended { generation: u64, outcome: Outcome<RecordingFile> },
Failed { generation: u64 },
}
state.rs:
#[derive(Default)]
pub struct State {
pub generation: u64,
pub phase: Phase,
pub title: Option<String>,
pub level_db: Option<f32>,
}
#[derive(Default, Clone, PartialEq, Debug)]
pub enum Phase {
#[default]
Idle,
Starting,
Recording { pid: ProcessId },
Stopping,
Saved(RecordingFile),
Cancelled,
Failed,
}
impl Phase {
pub fn is_active(&self) -> bool {
matches!(self, Phase::Starting | Phase::Recording { .. } | Phase::Stopping)
}
}
effect.rs:
pub enum Effect {
SpawnRecorder { generation: u64, title: String },
StopRecorder { generation: u64, pid: ProcessId },
CancelRecorder { generation: u64, pid: ProcessId },
StartTimer { generation: u64, after: Duration },
Persist { generation: u64, file: RecordingFile },
}
#[derive(Clone)]
pub struct Deps {
pub recorder: drivers::recorder::Recorder,
pub recordings: Arc<RecordingStore>,
}
pub async fn execute(effect: Effect, deps: &Deps) -> Option<Msg> {
match effect {
Effect::SpawnRecorder { generation, title } => Some(match deps.recorder.start(&title).await {
Ok(pid) => Msg::Started { generation, pid },
Err(_) => Msg::Failed { generation },
}),
Effect::StopRecorder { generation, pid } => Some(match deps.recorder.stop(pid).await {
Ok(file) => Msg::Ended { generation, outcome: Outcome::Done(file) },
Err(_) => Msg::Failed { generation },
}),
Effect::CancelRecorder { generation, pid } => Some(match deps.recorder.discard(pid).await {
Ok(()) => Msg::Ended { generation, outcome: Outcome::Cancelled },
Err(_) => Msg::Failed { generation },
}),
Effect::StartTimer { generation, after } => {
tokio::time::sleep(after).await;
Some(Msg::TimedOut { generation })
}
Effect::Persist { generation, file } => match deps.recordings.save(&file).await {
Ok(()) => None,
Err(_) => Some(Msg::Failed { generation }),
},
}
}
update.rs:
pub fn update(state: &mut State, msg: Msg) -> Vec<Effect> {
match msg {
Msg::Start { title, limit } if !state.phase.is_active() => {
state.generation += 1;
state.phase = Phase::Starting;
state.title = Some(title.clone());
vec![
Effect::SpawnRecorder { generation: state.generation, title },
Effect::StartTimer { generation: state.generation, after: limit },
]
}
Msg::Started { generation, pid } if generation == state.generation => {
state.phase = Phase::Recording { pid };
vec![]
}
Msg::Level { generation, db } if generation == state.generation => {
state.level_db = Some(db);
vec![]
}
Msg::Stop { generation } | Msg::TimedOut { generation }
if generation == state.generation =>
{
match state.phase.clone() {
Phase::Recording { pid } => {
state.phase = Phase::Stopping;
vec![Effect::StopRecorder { generation, pid }]
}
_ => vec![],
}
}
Msg::Cancel { generation } if generation == state.generation => {
match state.phase.clone() {
Phase::Recording { pid } => {
state.phase = Phase::Stopping;
vec![Effect::CancelRecorder { generation, pid }]
}
_ => vec![],
}
}
Msg::Ended { generation, outcome } if generation == state.generation => {
state.level_db = None;
match outcome {
Outcome::Done(file) => {
state.phase = Phase::Saved(file.clone());
vec![Effect::Persist { generation, file }]
}
Outcome::Cancelled => {
state.phase = Phase::Cancelled;
vec![]
}
}
}
Msg::Failed { generation } if generation == state.generation => {
state.phase = Phase::Failed;
state.level_db = None;
vec![]
}
_ => vec![],
}
}
A new recording may start whenever nothing is in progress, including after an earlier one was saved or cancelled. The last arm is the point of generations: a Level, TimedOut or Ended message from an earlier recording arrives with an old generation and changes nothing.
A Start while a recording is in progress changes nothing either. The window does not offer Start then, because the snapshot says a recording is active; a caller that needs an answer uses ask with a oneshot (9.2). Failed is the end when the recorder could not start, stop or save. Before a driver returns that error, it has already killed the process and proved it dead (17.5), so Failed never leaves a recorder running.
run.rs:
pub fn spawn(deps: Deps) -> Handle {
let (tx, mut rx) = mpsc::channel(64);
let (snapshot_tx, snapshot_rx) = watch::channel(Snapshot::default());
let mailbox = tx.downgrade();
tokio::spawn(async move {
let mut state = State::default();
while let Some(msg) = rx.recv().await {
for effect in update(&mut state, msg) {
let deps = deps.clone();
let mailbox = mailbox.clone();
tokio::spawn(async move {
if let Some(next) = execute(effect, &deps).await {
if let Some(mailbox) = mailbox.upgrade() {
let _ = mailbox.send(next).await;
}
}
});
}
let next = Snapshot::from(&state);
snapshot_tx.send_if_modified(|current| {
let changed = *current != next;
if changed {
*current = next;
}
changed
});
}
});
Handle::new(tx, snapshot_rx)
}
handle.rs:
#[derive(Clone)]
pub struct Handle {
tx: mpsc::Sender<Msg>,
snapshot: watch::Receiver<Snapshot>,
}
impl Handle {
pub(super) fn new(tx: mpsc::Sender<Msg>, snapshot: watch::Receiver<Snapshot>) -> Self {
Self { tx, snapshot }
}
pub async fn send(&self, msg: Msg) -> Result<(), ActorGone> {
self.tx.send(msg).await.map_err(|_| ActorGone)
}
pub fn current(&self) -> Snapshot {
self.snapshot.borrow().clone()
}
pub fn subscribe(&self) -> watch::Receiver<Snapshot> {
self.snapshot.clone()
}
}
snapshot.rs:
#[derive(Clone, Default, PartialEq, Debug)]
pub struct Snapshot {
pub generation: u64,
pub phase: Phase,
pub title: Option<String>,
pub level_db: Option<i8>,
}
impl From<&State> for Snapshot {
fn from(state: &State) -> Self {
Self {
generation: state.generation,
phase: state.phase.clone(),
title: state.title.clone(),
level_db: state.level_db.map(|db| db.round() as i8),
}
}
}
mod.rs:
mod effect;
mod handle;
mod msg;
mod run;
mod snapshot;
mod state;
mod update;
pub use effect::Deps;
pub use handle::Handle;
pub use msg::Msg;
pub use run::spawn;
pub use snapshot::Snapshot;
The window takes the generation it needs for Stop and Cancel from the snapshot. The loop sends a snapshot only when it changed (send_if_modified), and the level is rounded to whole decibels, so a meter that reports every few milliseconds does not turn every report into an event for the window. A value that changes faster than the window can draw belongs to a stream (8.4), not to a snapshot.
The loop keeps only a weak sender for the results of its own effects. When the last Handle is dropped, recv returns None and the actor ends instead of waiting forever.
When the order of effects matters (persist before notify, for example), execute those effects in sequence inside one spawned task instead of one task per effect. The rule is only that the loop itself never waits.
9.5. Testing an actor
Most tests never start the actor. They call update directly:
#[test]
fn a_late_timeout_from_an_earlier_recording_changes_nothing() {
let mut state = State::default();
update(&mut state, Msg::Start { title: "first".into(), limit: MINUTE });
update(&mut state, Msg::Ended { generation: 1, outcome: Outcome::Cancelled });
update(&mut state, Msg::Start { title: "second".into(), limit: MINUTE });
update(&mut state, Msg::Started { generation: 2, pid: PID });
let effects = update(&mut state, Msg::TimedOut { generation: 1 });
assert!(effects.is_empty());
assert_eq!(state.phase, Phase::Recording { pid: PID });
}
A few tests drive the whole actor through its Handle with tokio::time::pause(), a data seam or a fake driver (14.2), and assertions on the sequence of snapshots.