nova_api/
lib.rs

1use std::borrow::Cow;
2
3use raft::v1::{ConfChange, ConfChangeSingle, ConfChangeType, ConfChangeV2};
4
5pub mod raft {
6    pub mod v1 {
7        include!("protos/mod.rs");
8
9        pub use raft::*;
10        pub use metadata::*;
11
12        impl Snapshot {
13            /// For a given snapshot, determine if it's empty or not.
14            pub fn is_empty(&self) -> bool {
15                self.get_metadata().index == 0
16            }
17        }
18    }
19}
20
21pub mod util {
22    use crate::raft::v1::ConfState;
23
24    impl<Iter1, Iter2> From<(Iter1, Iter2)> for ConfState
25    where
26        Iter1: IntoIterator<Item = u64>,
27        Iter2: IntoIterator<Item = u64>,
28    {
29        fn from((voters, learners): (Iter1, Iter2)) -> Self {
30            let mut conf_state = ConfState::default();
31            conf_state.mut_voters().extend(voters);
32            conf_state.mut_learners().extend(learners);
33            conf_state
34        }
35    }
36}
37
38pub fn new_conf_change_single(node_id: u64, ty: ConfChangeType) -> ConfChangeSingle {
39    let mut single = ConfChangeSingle::default();
40    single.node_id = node_id;
41    single.set_change_type(ty);
42    single
43}
44
45/// Abstracts over ConfChangeV2 and (legacy) ConfChange to allow
46/// treating them in a unified manner.
47pub trait ConfChangeI {
48    /// Converts conf change to `ConfChangeV2`.
49    fn into_v2(self) -> ConfChangeV2;
50
51    /// Gets conf change as `ConfChangeV2`.
52    fn as_v2(&self) -> Cow<ConfChangeV2>;
53
54    /// Converts conf change to `ConfChange`.
55    ///
56    /// `ConfChangeV2` can't be changed back to `ConfChange`.
57    fn as_v1(&self) -> Option<&ConfChange>;
58}
59
60impl ConfChangeI for ConfChange {
61    #[inline]
62    fn into_v2(mut self) -> ConfChangeV2 {
63        let mut cc = ConfChangeV2::default();
64        let single = new_conf_change_single(self.node_id, self.get_change_type());
65        cc.mut_changes().push(single);
66        cc.set_context(self.take_context());
67        cc
68    }
69
70    #[inline]
71    fn as_v2(&self) -> Cow<ConfChangeV2> {
72        Cow::Owned(self.clone().into_v2())
73    }
74
75    #[inline]
76    fn as_v1(&self) -> Option<&ConfChange> {
77        Some(self)
78    }
79}
80
81impl ConfChangeI for ConfChangeV2 {
82    #[inline]
83    fn into_v2(self) -> ConfChangeV2 {
84        self
85    }
86
87    #[inline]
88    fn as_v2(&self) -> Cow<ConfChangeV2> {
89        Cow::Borrowed(self)
90    }
91
92    #[inline]
93    fn as_v1(&self) -> Option<&ConfChange> {
94        None
95    }
96}