Skip to main content

raft_log/api/
types.rs

1//! Core type definitions for the Raft-log implementation.
2//!
3//! This module defines the `Types` trait which serves as a type system for the
4//! entire Raft-log implementation. It allows users to customize core data types
5//! such as log id, log payload, vote, callback, and user data.
6
7use std::fmt::Debug;
8
9use codeq::Codec;
10
11use crate::raft_log::wal::callback::Callback;
12
13/// The `Types` trait defines the core type parameters used throughout the
14/// Raft-log implementation.
15///
16/// This trait provides an abstraction layer for the log implementation by
17/// defining the core types used throughout the system. Implementations can
18/// customize the concrete types for: log id, log payload, vote, callback, and
19/// user data.
20pub trait Types
21where Self: Debug + Default + PartialEq + Eq + Clone + 'static
22{
23    /// Unique identifier for log entries. Usually it contains the term and log
24    /// index.
25    type LogId: Debug + Clone + Ord + Eq + Codec + Send + Sync + 'static;
26
27    /// The actual data/command stored in log entries.
28    type LogPayload: Debug + Clone + Codec + Send + Sync + 'static;
29
30    /// Representation of vote in leader election.
31    ///
32    /// A vote typically contains:
33    /// - The election term number
34    /// - The candidate node ID
35    /// - A commitment flag indicating whether a quorum of nodes has granted
36    ///   this vote
37    ///
38    /// The commitment flag is set to true when a majority of nodes in the
39    /// cluster have voted for this candidate in this term.
40    ///
41    /// In some raft implementation the vote is called `hard state`
42    type Vote: Debug + Clone + PartialOrd + Eq + Codec + 'static;
43
44    /// Callback handlers for notification of an IO operation.
45    type Callback: Callback + Send + 'static;
46
47    /// Custom data that can be attached to Raft-log.
48    ///
49    /// This data is not used by the Raft-log implementation, but it can be used
50    /// by the user. For example, an application could attach a
51    /// configuration or the node info in this field.
52    type UserData: Debug + Clone + Eq + Codec + 'static;
53
54    /// Get the log index from the log id.
55    fn log_index(log_id: &Self::LogId) -> u64;
56
57    /// Get the payload size from the log payload.
58    ///
59    /// The returned size does not have to be accurate. It is only used to
60    /// estimate the space occupied in the cache.
61    fn payload_size(payload: &Self::LogPayload) -> u64;
62
63    /// Get the next log index from the log id.
64    fn next_log_index(log_id: Option<&Self::LogId>) -> u64 {
65        match log_id {
66            Some(log_id) => Self::log_index(log_id) + 1,
67            None => 0,
68        }
69    }
70}