pub trait StateMachine: Send + 'static {
type Command: Command;
type Query: Query;
type Response: Send + 'static + Serialize + DeserializeOwned;
type Error: Error + Send + Sync + 'static;
// Required methods
fn apply(
&mut self,
index: LogIndex,
command: &Self::Command,
) -> Result<Self::Response, Self::Error>;
fn query(&self, query: &Self::Query) -> Result<Self::Response, Self::Error>;
fn snapshot(&self) -> Result<Vec<u8>, Self::Error>;
fn restore(&mut self, snapshot: &[u8]) -> Result<(), Self::Error>;
}Expand description
The user-defined, deterministic application state machine (state-machine).
Implementations must be deterministic: applying the same sequence of
commands from the same snapshot must always yield the same state and the
same per-command Response. This is what lets a
lagging follower rebuild identical state purely from the replicated log, and
what lets the deterministic simulator (testing-strategy) reproduce runs. Avoid wall
clocks, RNGs, and external I/O inside apply; feed
any such inputs in through the command instead.
Required Associated Types§
Sourcetype Response: Send + 'static + Serialize + DeserializeOwned
type Response: Send + 'static + Serialize + DeserializeOwned
The value returned to the client from an apply or query.
Required Methods§
Sourcefn apply(
&mut self,
index: LogIndex,
command: &Self::Command,
) -> Result<Self::Response, Self::Error>
fn apply( &mut self, index: LogIndex, command: &Self::Command, ) -> Result<Self::Response, Self::Error>
Apply a committed command at log index, mutating state and returning a
response for the client.
The runtime calls this exactly once per committed command, in ascending
index order. index is provided so implementations can persist an
applied-through watermark for idempotent external side effects
(actor-state-redis), though the in-log state itself needs no such bookkeeping.
§Errors
Returns Self::Error if the command is invalid
for the current state. Note that a returned error does not roll back
the log entry — it is reported to the client while the command remains
committed, so implementations should validate before mutating.
Sourcefn query(&self, query: &Self::Query) -> Result<Self::Response, Self::Error>
fn query(&self, query: &Self::Query) -> Result<Self::Response, Self::Error>
Answer a read-only query against the current applied state.
Must not mutate state. Linearizability is guaranteed by the caller via
ReadIndex (read-consistency), not by this method.
§Errors
Returns Self::Error if the query is invalid.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".