MockStateMachine

Struct MockStateMachine 

Source
pub struct MockStateMachine { /* private fields */ }
Expand description

State machine trait for Raft consensus

§Thread Safety Requirements

CRITICAL: Implementations MUST be thread-safe.

  • Read methods (get(), len()) may be called concurrently
  • Write methods should use internal synchronization
  • No assumptions about caller’s threading model

Implementations§

Source§

impl MockStateMachine

Source

pub fn checkpoint(&mut self)

Validate that all current expectations for all methods have been satisfied, and discard them.

Source

pub fn new() -> Self

Create a new mock object with no expectations.

This method will not be generated if the real struct already has a new method. However, it will be generated if the struct implements a trait with a new method. The trait’s new method can still be called like <MockX as TraitY>::new

Source§

impl MockStateMachine

Source

pub fn expect_start(&mut self) -> &mut Expectation

Create an Expectation for mocking the start method

Source

pub fn expect_stop(&mut self) -> &mut Expectation

Create an Expectation for mocking the stop method

Source

pub fn expect_is_running(&mut self) -> &mut Expectation

Create an Expectation for mocking the is_running method

Source

pub fn expect_get(&mut self) -> &mut Expectation

Create an Expectation for mocking the get method

Source

pub fn expect_entry_term(&mut self) -> &mut Expectation

Create an Expectation for mocking the entry_term method

Source

pub fn expect_apply_chunk(&mut self) -> &mut Expectation

Create an Expectation for mocking the apply_chunk method

Source

pub fn expect_len(&mut self) -> &mut Expectation

Create an Expectation for mocking the len method

Source

pub fn expect_is_empty(&mut self) -> &mut Expectation

Create an Expectation for mocking the is_empty method

Source

pub fn expect_update_last_applied(&mut self) -> &mut Expectation

Create an Expectation for mocking the update_last_applied method

Source

pub fn expect_last_applied(&mut self) -> &mut Expectation

Create an Expectation for mocking the last_applied method

Source

pub fn expect_persist_last_applied(&mut self) -> &mut Expectation

Create an Expectation for mocking the persist_last_applied method

Source

pub fn expect_update_last_snapshot_metadata(&mut self) -> &mut Expectation

Create an Expectation for mocking the update_last_snapshot_metadata method

Source

pub fn expect_snapshot_metadata(&mut self) -> &mut Expectation

Create an Expectation for mocking the snapshot_metadata method

Source

pub fn expect_persist_last_snapshot_metadata(&mut self) -> &mut Expectation

Create an Expectation for mocking the persist_last_snapshot_metadata method

Source

pub fn expect_apply_snapshot_from_file(&mut self) -> &mut Expectation

Create an Expectation for mocking the apply_snapshot_from_file method

Source

pub fn expect_generate_snapshot_data(&mut self) -> &mut Expectation

Create an Expectation for mocking the generate_snapshot_data method

Source

pub fn expect_save_hard_state(&mut self) -> &mut Expectation

Create an Expectation for mocking the save_hard_state method

Source

pub fn expect_flush(&mut self) -> &mut Expectation

Create an Expectation for mocking the flush method

Source

pub fn expect_flush_async(&mut self) -> &mut Expectation

Create an Expectation for mocking the flush_async method

Source

pub fn expect_reset(&mut self) -> &mut Expectation

Create an Expectation for mocking the reset method

Source

pub fn expect_lease_background_cleanup(&mut self) -> &mut Expectation

Create an Expectation for mocking the lease_background_cleanup method

Trait Implementations§

Source§

impl Debug for MockStateMachine

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for MockStateMachine

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl StateMachine for MockStateMachine

State machine trait for Raft consensus

§Thread Safety Requirements

CRITICAL: Implementations MUST be thread-safe.

  • Read methods (get(), len()) may be called concurrently
  • Write methods should use internal synchronization
  • No assumptions about caller’s threading model
Source§

fn start<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Starts the state machine service.

This method:

  1. Flips internal state flags
  2. Loads persisted data (e.g., TTL state from disk)

Called once during node startup. Performance is not critical.

Source§

fn stop(&self) -> Result<(), Error>

Stops the state machine service gracefully. This is typically a sync operation for state management.

Source§

fn is_running(&self) -> bool

Checks if the state machine is currently running. Sync operation as it just checks an atomic boolean.

Source§

fn get(&self, key_buffer: &[u8]) -> Result<Option<Bytes>, Error>

Retrieves a value by key from the state machine. Sync operation as it accesses in-memory data structures.

Source§

fn entry_term(&self, entry_id: u64) -> Option<u64>

Returns the term of a specific log entry by its ID. Sync operation as it queries in-memory data.

Source§

