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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
use tracing::{debug, trace};
use crate::{
common::{
ErrorSpecific, Id, PutRequest, PutRequestSpecific, RequestSpecific, RequestTypeSpecific,
},
Node,
};
use super::socket::KrpcSocket;
#[derive(Debug)]
/// Once an [super::IterativeQuery] is done, or if a previous cached one was a vailable,
/// we can store data at the closest nodes using this PutQuery, that keeps track of
/// acknowledging nodes, and or errors.
pub struct PutQuery {
pub target: Id,
/// Nodes that confirmed success
stored_at: u8,
inflight_requests: Vec<u32>,
pub request: PutRequestSpecific,
errors: Vec<(u8, ErrorSpecific)>,
extra_nodes: Box<[Node]>,
}
impl PutQuery {
pub fn new(target: Id, request: PutRequestSpecific, extra_nodes: Option<Box<[Node]>>) -> Self {
Self {
target,
stored_at: 0,
inflight_requests: Vec::new(),
request,
errors: Vec::new(),
extra_nodes: extra_nodes.unwrap_or(Box::new([])),
}
}
pub fn start(
&mut self,
socket: &mut KrpcSocket,
closest_nodes: &[Node],
) -> Result<(), PutError> {
if self.started() {
panic!("should not call PutQuery::start() twice");
};
let target = self.target;
trace!(?target, "PutQuery start");
if closest_nodes.is_empty() {
Err(PutQueryError::NoClosestNodes)?;
}
if closest_nodes.len() > u8::MAX as usize {
panic!("should not send PUT query to more than 256 nodes")
}
for node in closest_nodes.iter().chain(self.extra_nodes.iter()) {
// Set correct values to the request placeholders
if let Some(token) = node.token() {
let tid = socket.request(
node.address(),
RequestSpecific {
requester_id: Id::random(),
request_type: RequestTypeSpecific::Put(PutRequest {
token,
put_request_type: self.request.clone(),
}),
},
);
self.inflight_requests.push(tid);
}
}
Ok(())
}
pub fn started(&self) -> bool {
!self.inflight_requests.is_empty()
}
pub fn inflight(&self, tid: u32) -> bool {
self.inflight_requests.contains(&tid)
}
pub fn success(&mut self) {
debug!(target = ?self.target, "PutQuery got success response");
self.stored_at += 1
}
pub fn error(&mut self, error: ErrorSpecific) {
debug!(target = ?self.target, ?error, "PutQuery got error");
if let Some(pos) = self
.errors
.iter()
.position(|(_, err)| error.code == err.code)
{
// Increment the count of the existing error
self.errors[pos].0 += 1;
// Move the updated element to maintain the order (highest count first)
let mut i = pos;
while i > 0 && self.errors[i].0 > self.errors[i - 1].0 {
self.errors.swap(i, i - 1);
i -= 1;
}
} else {
// Add the new error with a count of 1
self.errors.push((1, error));
}
}
/// Check if the query is done, and if so send the query target to the receiver if any.
pub fn tick(&mut self, socket: &KrpcSocket) -> Result<bool, PutError> {
// Didn't start yet.
if self.inflight_requests.is_empty() {
return Ok(false);
}
// And all queries got responses or timedout
if self.is_done(socket) {
let target = self.target;
if self.stored_at == 0 {
let most_common_error = self.most_common_error();
debug!(
?target,
?most_common_error,
nodes_count = self.inflight_requests.len(),
"Put Query: failed"
);
return Err(most_common_error
.map(|(_, error)| error)
.unwrap_or(PutQueryError::Timeout.into()));
}
debug!(?target, stored_at = ?self.stored_at, "PutQuery Done successfully");
return Ok(true);
} else if let Some(most_common_error) = self.majority_nodes_rejected_put_mutable() {
let target = self.target;
debug!(
?target,
?most_common_error,
nodes_count = self.inflight_requests.len(),
"PutQuery for MutableItem was rejected by most nodes with 3xx code."
);
return Err(most_common_error)?;
}
Ok(false)
}
fn is_done(&self, socket: &KrpcSocket) -> bool {
!self
.inflight_requests
.iter()
.any(|&tid| socket.inflight(tid))
}
fn majority_nodes_rejected_put_mutable(&self) -> Option<ConcurrencyError> {
let half = ((self.inflight_requests.len() / 2) + 1) as u8;
if matches!(self.request, PutRequestSpecific::PutMutable(_)) {
return self.most_common_error().and_then(|(count, error)| {
if count >= half {
if let PutError::Concurrency(err) = error {
Some(err)
} else {
None
}
} else {
None
}
});
};
None
}
fn most_common_error(&self) -> Option<(u8, PutError)> {
self.errors
.first()
.and_then(|(count, error)| match error.code {
301 => Some((*count, PutError::from(ConcurrencyError::CasFailed))),
302 => Some((*count, PutError::from(ConcurrencyError::NotMostRecent))),
_ => None,
})
}
}
#[derive(thiserror::Error, Debug, Clone)]
/// PutQuery errors
pub enum PutError {
/// Common PutQuery errors
#[error(transparent)]
Query(#[from] PutQueryError),
#[error(transparent)]
/// PutQuery for [crate::MutableItem] errors
Concurrency(#[from] ConcurrencyError),
}
#[derive(thiserror::Error, Debug, Clone)]
/// Common PutQuery errors
pub enum PutQueryError {
/// Failed to find any nodes close, usually means dht node failed to bootstrap,
/// so the routing table is empty. Check the machine's access to UDP socket,
/// or find better bootstrapping nodes.
#[error("Failed to find any nodes close to store value at")]
NoClosestNodes,
/// Either Put Query faild to store at any nodes, and most nodes responded
/// with a non `301` nor `302` errors.
///
/// Either way; contains the most common error response.
#[error("Query Error Response")]
ErrorResponse(ErrorSpecific),
/// PutQuery timed out with no responses neither success or errors
#[error("PutQuery timed out with no responses neither success or errors")]
Timeout,
}
#[derive(thiserror::Error, Debug, Clone)]
/// PutQuery for [crate::MutableItem] errors
pub enum ConcurrencyError {
/// Trying to PUT mutable items with the same `key`, and `salt` but different `seq`.
///
/// Moreover, the more recent item does _NOT_ mention the the earlier
/// item's `seq` in its `cas` field.
///
/// This risks a [Lost Update Problem](https://en.wikipedia.org/wiki/Write-write_conflict).
///
/// Try reading most recent mutable item before writing again,
/// and make sure to set the `cas` field.
#[error("Conflict risk, try reading most recent item before writing again.")]
ConflictRisk,
/// The [crate::MutableItem::seq] is less than or equal the sequence from another signed item.
///
/// Try reading most recent mutable item before writing again.
#[error("MutableItem::seq is not the most recent, try reading most recent item before writing again.")]
NotMostRecent,
/// The `CAS` condition does not match the `seq` of the most recent knonw signed item.
#[error("CAS check failed, try reading most recent item before writing again.")]
CasFailed,
}