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
|
//! The coordinator: the node that received the proposal counts the votes (`vote`) and
//! writes the decision.
//!
//! It commits as soon as a majority of the electorate voted for the remake. It aborts
//! if, before that:
//! * an operator requested an abort,
//! * the local epoch changed,
//! * a competing remake of the same epoch committed,
//! * a majority is out of reach (too many members voted for a competing remake), or
//! * the voting period (`settleSecs`) passed without a majority.
//!
//! Committing builds the snapshot at the base heads and records the new epoch, so
//! every node can verify its own build against it.
//!
//! The task lives only in memory. If the coordinator dies, nobody decides and the
//! proposal expires (its votes become void).
use std::time::Duration;
use tracing::{info, warn};
use super::Host;
use super::records::{self, Decision, Record};
use super::snapshot;
use super::vote;
use crate::document::store::StoreError;
const TICK: Duration = Duration::from_secs(1);
pub(crate) async fn run<H: Host>(host: H, id: String) {
info!(remake = %id, "Coordinating remake");
loop {
tokio::time::sleep(TICK).await;
match step(&host, &id).await {
Ok(true) => return,
Ok(false) => {}
Err(error) => {
warn!(remake = %id, error = %format!("{error:#}"), "Coordinator step failed; retrying");
}
}
}
}
/// One evaluation. Returns true once the coordinator is done.
async fn step<H: Host>(host: &H, id: &str) -> Result<bool, StoreError> {
let wanted = id.to_owned();
let (record, all) = host
.read_doc(move |doc| (records::load(doc, &wanted), records::load_all(doc)))
.await;
let Some(record) = record else {
warn!(remake = %id, "Remake record vanished; stopping coordinator");
return Ok(true);
};
if record.decision.is_some() {
return Ok(true);
}
let now = records::unix_millis();
let grace = host.dormant_after().as_millis() as u64;
if let Some(reason) = abort_reason(host, id, &record, &all, now, grace) {
decide_abort(host, id, reason).await?;
return Ok(true);
}
let tally = vote::tally(id, &record, &all, now, grace);
if tally.reached() {
info!(remake = %id, votes = %tally, "Majority reached");
commit(host, id, &record).await?;
return Ok(true);
}
if tally.out_of_reach() {
decide_abort(host, id, format!("a majority is out of reach: {tally}")).await?;
return Ok(true);
}
if now >= record.proposal.settle_until {
decide_abort(
host,
id,
format!("no majority in the voting period: {tally}"),
)
.await?;
return Ok(true);
}
Ok(false)
}
fn abort_reason<H: Host>(
host: &H,
id: &str,
record: &Record,
all: &[(String, Record)],
now: u64,
grace: u64,
) -> Option<String> {
let proposal = &record.proposal;
if let Some(request) = &record.abort_requested {
return Some(format!("aborted by operator via {}", request.by));
}
if records::EpochRecord::from(host.current_epoch()) != proposal.from_epoch {
return Some("local epoch changed during the vote".to_owned());
}
if let Some((other, _)) = all.iter().find(|(other, candidate)| {
other != id
&& candidate.proposal.from_epoch == proposal.from_epoch
&& candidate.phase(now, grace) == records::Phase::Committed
}) {
return Some(format!("competing remake {other} committed"));
}
None
}
async fn commit<H: Host>(host: &H, id: &str, record: &Record) -> Result<(), StoreError> {
let Some(request) = record.snapshot_request(id) else {
return decide_abort(
host,
id,
"unreadable epoch or base heads in proposal".into(),
)
.await;
};
// Clone under the read lock, build without any lock.
let copy = host.read_doc(|doc| doc.clone()).await;
let mut snapshot = match snapshot::build_detached(copy, request).await {
Ok((snapshot, _copy)) => snapshot,
Err(error) => {
return decide_abort(host, id, format!("snapshot build failed: {error}")).await;
}
};
let to_epoch = snapshot.epoch;
let snapshot_bytes = snapshot.doc.save().len() as u64;
let decision = Decision::Committed {
to_epoch: to_epoch.into(),
snapshot_bytes,
decided_at: records::unix_millis(),
};
write_decision(host, id, decision).await?;
// The local switch reuses it instead of building again.
host.remake().store_prebuilt(id, snapshot);
info!(remake = %id, to_epoch = %to_epoch, snapshot_bytes, "Remake committed");
Ok(())
}
async fn decide_abort<H: Host>(host: &H, id: &str, reason: String) -> Result<(), StoreError> {
warn!(remake = %id, reason = %reason, "Remake aborted");
write_decision(
host,
id,
Decision::Aborted {
reason,
decided_at: records::unix_millis(),
},
)
.await
}
async fn write_decision<H: Host>(host: &H, id: &str, decision: Decision) -> Result<(), StoreError> {
let id = id.to_owned();
host.commit_doc(move |doc| records::write_decision(doc, &id, &decision))
.await
}
|