chunked_wal/api/state_machine.rs
1//! State machine abstraction for applying records in a deterministic order.
2
3use std::fmt::Debug;
4
5use crate::ChunkId;
6use crate::WALRecord;
7use crate::WalTypes;
8use crate::types::Segment;
9
10/// A trait representing a state machine of [`WAL`] that can apply records to
11/// modify its state.
12///
13/// The Raft-log follows a Write-Ahead Log (WAL) + State Machine pattern. This
14/// trait defines the state machine component that processes records persisted
15/// in the WAL to build and maintain application state.
16///
17/// # Type Parameters
18/// * `W` - The WAL type set that defines records and checkpoints
19///
20/// [`WAL`]: crate::api::wal::WAL
21pub trait StateMachine<W>
22where W: WalTypes
23{
24 /// The type of error that can occur during record application
25 type Error: std::error::Error + Debug + 'static;
26
27 /// Applies a record that is already persisted in the WAL to the state
28 /// machine, potentially modifying its state.
29 ///
30 /// # Arguments
31 /// * `record` - The record to apply.
32 /// * `chunk_id` - The identifier of the chunk containing this record.
33 /// * `global_segment` - The global offset and size of the record in the log
34 /// file.
35 fn apply(
36 &mut self,
37 record: &WALRecord<W>,
38 chunk_id: ChunkId,
39 global_segment: Segment,
40 ) -> Result<(), Self::Error>;
41
42 /// Returns the current checkpoint value for WAL storage.
43 ///
44 /// The WAL stores this value at the beginning of each new chunk. Keep it
45 /// small because it may be duplicated across chunks. The framework only
46 /// persists the value; the semantic content belongs to the state-machine
47 /// implementation.
48 fn checkpoint(&self) -> W::Checkpoint;
49}