1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::collections::VecDeque;
use slog::Logger;
use crate::eraftpb::Message;
use crate::{HashMap, HashSet};
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ReadOnlyOption {
Safe,
LeaseBased,
}
impl Default for ReadOnlyOption {
fn default() -> ReadOnlyOption {
ReadOnlyOption::Safe
}
}
#[derive(Default, Debug, PartialEq, Clone)]
pub struct ReadState {
pub index: u64,
pub request_ctx: Vec<u8>,
}
#[derive(Default, Debug, Clone)]
pub struct ReadIndexStatus {
pub req: Message,
pub index: u64,
pub acks: HashSet<u64>,
}
#[derive(Default, Debug, Clone)]
pub struct ReadOnly {
pub option: ReadOnlyOption,
pub pending_read_index: HashMap<Vec<u8>, ReadIndexStatus>,
pub read_index_queue: VecDeque<Vec<u8>>,
}
impl ReadOnly {
pub fn new(option: ReadOnlyOption) -> ReadOnly {
ReadOnly {
option,
pending_read_index: HashMap::default(),
read_index_queue: VecDeque::new(),
}
}
pub fn add_request(&mut self, index: u64, req: Message, self_id: u64) {
let ctx = {
let key: &[u8] = req.entries[0].data.as_ref();
if self.pending_read_index.contains_key(key) {
return;
}
key.to_vec()
};
let mut acks = HashSet::<u64>::default();
acks.insert(self_id);
let status = ReadIndexStatus { req, index, acks };
self.pending_read_index.insert(ctx.clone(), status);
self.read_index_queue.push_back(ctx);
}
pub fn recv_ack(&mut self, id: u64, ctx: &[u8]) -> Option<&HashSet<u64>> {
self.pending_read_index.get_mut(ctx).map(|rs| {
rs.acks.insert(id);
&rs.acks
})
}
pub fn advance(&mut self, ctx: &[u8], logger: &Logger) -> Vec<ReadIndexStatus> {
let mut rss = vec![];
if let Some(i) = self.read_index_queue.iter().position(|x| {
if !self.pending_read_index.contains_key(x) {
fatal!(logger, "cannot find correspond read state from pending map");
}
*x == ctx
}) {
for _ in 0..=i {
let rs = self.read_index_queue.pop_front().unwrap();
let status = self.pending_read_index.remove(&rs).unwrap();
rss.push(status);
}
}
rss
}
pub fn last_pending_request_ctx(&self) -> Option<Vec<u8>> {
self.read_index_queue.back().cloned()
}
#[inline]
pub fn pending_read_count(&self) -> usize {
self.read_index_queue.len()
}
}