fn apply_chunk<'life0, 'async_trait>( &'life0 self, chunk: Vec<Entry>, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Applies a chunk of log entries to the state machine. Async operation as it may involve disk I/O for persistence.

Source§

fn len(&self) -> usize

Returns the number of entries in the state machine. NOTE: This may be expensive for some implementations. Sync operation but should be used cautiously.

Source§

fn is_empty(&self) -> bool

Checks if the state machine is empty. Sync operation that typically delegates to len().

Source§

fn update_last_applied(&self, last_applied: LogId)

Updates the last applied index in memory. Sync operation as it just updates atomic variables.

Source§

fn last_applied(&self) -> LogId

Gets the last applied log index and term. Sync operation as it reads from atomic variables.

Source§

fn persist_last_applied(&self, last_applied: LogId) -> Result<(), Error>

Persists the last applied index to durable storage. Should be async as it involves disk I/O.

Source§

fn update_last_snapshot_metadata( &self, snapshot_metadata: &SnapshotMetadata, ) -> Result<(), Error>

Updates snapshot metadata in memory. Sync operation as it updates in-memory structures.

Source§

fn snapshot_metadata(&self) -> Option<SnapshotMetadata>

Retrieves the current snapshot metadata. Sync operation as it reads from in-memory structures.

Source§

fn persist_last_snapshot_metadata( &self, snapshot_metadata: &SnapshotMetadata, ) -> Result<(), Error>

Persists snapshot metadata to durable storage. Should be async as it involves disk I/O.

Source§

fn apply_snapshot_from_file<'life0, 'life1, 'async_trait>( &'life0 self, metadata: &'life1 SnapshotMetadata, snapshot_path: PathBuf, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Applies a snapshot received from the Raft leader to the local state machine

§Critical Security and Integrity Measures
  1. Checksum Validation: Verifies snapshot integrity before application
  2. Version Validation: Ensures snapshot is newer than current state
  3. Atomic Application: Uses locking to prevent concurrent modifications
  4. File Validation: Confirms compressed format before decompression
§Workflow
  1. Validate snapshot metadata and version
  2. Verify compressed file format
  3. Decompress to temporary directory
  4. Validate checklsum
  5. Initialize new state machine database
  6. Atomically replace current database
  7. Update Raft metadata and indexes
Source§

fn generate_snapshot_data<'life0, 'async_trait>( &'life0 self, new_snapshot_dir: PathBuf, last_included: LogId, ) -> Pin<Box<dyn Future<Output = Result<Bytes, Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Generates a snapshot of the state machine’s current key-value entries up to the specified last_included_index.

This function:

  1. Creates a new database at temp_snapshot_path.
  2. Copies all key-value entries from the current state machine’s database where the key (interpreted as a log index) does not exceed last_included_index.
  3. Uses batch writes for efficiency, committing every 100 records.
  4. Will update last_included_index and last_included_term in memory
  5. Will persist last_included_index and last_included_term into current database and new database specified by temp_snapshot_path
§Arguments
  • new_snapshot_dir - Temporary path to store the snapshot data.
  • last_included_index - Last log index included in the snapshot.
  • last_included_term - Last log term included in the snapshot.
§Returns
  • if success, checksum will be returned
Source§

fn save_hard_state(&self) -> Result<(), Error>

Saves the hard state of the state machine. Sync operation as it typically just delegates to other persistence methods.

Source§

fn flush(&self) -> Result<(), Error>

Flushes any pending writes to durable storage. Sync operation that may block but provides a synchronous interface.

Source§

fn flush_async<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Flushes any pending writes to durable storage. Async operation as it involves disk I/O.

Source§

fn reset<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Resets the state machine to its initial state. Async operation as it may involve cleaning up files and data.

Source§

fn lease_background_cleanup<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<Vec<Bytes>, Error>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Background lease cleanup hook.

Called periodically by the background cleanup task (if enabled). Returns keys that were cleaned up.

§Default Implementation

No-op, suitable for state machines without lease support.

§Called By

Framework calls this from background cleanup task spawned in NodeBuilder::build(). Only called when cleanup_strategy = “background”.

§Returns
  • Vec of deleted keys (for logging/metrics)
§Example (d-engine built-in state machines)
async fn lease_background_cleanup(&self) -> Result<Vec<Bytes>, Error> {
    if let Some(ref lease) = self.lease {
        let expired_keys = lease.get_expired_keys(SystemTime::now());
        if !expired_keys.is_empty() {
            self.delete_batch(&expired_keys).await?;
        }
        return Ok(expired_keys);
    }
    Ok(vec![])
}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Any for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Source§

fn type_name(&self) -> &'static str

Source§

impl<T> AnySync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more