Skip to main content

telltale_machine/
persistence.rs

1//! Persistence model for protocol-machine state deltas.
2
3use serde::{Deserialize, Serialize};
4
5use crate::session::SessionId;
6
7/// Persistence-model contract.
8pub trait PersistenceModel {
9    /// Persistent state representation.
10    type PState: Clone;
11    /// Delta representation for incremental updates.
12    type Delta: Clone;
13
14    /// Apply one delta to state.
15    ///
16    /// # Errors
17    ///
18    /// Returns an error if the delta cannot be applied.
19    fn apply(state: &mut Self::PState, delta: &Self::Delta) -> Result<(), String>;
20
21    /// Derive a delta between two states.
22    ///
23    /// # Errors
24    ///
25    /// Returns an error if derivation fails.
26    fn derive(before: &Self::PState, after: &Self::PState) -> Result<Self::Delta, String>;
27
28    /// Open-session lifecycle delta.
29    #[must_use]
30    fn open_delta(session: SessionId) -> Self::Delta;
31
32    /// Close-session lifecycle delta.
33    #[must_use]
34    fn close_delta(session: SessionId) -> Self::Delta;
35
36    /// Optional invoke-action delta.
37    #[must_use]
38    fn invoke_delta(_session: SessionId, _action: &str) -> Option<Self::Delta> {
39        None
40    }
41}
42
43/// No-op persistence model useful for tests and default ProtocolMachine construction.
44#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
45pub struct NoopPersistence;
46
47impl PersistenceModel for NoopPersistence {
48    type PState = ();
49    type Delta = ();
50
51    fn apply(_state: &mut Self::PState, _delta: &Self::Delta) -> Result<(), String> {
52        Ok(())
53    }
54
55    fn derive(_before: &Self::PState, _after: &Self::PState) -> Result<Self::Delta, String> {
56        Ok(())
57    }
58
59    fn open_delta(_session: SessionId) -> Self::Delta {}
60
61    fn close_delta(_session: SessionId) -> Self::Delta {}
62}