@feltdb/core 0.6.14 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/create/server-source/crates/feltdb/src/bin/feltdb_node.rs +116 -0
- package/dist/create/server-source/crates/feltdb/src/distributed_transactions.rs +19 -0
- package/dist/create/server-source/crates/feltdb/src/lib.rs +280 -0
- package/dist/create/server-source/crates/feltdb/src/replica_acknowledgements.rs +471 -0
- package/dist/create/server-source/crates/feltdb/src/tcp_transport.rs +72 -3
- package/dist/create/server-source/crates/feltdb/src/transaction_preconditions.rs +899 -0
- package/dist/create/server-source/crates/feltdb-server/src/main.rs +116 -4
- package/dist/db.d.ts +2 -2
- package/dist/db.d.ts.map +1 -1
- package/dist/db.js +29 -2
- package/dist/embedded-transaction.d.ts +9 -0
- package/dist/embedded-transaction.d.ts.map +1 -1
- package/dist/embedded-transaction.js +95 -3
- package/dist/feltdb.d.ts +16 -0
- package/dist/feltdb.d.ts.map +1 -1
- package/dist/file-db.d.ts.map +1 -1
- package/dist/file-db.js +1 -0
- package/dist/http-db.d.ts +11 -0
- package/dist/http-db.d.ts.map +1 -1
- package/dist/http-db.js +16 -2
- package/dist/indexeddb-db.d.ts.map +1 -1
- package/dist/indexeddb-db.js +5 -0
- package/dist/memory-db.d.ts.map +1 -1
- package/dist/memory-db.js +1 -0
- package/dist/studio-app/assets/{feltdb_wasm-C9xpYtna.js → feltdb_wasm-CD744e5D.js} +1 -1
- package/dist/studio-app/assets/feltdb_wasm_bg-CiIXhOLi.wasm +0 -0
- package/dist/studio-app/assets/index-DoROs8yx.js +28 -0
- package/dist/studio-app/index.html +1 -1
- package/dist/transaction.d.ts +127 -9
- package/dist/transaction.d.ts.map +1 -1
- package/dist/transaction.js +87 -3
- package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
- package/package.json +1 -1
- package/dist/studio-app/assets/feltdb_wasm_bg-BsXHw7eX.wasm +0 -0
- package/dist/studio-app/assets/index-D4RZ44qs.js +0 -28
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
//! Durable replica acknowledgements.
|
|
2
|
+
//!
|
|
3
|
+
//! An acknowledgement is a statement with a precise meaning, and the precision
|
|
4
|
+
//! is the point:
|
|
5
|
+
//!
|
|
6
|
+
//! > this replica has **durably applied** everything the frontier represents.
|
|
7
|
+
//!
|
|
8
|
+
//! Receiving a message is not an acknowledgement. A frontier a peer *claims* is
|
|
9
|
+
//! not one either, until it is durable on that peer. FeltDB's applied frontier
|
|
10
|
+
//! already has exactly this property -- it advances only in `record_applied`,
|
|
11
|
+
//! after the envelope has been fsynced and applied -- so an acknowledgement is
|
|
12
|
+
//! read from it rather than assembled.
|
|
13
|
+
//!
|
|
14
|
+
//! ## The conservative rule
|
|
15
|
+
//!
|
|
16
|
+
//! `adrs/membership-safety-and-conservative-reclamation.md` decides that a node
|
|
17
|
+
//! may act only on positive durable evidence, never on an absence:
|
|
18
|
+
//!
|
|
19
|
+
//! ```text
|
|
20
|
+
//! unknown replica unknown replica
|
|
21
|
+
//! │ │
|
|
22
|
+
//! ▼ ▼
|
|
23
|
+
//! assume required assume irrelevant <- forbidden
|
|
24
|
+
//! │ │
|
|
25
|
+
//! ▼ ▼
|
|
26
|
+
//! retain history delete history
|
|
27
|
+
//! ```
|
|
28
|
+
//!
|
|
29
|
+
//! Two things follow, and both are enforced here rather than left to the
|
|
30
|
+
//! caller that will eventually reclaim:
|
|
31
|
+
//!
|
|
32
|
+
//! 1. the required set is the **union** of this node's membership and every
|
|
33
|
+
//! replica named in any membership view observed from a peer. That is why an
|
|
34
|
+
//! acknowledgement carries the sender's membership view: without it the
|
|
35
|
+
//! union has no input, and a node could never learn that its view is short.
|
|
36
|
+
//! 2. a required replica with no acknowledgement **blocks**. There is no
|
|
37
|
+
//! timeout after which a silent replica is treated as caught up, because a
|
|
38
|
+
//! timeout is the forbidden inference with a clock attached.
|
|
39
|
+
//!
|
|
40
|
+
//! ## Deliberately not here
|
|
41
|
+
//!
|
|
42
|
+
//! Nothing is reclaimed, compacted, deleted or checkpointed. No consensus, no
|
|
43
|
+
//! epochs. This records what replicas have applied and computes what that
|
|
44
|
+
//! evidence does and does not permit; acting on it is a later change.
|
|
45
|
+
|
|
46
|
+
use crate::convergence::VectorClock;
|
|
47
|
+
use serde::{Deserialize, Serialize};
|
|
48
|
+
use std::collections::{BTreeMap, BTreeSet};
|
|
49
|
+
use std::path::{Path, PathBuf};
|
|
50
|
+
|
|
51
|
+
fn now_ms() -> u64 {
|
|
52
|
+
std::time::SystemTime::now()
|
|
53
|
+
.duration_since(std::time::UNIX_EPOCH)
|
|
54
|
+
.map(|elapsed| elapsed.as_millis() as u64)
|
|
55
|
+
.unwrap_or(0)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// What one replica has durably applied, as it reported it.
|
|
59
|
+
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
|
60
|
+
pub struct ReplicaAcknowledgement {
|
|
61
|
+
pub replica_id: String,
|
|
62
|
+
pub node_id: String,
|
|
63
|
+
/// Everything this replica has durably applied. Read from its applied
|
|
64
|
+
/// frontier, which advances only after an fsynced envelope is applied.
|
|
65
|
+
pub applied_frontier: VectorClock,
|
|
66
|
+
/// The highest identity this replica has committed per origin.
|
|
67
|
+
///
|
|
68
|
+
/// Carried because the operation log is also the source from which
|
|
69
|
+
/// `next_origin_sequence` is recovered, so a checkpoint that discards log
|
|
70
|
+
/// must preserve these or identity allocation regresses.
|
|
71
|
+
pub origin_sequence_high_water: BTreeMap<String, u64>,
|
|
72
|
+
/// Every replica the sender's membership names. The input to the union
|
|
73
|
+
/// rule: this is how a node discovers a replica it has never heard of.
|
|
74
|
+
pub membership_view: Vec<String>,
|
|
75
|
+
/// When the sender produced it. Recorded for operators, never used to
|
|
76
|
+
/// decide anything -- a stale acknowledgement is not a missing one, and
|
|
77
|
+
/// neither is treated as permission.
|
|
78
|
+
pub produced_at_ms: u64,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
impl ReplicaAcknowledgement {
|
|
82
|
+
pub fn new(
|
|
83
|
+
replica_id: String,
|
|
84
|
+
node_id: String,
|
|
85
|
+
applied_frontier: VectorClock,
|
|
86
|
+
origin_sequence_high_water: BTreeMap<String, u64>,
|
|
87
|
+
membership_view: Vec<String>,
|
|
88
|
+
) -> Self {
|
|
89
|
+
Self {
|
|
90
|
+
replica_id,
|
|
91
|
+
node_id,
|
|
92
|
+
applied_frontier,
|
|
93
|
+
origin_sequence_high_water,
|
|
94
|
+
membership_view,
|
|
95
|
+
produced_at_ms: now_ms(),
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// What this node's evidence permits.
|
|
101
|
+
///
|
|
102
|
+
/// A typed outcome rather than an `Option<VectorClock>`, because "there is no
|
|
103
|
+
/// safe frontier yet" and "the safe frontier is empty" are different states and
|
|
104
|
+
/// a caller that confused them would reclaim on an absence.
|
|
105
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
106
|
+
pub enum ReclamationEvidence {
|
|
107
|
+
/// Some required replica has not acknowledged. Nothing may be reclaimed,
|
|
108
|
+
/// and these are the replicas being waited on.
|
|
109
|
+
Blocked { waiting_on: Vec<String> },
|
|
110
|
+
/// Every required replica has acknowledged at least this much.
|
|
111
|
+
SafeThrough {
|
|
112
|
+
frontier: VectorClock,
|
|
113
|
+
covered: Vec<String>,
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
#[derive(Debug)]
|
|
118
|
+
pub enum AcknowledgementError {
|
|
119
|
+
Io(String),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
impl std::fmt::Display for AcknowledgementError {
|
|
123
|
+
fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
124
|
+
match self {
|
|
125
|
+
Self::Io(message) => write!(out, "acknowledgement store: {message}"),
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/// Durable acknowledgements, one per replica: the latest each has reported.
|
|
131
|
+
pub struct AcknowledgementStore {
|
|
132
|
+
path: PathBuf,
|
|
133
|
+
acknowledgements: BTreeMap<String, ReplicaAcknowledgement>,
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
impl AcknowledgementStore {
|
|
137
|
+
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, AcknowledgementError> {
|
|
138
|
+
let path = path.as_ref().to_path_buf();
|
|
139
|
+
let acknowledgements = if path.exists() {
|
|
140
|
+
let bytes = std::fs::read(&path).map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
141
|
+
serde_json::from_slice(&bytes).map_err(|e| AcknowledgementError::Io(e.to_string()))?
|
|
142
|
+
} else {
|
|
143
|
+
BTreeMap::new()
|
|
144
|
+
};
|
|
145
|
+
Ok(Self { path, acknowledgements })
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
fn persist(&self) -> Result<(), AcknowledgementError> {
|
|
149
|
+
if let Some(parent) = self.path.parent() {
|
|
150
|
+
std::fs::create_dir_all(parent).map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
151
|
+
}
|
|
152
|
+
let temp = self.path.with_extension("tmp");
|
|
153
|
+
let bytes = serde_json::to_vec_pretty(&self.acknowledgements)
|
|
154
|
+
.map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
155
|
+
{
|
|
156
|
+
use std::io::Write;
|
|
157
|
+
let mut file =
|
|
158
|
+
std::fs::File::create(&temp).map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
159
|
+
file.write_all(&bytes).map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
160
|
+
file.sync_all().map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
161
|
+
}
|
|
162
|
+
std::fs::rename(&temp, &self.path).map_err(|e| AcknowledgementError::Io(e.to_string()))?;
|
|
163
|
+
if let Some(parent) = self.path.parent() {
|
|
164
|
+
if let Ok(dir) = std::fs::File::open(parent) {
|
|
165
|
+
let _ = dir.sync_all();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
Ok(())
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/// Record an acknowledgement, durably, before it counts as evidence.
|
|
172
|
+
///
|
|
173
|
+
/// An acknowledgement that only ever existed in memory would be forgotten
|
|
174
|
+
/// by the restart that most needs it, and the node would then be unable to
|
|
175
|
+
/// say what it had been told.
|
|
176
|
+
///
|
|
177
|
+
/// A report that does not advance the frontier is kept rather than
|
|
178
|
+
/// discarded, so `produced_at_ms` still moves and an operator can see the
|
|
179
|
+
/// replica is alive and stuck. A report that would move a frontier
|
|
180
|
+
/// *backwards* is refused: acknowledgement is monotonic, and accepting a
|
|
181
|
+
/// regression would let a peer talk a node into believing less is durable
|
|
182
|
+
/// than it has already been told, which is the one direction that could
|
|
183
|
+
/// later un-block a reclamation decision.
|
|
184
|
+
pub fn record(&mut self, ack: ReplicaAcknowledgement) -> Result<bool, AcknowledgementError> {
|
|
185
|
+
if let Some(existing) = self.acknowledgements.get(&ack.replica_id) {
|
|
186
|
+
if !ack.applied_frontier.dominates(&existing.applied_frontier) {
|
|
187
|
+
return Ok(false);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
self.acknowledgements.insert(ack.replica_id.clone(), ack);
|
|
191
|
+
self.persist()?;
|
|
192
|
+
Ok(true)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
pub fn get(&self, replica_id: &str) -> Option<&ReplicaAcknowledgement> {
|
|
196
|
+
self.acknowledgements.get(replica_id)
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
pub fn all(&self) -> Vec<ReplicaAcknowledgement> {
|
|
200
|
+
self.acknowledgements.values().cloned().collect()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/// Every replica named by this node's membership or by any membership view
|
|
204
|
+
/// it has been told about.
|
|
205
|
+
///
|
|
206
|
+
/// The union is what makes "unknown means required" real: a replica this
|
|
207
|
+
/// node has never enrolled, but which a peer names, is required here too.
|
|
208
|
+
pub fn required_union(&self, local_required: &[String]) -> Vec<String> {
|
|
209
|
+
let mut union: BTreeSet<String> = local_required.iter().cloned().collect();
|
|
210
|
+
for ack in self.acknowledgements.values() {
|
|
211
|
+
for replica in &ack.membership_view {
|
|
212
|
+
union.insert(replica.clone());
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
union.into_iter().collect()
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/// What the evidence permits, given the replicas this node must retain for.
|
|
219
|
+
///
|
|
220
|
+
/// `local_required` comes from durable membership. Replicas learned only
|
|
221
|
+
/// from a peer's view are added by `required_union` and, having never
|
|
222
|
+
/// acknowledged anything here, block -- which is the intended outcome and
|
|
223
|
+
/// not an oversight.
|
|
224
|
+
pub fn evidence(&self, local_required: &[String]) -> ReclamationEvidence {
|
|
225
|
+
let required = self.required_union(local_required);
|
|
226
|
+
if required.is_empty() {
|
|
227
|
+
// No required replicas at all. Still not a licence: a node with no
|
|
228
|
+
// membership has not established that it is alone, it has
|
|
229
|
+
// established nothing.
|
|
230
|
+
return ReclamationEvidence::Blocked { waiting_on: Vec::new() };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let missing: Vec<String> = required
|
|
234
|
+
.iter()
|
|
235
|
+
.filter(|replica| !self.acknowledgements.contains_key(*replica))
|
|
236
|
+
.cloned()
|
|
237
|
+
.collect();
|
|
238
|
+
if !missing.is_empty() {
|
|
239
|
+
return ReclamationEvidence::Blocked { waiting_on: missing };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// The minimum over every required replica, component-wise. A frontier
|
|
243
|
+
// is safe only where every one of them has reached it.
|
|
244
|
+
let mut frontier = VectorClock::new();
|
|
245
|
+
let mut origins: BTreeSet<String> = BTreeSet::new();
|
|
246
|
+
for replica in &required {
|
|
247
|
+
let ack = &self.acknowledgements[replica];
|
|
248
|
+
for origin in ack.applied_frontier.clocks.keys() {
|
|
249
|
+
origins.insert(origin.clone());
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
for origin in origins {
|
|
253
|
+
let lowest = required
|
|
254
|
+
.iter()
|
|
255
|
+
.map(|replica| self.acknowledgements[replica].applied_frontier.get(&origin))
|
|
256
|
+
.min()
|
|
257
|
+
.unwrap_or(0);
|
|
258
|
+
if lowest > 0 {
|
|
259
|
+
frontier.clocks.insert(origin, lowest);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
ReclamationEvidence::SafeThrough { frontier, covered: required }
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
#[cfg(test)]
|
|
267
|
+
mod tests {
|
|
268
|
+
use super::*;
|
|
269
|
+
|
|
270
|
+
fn clock(entries: &[(&str, u64)]) -> VectorClock {
|
|
271
|
+
let mut clock = VectorClock::new();
|
|
272
|
+
for (node, value) in entries {
|
|
273
|
+
clock.clocks.insert((*node).to_string(), *value);
|
|
274
|
+
}
|
|
275
|
+
clock
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
fn ack(replica: &str, frontier: &[(&str, u64)], view: &[&str]) -> ReplicaAcknowledgement {
|
|
279
|
+
ReplicaAcknowledgement::new(
|
|
280
|
+
replica.to_string(),
|
|
281
|
+
replica.to_uppercase(),
|
|
282
|
+
clock(frontier),
|
|
283
|
+
BTreeMap::new(),
|
|
284
|
+
view.iter().map(|v| v.to_string()).collect(),
|
|
285
|
+
)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
fn store(dir: &tempfile::TempDir) -> AcknowledgementStore {
|
|
289
|
+
AcknowledgementStore::open(dir.path().join("acknowledgements.json")).expect("open")
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// -- durability --------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
#[test]
|
|
295
|
+
fn acknowledgements_survive_restart() {
|
|
296
|
+
// The acceptance criterion: after a restart a node can prove what its
|
|
297
|
+
// replicas acknowledged. An in-memory record would be forgotten by
|
|
298
|
+
// exactly the event that makes the question worth asking.
|
|
299
|
+
let dir = tempfile::tempdir().unwrap();
|
|
300
|
+
{
|
|
301
|
+
let mut acks = store(&dir);
|
|
302
|
+
acks.record(ack("rb", &[("A", 3)], &["ra", "rb"])).unwrap();
|
|
303
|
+
}
|
|
304
|
+
let recovered = store(&dir);
|
|
305
|
+
let recorded = recovered.get("rb").expect("rb acknowledged");
|
|
306
|
+
assert_eq!(recorded.applied_frontier.get("A"), 3);
|
|
307
|
+
assert_eq!(recorded.membership_view, vec!["ra", "rb"]);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
#[test]
|
|
311
|
+
fn acknowledgement_is_monotonic_and_a_regression_is_refused() {
|
|
312
|
+
// Accepting a lower frontier would let a peer talk this node into
|
|
313
|
+
// believing less is durable than it has already been told -- the one
|
|
314
|
+
// direction that could later un-block a decision that was blocked.
|
|
315
|
+
let dir = tempfile::tempdir().unwrap();
|
|
316
|
+
let mut acks = store(&dir);
|
|
317
|
+
assert!(acks.record(ack("rb", &[("A", 5)], &["ra", "rb"])).unwrap());
|
|
318
|
+
assert!(!acks.record(ack("rb", &[("A", 2)], &["ra", "rb"])).unwrap());
|
|
319
|
+
assert_eq!(acks.get("rb").unwrap().applied_frontier.get("A"), 5);
|
|
320
|
+
|
|
321
|
+
// A repeat at the same frontier is kept, so liveness stays visible.
|
|
322
|
+
assert!(acks.record(ack("rb", &[("A", 5)], &["ra", "rb"])).unwrap());
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// -- the conservative rule ---------------------------------------------
|
|
326
|
+
|
|
327
|
+
#[test]
|
|
328
|
+
fn a_required_replica_with_no_acknowledgement_blocks() {
|
|
329
|
+
let dir = tempfile::tempdir().unwrap();
|
|
330
|
+
let mut acks = store(&dir);
|
|
331
|
+
acks.record(ack("rb", &[("A", 3)], &["ra", "rb", "rc"])).unwrap();
|
|
332
|
+
|
|
333
|
+
let evidence = acks.evidence(&["ra".into(), "rb".into(), "rc".into()]);
|
|
334
|
+
match evidence {
|
|
335
|
+
ReclamationEvidence::Blocked { waiting_on } => {
|
|
336
|
+
assert_eq!(waiting_on, vec!["ra", "rc"], "and it names who it waits for");
|
|
337
|
+
}
|
|
338
|
+
other => panic!("missing acknowledgement must block, got {other:?}"),
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
#[test]
|
|
343
|
+
fn a_replica_known_only_from_a_peers_view_is_required_and_blocks() {
|
|
344
|
+
// This is "unknown means required" doing its work. This node's
|
|
345
|
+
// membership does not contain rc at all; rb's acknowledgement names it,
|
|
346
|
+
// and that alone is enough to stop reclamation.
|
|
347
|
+
let dir = tempfile::tempdir().unwrap();
|
|
348
|
+
let mut acks = store(&dir);
|
|
349
|
+
acks.record(ack("ra", &[("A", 3)], &["ra", "rb"])).unwrap();
|
|
350
|
+
acks.record(ack("rb", &[("A", 3)], &["ra", "rb", "rc"])).unwrap();
|
|
351
|
+
|
|
352
|
+
let local = vec!["ra".to_string(), "rb".to_string()];
|
|
353
|
+
assert_eq!(acks.required_union(&local), vec!["ra", "rb", "rc"]);
|
|
354
|
+
match acks.evidence(&local) {
|
|
355
|
+
ReclamationEvidence::Blocked { waiting_on } => assert_eq!(waiting_on, vec!["rc"]),
|
|
356
|
+
other => panic!("a replica this node has never heard of must block, got {other:?}"),
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
#[test]
|
|
361
|
+
fn no_membership_at_all_is_not_permission() {
|
|
362
|
+
// A node that knows of no replicas has not established that it is
|
|
363
|
+
// alone. It has established nothing, and nothing is what it may act on.
|
|
364
|
+
let dir = tempfile::tempdir().unwrap();
|
|
365
|
+
let acks = store(&dir);
|
|
366
|
+
assert!(matches!(acks.evidence(&[]), ReclamationEvidence::Blocked { .. }));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
#[test]
|
|
370
|
+
fn a_stale_acknowledgement_is_not_a_missing_one_and_neither_is_permission() {
|
|
371
|
+
// Age is recorded and never consulted. An acknowledgement produced long
|
|
372
|
+
// ago still says what it says; what it does not do is advance.
|
|
373
|
+
let dir = tempfile::tempdir().unwrap();
|
|
374
|
+
let mut acks = store(&dir);
|
|
375
|
+
let mut ancient = ack("rb", &[("A", 2)], &["ra", "rb"]);
|
|
376
|
+
ancient.produced_at_ms = 0;
|
|
377
|
+
acks.record(ancient).unwrap();
|
|
378
|
+
acks.record(ack("ra", &[("A", 7)], &["ra", "rb"])).unwrap();
|
|
379
|
+
|
|
380
|
+
match acks.evidence(&["ra".into(), "rb".into()]) {
|
|
381
|
+
ReclamationEvidence::SafeThrough { frontier, .. } => {
|
|
382
|
+
assert_eq!(
|
|
383
|
+
frontier.get("A"),
|
|
384
|
+
2,
|
|
385
|
+
"the laggard sets the safe frontier, however old its report"
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
other => panic!("expected a safe frontier, got {other:?}"),
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// -- the minimum -------------------------------------------------------
|
|
393
|
+
|
|
394
|
+
#[test]
|
|
395
|
+
fn the_safe_frontier_is_the_minimum_over_every_required_replica() {
|
|
396
|
+
let dir = tempfile::tempdir().unwrap();
|
|
397
|
+
let mut acks = store(&dir);
|
|
398
|
+
acks.record(ack("ra", &[("A", 9), ("B", 4)], &["ra", "rb"])).unwrap();
|
|
399
|
+
acks.record(ack("rb", &[("A", 5), ("B", 6)], &["ra", "rb"])).unwrap();
|
|
400
|
+
|
|
401
|
+
match acks.evidence(&["ra".into(), "rb".into()]) {
|
|
402
|
+
ReclamationEvidence::SafeThrough { frontier, covered } => {
|
|
403
|
+
assert_eq!(frontier.get("A"), 5, "component-wise minimum, per origin");
|
|
404
|
+
assert_eq!(frontier.get("B"), 4);
|
|
405
|
+
assert_eq!(covered, vec!["ra", "rb"]);
|
|
406
|
+
}
|
|
407
|
+
other => panic!("expected a safe frontier, got {other:?}"),
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
#[test]
|
|
412
|
+
fn an_origin_one_replica_has_never_seen_is_not_safe_at_all() {
|
|
413
|
+
// rb has applied nothing from C. The minimum for C is therefore zero,
|
|
414
|
+
// and a zero component must not appear as though it were a position
|
|
415
|
+
// anything is safe through.
|
|
416
|
+
let dir = tempfile::tempdir().unwrap();
|
|
417
|
+
let mut acks = store(&dir);
|
|
418
|
+
acks.record(ack("ra", &[("A", 4), ("C", 9)], &["ra", "rb"])).unwrap();
|
|
419
|
+
acks.record(ack("rb", &[("A", 4)], &["ra", "rb"])).unwrap();
|
|
420
|
+
|
|
421
|
+
match acks.evidence(&["ra".into(), "rb".into()]) {
|
|
422
|
+
ReclamationEvidence::SafeThrough { frontier, .. } => {
|
|
423
|
+
assert_eq!(frontier.get("A"), 4);
|
|
424
|
+
assert_eq!(
|
|
425
|
+
frontier.get("C"),
|
|
426
|
+
0,
|
|
427
|
+
"one replica has none of C's history, so none of it is safe"
|
|
428
|
+
);
|
|
429
|
+
assert!(!frontier.clocks.contains_key("C"));
|
|
430
|
+
}
|
|
431
|
+
other => panic!("expected a safe frontier, got {other:?}"),
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
#[test]
|
|
436
|
+
fn evidence_survives_restart_and_still_blocks_for_the_same_replica() {
|
|
437
|
+
let dir = tempfile::tempdir().unwrap();
|
|
438
|
+
{
|
|
439
|
+
let mut acks = store(&dir);
|
|
440
|
+
acks.record(ack("rb", &[("A", 3)], &["ra", "rb", "rc"])).unwrap();
|
|
441
|
+
}
|
|
442
|
+
let recovered = store(&dir);
|
|
443
|
+
match recovered.evidence(&["ra".into(), "rb".into()]) {
|
|
444
|
+
ReclamationEvidence::Blocked { waiting_on } => {
|
|
445
|
+
assert_eq!(
|
|
446
|
+
waiting_on,
|
|
447
|
+
vec!["ra", "rc"],
|
|
448
|
+
"the union learned from rb's view survives the restart too"
|
|
449
|
+
);
|
|
450
|
+
}
|
|
451
|
+
other => panic!("expected blocked, got {other:?}"),
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
#[test]
|
|
456
|
+
fn origin_sequence_high_water_marks_are_carried() {
|
|
457
|
+
// Needed by the checkpoint that comes later: the operation log is also
|
|
458
|
+
// the source from which next_origin_sequence is recovered.
|
|
459
|
+
let dir = tempfile::tempdir().unwrap();
|
|
460
|
+
let mut acks = store(&dir);
|
|
461
|
+
let mut ack = ack("rb", &[("A", 3)], &["ra", "rb"]);
|
|
462
|
+
ack.origin_sequence_high_water.insert("A".to_string(), 7);
|
|
463
|
+
acks.record(ack).unwrap();
|
|
464
|
+
|
|
465
|
+
let recovered = store(&dir);
|
|
466
|
+
assert_eq!(
|
|
467
|
+
recovered.get("rb").unwrap().origin_sequence_high_water.get("A"),
|
|
468
|
+
Some(&7),
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
@@ -19,6 +19,21 @@
|
|
|
19
19
|
/// Deduplication/idempotency/retry logic is the protocol's responsibility via DistributedTransactionExecutor.
|
|
20
20
|
|
|
21
21
|
use crate::distributed_transactions::ReplicationMessage;
|
|
22
|
+
use crate::replica_acknowledgements::ReplicaAcknowledgement;
|
|
23
|
+
|
|
24
|
+
/// What actually goes on the wire.
|
|
25
|
+
///
|
|
26
|
+
/// Tagged, so a connection can carry envelopes and acknowledgements without
|
|
27
|
+
/// either being able to masquerade as the other. The alternative -- an
|
|
28
|
+
/// acknowledgement riding inside a `ReplicationMessage` with a placeholder
|
|
29
|
+
/// envelope -- would put a value on the receive path that only a flag
|
|
30
|
+
/// distinguishes from a real operation, and the receive path's whole job is
|
|
31
|
+
/// deciding what to apply.
|
|
32
|
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
|
33
|
+
pub enum Frame {
|
|
34
|
+
Replication(Box<ReplicationMessage>),
|
|
35
|
+
Acknowledgement(Box<ReplicaAcknowledgement>),
|
|
36
|
+
}
|
|
22
37
|
use crate::replication_protocol::{ProtocolError, ProtocolMetrics, ProtocolTransport};
|
|
23
38
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
24
39
|
use std::sync::Arc;
|
|
@@ -37,6 +52,12 @@ pub struct TcpTransport {
|
|
|
37
52
|
metrics: Arc<ProtocolMetrics>,
|
|
38
53
|
is_connected: Arc<AtomicBool>,
|
|
39
54
|
receive_buffer: Arc<Mutex<Vec<ReplicationMessage>>>,
|
|
55
|
+
/// Acknowledgements read off the socket, waiting to be drained.
|
|
56
|
+
///
|
|
57
|
+
/// They arrive interleaved with envelopes on the same connection, so
|
|
58
|
+
/// `receive` parks them here rather than changing its return type and the
|
|
59
|
+
/// trait every caller implements against.
|
|
60
|
+
ack_buffer: Arc<Mutex<Vec<ReplicaAcknowledgement>>>,
|
|
40
61
|
}
|
|
41
62
|
|
|
42
63
|
impl TcpTransport {
|
|
@@ -49,6 +70,7 @@ impl TcpTransport {
|
|
|
49
70
|
metrics: Arc::new(ProtocolMetrics::new()),
|
|
50
71
|
is_connected: Arc::new(AtomicBool::new(false)),
|
|
51
72
|
receive_buffer: Arc::new(Mutex::new(Vec::with_capacity(MESSAGE_BUFFER_SIZE))),
|
|
73
|
+
ack_buffer: Arc::new(Mutex::new(Vec::new())),
|
|
52
74
|
}
|
|
53
75
|
}
|
|
54
76
|
|
|
@@ -76,6 +98,44 @@ impl TcpTransport {
|
|
|
76
98
|
}
|
|
77
99
|
}
|
|
78
100
|
|
|
101
|
+
impl TcpTransport {
|
|
102
|
+
/// Send an acknowledgement over the same connection envelopes use.
|
|
103
|
+
///
|
|
104
|
+
/// Not part of `ProtocolTransport`: that trait is the replication protocol,
|
|
105
|
+
/// and an acknowledgement is a statement about what has been applied rather
|
|
106
|
+
/// than something to apply.
|
|
107
|
+
pub async fn send_acknowledgement(
|
|
108
|
+
&self,
|
|
109
|
+
ack: ReplicaAcknowledgement,
|
|
110
|
+
) -> Result<(), ProtocolError> {
|
|
111
|
+
let mut stream_guard = self.stream.lock().await;
|
|
112
|
+
let stream = stream_guard
|
|
113
|
+
.as_mut()
|
|
114
|
+
.ok_or(ProtocolError::ConnectionError("not connected".to_string()))?;
|
|
115
|
+
let payload = serde_json::to_vec(&Frame::Acknowledgement(Box::new(ack)))
|
|
116
|
+
.map_err(|e| ProtocolError::SerializationError(e.to_string()))?;
|
|
117
|
+
stream
|
|
118
|
+
.write_all(&(payload.len() as u32).to_be_bytes())
|
|
119
|
+
.await
|
|
120
|
+
.map_err(|e| ProtocolError::TransportError(e.to_string()))?;
|
|
121
|
+
stream
|
|
122
|
+
.write_all(&payload)
|
|
123
|
+
.await
|
|
124
|
+
.map_err(|e| ProtocolError::TransportError(e.to_string()))?;
|
|
125
|
+
stream
|
|
126
|
+
.flush()
|
|
127
|
+
.await
|
|
128
|
+
.map_err(|e| ProtocolError::TransportError(e.to_string()))?;
|
|
129
|
+
self.metrics.record_send(4 + payload.len());
|
|
130
|
+
Ok(())
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/// Take the acknowledgements read off the socket since the last drain.
|
|
134
|
+
pub async fn take_acknowledgements(&self) -> Vec<ReplicaAcknowledgement> {
|
|
135
|
+
std::mem::take(&mut *self.ack_buffer.lock().await)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
79
139
|
#[async_trait::async_trait]
|
|
80
140
|
impl ProtocolTransport for TcpTransport {
|
|
81
141
|
async fn send(&self, message: ReplicationMessage) -> Result<(), ProtocolError> {
|
|
@@ -85,7 +145,7 @@ impl ProtocolTransport for TcpTransport {
|
|
|
85
145
|
.ok_or(ProtocolError::ConnectionError("not connected".to_string()))?;
|
|
86
146
|
|
|
87
147
|
// Serialize message using serde_json (bincode has issues with serde_json::Value)
|
|
88
|
-
let payload = serde_json::to_vec(&message)
|
|
148
|
+
let payload = serde_json::to_vec(&Frame::Replication(Box::new(message)))
|
|
89
149
|
.map_err(|e| ProtocolError::SerializationError(e.to_string()))?;
|
|
90
150
|
|
|
91
151
|
let payload_len = payload.len() as u32;
|
|
@@ -152,12 +212,21 @@ impl ProtocolTransport for TcpTransport {
|
|
|
152
212
|
.await
|
|
153
213
|
.map_err(|e| ProtocolError::TransportError(e.to_string()))?;
|
|
154
214
|
|
|
155
|
-
let
|
|
215
|
+
let frame: Frame = serde_json::from_slice(&payload)
|
|
156
216
|
.map_err(|e| ProtocolError::SerializationError(e.to_string()))?;
|
|
157
217
|
|
|
158
218
|
self.metrics.record_receive(4 + payload_len);
|
|
159
219
|
|
|
160
|
-
|
|
220
|
+
match frame {
|
|
221
|
+
Frame::Replication(message) => Ok(vec![*message]),
|
|
222
|
+
Frame::Acknowledgement(ack) => {
|
|
223
|
+
// Read off the socket and parked. The bytes crossed the
|
|
224
|
+
// network exactly as an envelope's do, and the counters
|
|
225
|
+
// above record them.
|
|
226
|
+
self.ack_buffer.lock().await.push(*ack);
|
|
227
|
+
Ok(Vec::new())
|
|
228
|
+
}
|
|
229
|
+
}
|
|
161
230
|
}
|
|
162
231
|
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
|
|
163
232
|
// No data available right now
|