Sezione 9 di 25

Attori: slice con stato

Indice

9.1. Quando usare un attore

Si usa un attore solo quando tutte e tre le condizioni sono vere:

  1. lo stato vive più a lungo di una singola chiamata di comando;
  2. più fonti lo modificano in modo concorrente (la finestra, i processi, i timer, la rete);
  3. la finestra lo osserva in tempo reale.

In tutti gli altri casi si usa un semplice service.rs. Non ogni feature NgRx ha bisogno di effect, e non ogni slice SLAT ha bisogno di un attore.

Candidato 1 2 3 Verdetto
un'esecuzione di agenti con passi e processi sì finestra, processi, timer sì attore
una registrazione in corso sì finestra, dispositivo audio, timer sì attore
una conversazione con un modello sì finestra, processo del modello, dispositivo remoto sì attore
generare una bozza una volta e restituirla sì finestra (avvio/stop) no, un solo risultato servizio + kit::Jobs
una cache dei prezzi dei modelli sì nessuna no un campo del servizio della slice

9.2. File

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>
windowprocesstimerHandle.sendMsg → mailboxupdate(&mut State, Msg)pure · no I/O · no async→ Vec<Effect>executedrivers · store · timersresult → MsgSnapshot (watch)app/events.rswindow

9.3. Il contratto

  • update è pura. Riceve lo stato e un messaggio e restituisce una lista di effetti. Ogni regola di business su quello stato si può testare senza tokio, processi o database.
  • Un effetto che produce un risultato lo restituisce come nuovo Msg. L'attore non aspetta mai un effetto lungo dentro il proprio ciclo. Un effetto lungo va in tokio::spawn, e il suo risultato torna attraverso la mailbox.
  • L'annullamento è un messaggio con una generazione, non un flag: Msg::Cancel { generation }. Lo stato contiene generation: u64, e una risposta tardiva con una generazione vecchia viene ignorata in update. Un AtomicBool globale si trascina da un'operazione all'altra; una generazione no.
  • Un risultato è un valore: enum Outcome<T> { Done(T), Cancelled }, mai Err(Cancelled). Annullare è qualcosa che la persona ha chiesto, non un fallimento.
  • Un limite di tempo è Effect::StartTimer, e la sua scadenza è Msg::TimedOut. Terminare un processo dopo un limite di tempo è compito di un driver. Un semplice tokio::time::timeout annulla il future di Rust, non il processo del sistema operativo.
  • Nessun std::sync::Mutex dentro un attore. Il suo stato ha un solo proprietario, quindi non serve un lock.
  • Un attore per ogni istanza di stato: uno per esecuzione, uno per conversazione. Il registro delle istanze attive è a sua volta un piccolo attore, oppure un servizio con una mappa di handle.

9.4. Un piccolo attore completo

Un attore di registrazione che avvia un processo registratore, applica un limite di tempo e può essere fermato (il file viene conservato) o annullato (il file viene scartato). Tutti i nomi di tipi e funzioni sono illustrativi.

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![],
    }
}

Una nuova registrazione può partire ogni volta che non c'è nulla in corso, anche dopo che una precedente è stata salvata o annullata. L'ultimo ramo è il senso delle generazioni: un messaggio Level, TimedOut o Ended proveniente da una registrazione precedente arriva con una generazione vecchia e non cambia nulla.

Anche uno Start durante una registrazione in corso non cambia nulla. In quel momento la finestra non offre Start, perché lo snapshot dice che una registrazione è attiva; chi chiama e ha bisogno di una risposta usa ask con un oneshot (9.2). Failed è la fine quando il registratore non è riuscito ad avviarsi, a fermarsi o a salvare. Prima che un driver restituisca quell'errore, ha già ucciso il processo e dimostrato che è morto (17.5), quindi Failed non lascia mai un registratore in esecuzione.

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;

La finestra prende dallo snapshot la generazione che le serve per Stop e Cancel. Il ciclo invia uno snapshot solo quando è cambiato (send_if_modified), e il livello è arrotondato a decibel interi, quindi un misuratore che riporta un valore ogni pochi millisecondi non trasforma ogni lettura in un evento per la finestra. Un valore che cambia più in fretta di quanto la finestra riesca a disegnarlo appartiene a un flusso (8.4), non a uno snapshot.

Il ciclo tiene solo un mittente debole per i risultati dei propri effetti. Quando l'ultimo Handle viene distrutto, recv restituisce None e l'attore termina invece di restare in attesa per sempre.

Quando l'ordine degli effetti conta (per esempio, salvare prima di notificare), quegli effetti si eseguono in sequenza dentro un unico task, invece di avviare un task per effetto. L'unica regola è che il ciclo stesso non aspetti mai.

9.5. Testare un attore

La maggior parte dei test non avvia mai l'attore. Chiama direttamente update:

#[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 });
}

Alcuni test guidano l'intero attore attraverso il suo Handle con tokio::time::pause(), un punto di giunzione sui dati o un driver finto (14.2) e asserzioni sulla sequenza degli snapshot.