1mod deadline;
13mod exit_view;
14mod installation;
15mod poll;
16mod receive;
17mod storage;
18mod validation;
19
20pub use installation::ActivationTicket;
21pub use validation::ValidationTicket;
22
23use std::time::Duration;
24
25use ozzy_proto::NodeId;
26
27use crate::wire::Control;
28use crate::{
29 Configuration, Digest, InstallingView, LogSource, NormalReplica, OpNumber, Prefix,
30 PromiseTicket, ReplicaSnapshot, ReplicationError, Scope, SelectedView, Status, ViewChange,
31 ViewChangeError, VoterIndex, VoterSet, Voters,
32};
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Timing {
37 pub heartbeat: Duration,
39 pub primary_timeout: Duration,
41 pub retransmit: Duration,
43 pub election_timeout: Duration,
45 pub max_election_timeout: Duration,
47}
48
49impl Timing {
50 fn validate(self, now: Duration) -> Result<(), DriverError> {
51 if self.heartbeat.is_zero()
52 || self.retransmit.is_zero()
53 || self.heartbeat >= self.primary_timeout
54 || self.retransmit >= self.election_timeout
55 || self.election_timeout > self.max_election_timeout
56 {
57 return Err(DriverError::InvalidTiming);
58 }
59 if now
60 .checked_add(self.max_election_timeout.max(self.primary_timeout))
61 .is_none()
62 {
63 return Err(DriverError::TimeExhausted);
64 }
65 Ok(())
66 }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Action {
72 Broadcast(Control),
74 Send {
76 to: NodeId,
78 message: Control,
80 },
81 PersistPromise(PromiseTicket),
83}
84
85#[derive(Debug)]
87#[expect(
88 clippy::large_enum_variant,
89 reason = "move preallocated roles without boxing"
90)]
91pub enum Role {
92 Normal(NormalReplica),
94 ViewChanging(ViewChange),
96 Installing(InstallingView),
98 Fenced(Scope),
101}
102
103#[derive(Debug)]
108pub struct ReplicaDriver {
109 role: Role,
110 configuration: Configuration,
111 local: VoterIndex,
112 timing: Timing,
113 now: Duration,
114 contact_deadline: Duration,
115 progress_deadline: Duration,
116 persistence_deadline: Duration,
117 storage_busy_since: Option<Duration>,
119 election_deadline: Duration,
120 election_delay: Duration,
121 retry_at: Duration,
122 start_pending: bool,
123 report_pending: bool,
124 commit_pending: bool,
125 activation_pending: VoterSet,
128 exit_votes: VoterSet,
130 exit_heard_at: Voters<Duration>,
132 exit_retry_at: Option<Duration>,
134 exit_echo: Option<(Scope, VoterSet)>,
137 exit_echo_at: Voters<Duration>,
139}
140
141impl ReplicaDriver {
142 pub fn from_normal(
145 normal: NormalReplica,
146 now: Duration,
147 timing: Timing,
148 ) -> Result<Self, DriverError> {
149 let (configuration, local) = normal.driver_identity();
150 Self::new(Role::Normal(normal), configuration, local, now, timing)
151 }
152
153 pub fn from_view_change(
156 changing: ViewChange,
157 now: Duration,
158 timing: Timing,
159 ) -> Result<Self, DriverError> {
160 let configuration = changing.configuration;
161 let local = changing.local;
162 Self::new(
163 Role::ViewChanging(changing),
164 configuration,
165 local,
166 now,
167 timing,
168 )
169 }
170
171 fn new(
172 role: Role,
173 configuration: Configuration,
174 local: VoterIndex,
175 now: Duration,
176 timing: Timing,
177 ) -> Result<Self, DriverError> {
178 timing.validate(now)?;
179 let changing = matches!(role, Role::ViewChanging(_));
180 let activating =
181 matches!(&role, Role::Normal(normal) if !normal.snapshot().ready_for_appends);
182 Ok(Self {
183 role,
184 configuration,
185 local,
186 timing,
187 now,
188 contact_deadline: now.saturating_add(timing.primary_timeout),
189 persistence_deadline: now.saturating_add(timing.primary_timeout),
190 storage_busy_since: None,
191 progress_deadline: now
192 + if activating {
193 timing.election_timeout
194 } else {
195 timing.primary_timeout
196 },
197 election_deadline: now.saturating_add(timing.election_timeout),
198 election_delay: timing.election_timeout,
199 retry_at: now
200 + if changing {
201 timing.retransmit
202 } else {
203 timing.heartbeat
204 },
205 start_pending: changing,
206 report_pending: changing,
207 commit_pending: false,
208 activation_pending: VoterSet::EMPTY,
209 exit_votes: VoterSet::EMPTY,
210 exit_heard_at: Voters::splat(Duration::ZERO),
211 exit_retry_at: None,
212 exit_echo: None,
213 exit_echo_at: Voters::splat(Duration::ZERO),
214 })
215 }
216
217 pub fn normal(&self) -> Option<&NormalReplica> {
219 match &self.role {
220 Role::Normal(normal) => Some(normal),
221 Role::ViewChanging(_) | Role::Installing(_) | Role::Fenced(_) => None,
222 }
223 }
224
225 pub fn election_needs_sync(&self) -> bool {
227 let Role::ViewChanging(changing) = &self.role else {
228 return false;
229 };
230 let journal = changing.normal_snapshot().journal;
231 journal.written == journal.accepted && journal.written > journal.durable
232 }
233
234 pub fn scope(&self) -> Scope {
236 match &self.role {
237 Role::Normal(normal) => normal.scope(),
238 Role::ViewChanging(changing) => changing.scope(),
239 Role::Installing(installing) => installing.requested_scope(),
240 Role::Fenced(scope) => *scope,
241 }
242 }
243
244 pub fn into_role(self) -> Role {
247 self.role
248 }
249
250 pub fn select(
253 &mut self,
254 lookup: impl FnMut(LogSource, Prefix) -> Option<Digest>,
255 ) -> Result<SelectedView, DriverError> {
256 Ok(self.changing()?.select(lookup)?)
257 }
258
259 pub fn history_sources(&self) -> [Option<LogSource>; 3] {
261 match &self.role {
262 Role::ViewChanging(changing) => changing.history_sources(),
263 Role::Normal(_) | Role::Installing(_) | Role::Fenced(_) => [None; 3],
264 }
265 }
266
267 pub fn lookup_ops(&self) -> [Option<OpNumber>; 8] {
270 match &self.role {
271 Role::ViewChanging(changing) => changing.lookup_ops(),
272 Role::Normal(_) | Role::Installing(_) | Role::Fenced(_) => [None; 8],
273 }
274 }
275
276 fn changing(&mut self) -> Result<&mut ViewChange, DriverError> {
277 match &mut self.role {
278 Role::ViewChanging(changing) => Ok(changing),
279 Role::Normal(_) | Role::Installing(_) => Err(ReplicationError::WrongRole.into()),
280 Role::Fenced(_) => Err(ViewChangeError::Faulted.into()),
281 }
282 }
283
284 fn require_normal(&self) -> Result<&NormalReplica, DriverError> {
285 Ok(self.normal().ok_or(ReplicationError::NotNormal)?)
286 }
287
288 fn require_healthy(&self) -> Result<(), DriverError> {
290 match &self.role {
291 Role::Normal(normal) if normal.snapshot().status == Status::Faulted => {
292 Err(ViewChangeError::Faulted.into())
293 }
294 Role::ViewChanging(changing)
295 if changing.normal_snapshot().status == Status::Faulted =>
296 {
297 Err(ViewChangeError::Faulted.into())
298 }
299 Role::Installing(installing) => Ok(installing.require_pending()?),
300 Role::Fenced(_) => Err(ViewChangeError::Faulted.into()),
301 Role::Normal(_) | Role::ViewChanging(_) => Ok(()),
302 }
303 }
304
305 fn take_role(&mut self) -> Role {
308 let fenced = Role::Fenced(self.scope());
309 std::mem::replace(&mut self.role, fenced)
310 }
311
312 fn observe_time(&mut self, now: Duration) -> Result<(), DriverError> {
313 if now < self.now {
314 return Err(DriverError::ClockRegressed);
315 }
316 self.timing.validate(now)?;
317 self.now = now;
318 Ok(())
319 }
320
321 fn progress_timeout(&self) -> Duration {
322 if self
323 .normal()
324 .is_some_and(|normal| normal.snapshot().ready_for_appends)
325 {
326 self.timing.primary_timeout
327 } else {
328 self.election_delay
329 }
330 }
331
332 fn observe_normal_progress(
333 &mut self,
334 previous: &ReplicaSnapshot,
335 current: &ReplicaSnapshot,
336 now: Duration,
337 ) {
338 if current.committed != previous.committed {
339 self.progress_deadline = now.saturating_add(self.progress_timeout());
340 }
341 if current.journal.durable > previous.journal.durable {
342 self.persistence_deadline = now.saturating_add(self.timing.primary_timeout);
343 }
344 }
345
346 fn normal_timed_out(&self, snapshot: &ReplicaSnapshot) -> bool {
347 let primary = VoterIndex::primary(snapshot.scope.view) == self.local;
348 let outstanding = snapshot.accepted != snapshot.committed || !snapshot.ready_for_appends;
349 (!primary && self.now >= self.contact_deadline)
350 || (outstanding && self.now >= self.progress_deadline)
351 || (snapshot.accepted.op > snapshot.journal.durable
352 && self.now >= self.persistence_deadline)
353 || self
354 .storage_busy_since
355 .is_some_and(|since| self.now >= since.saturating_add(self.timing.primary_timeout))
356 }
357
358 fn next_view(&mut self) -> Result<(), DriverError> {
359 let view = self
360 .scope()
361 .view
362 .checked_add(1)
363 .ok_or(ViewChangeError::ViewExhausted)?;
364 self.change_view(view)
365 }
366
367 fn change_view(&mut self, view: u64) -> Result<(), DriverError> {
368 match &mut self.role {
369 Role::ViewChanging(changing) => changing.advance_view(view)?,
370 Role::Installing(installing) => installing.request_view(view)?,
371 Role::Normal(normal) if normal.snapshot().status == Status::Faulted => {
372 return Err(ViewChangeError::Faulted.into());
373 }
374 Role::Normal(_) => {
375 let Role::Normal(normal) = self.take_role() else {
376 return Err(ViewChangeError::Faulted.into());
377 };
378 self.role = Role::ViewChanging(normal.into_view_change(view)?);
379 }
380 Role::Fenced(_) => return Err(ViewChangeError::Faulted.into()),
381 }
382 self.exit_votes = VoterSet::EMPTY;
383 self.exit_retry_at = None;
384 self.election_deadline = self.now.saturating_add(self.election_delay);
385 self.retry_at = self.now.saturating_add(self.timing.retransmit);
386 self.start_pending = true;
387 self.report_pending = true;
388 self.commit_pending = false;
389 self.activation_pending = VoterSet::EMPTY;
390 Ok(())
391 }
392}
393
394#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
396pub enum DriverError {
397 #[error("invalid replica timing intervals")]
399 InvalidTiming,
400 #[error("replica clock regressed")]
402 ClockRegressed,
403 #[error("replica clock exhausted")]
405 TimeExhausted,
406 #[error("stale replica application validation")]
408 StaleValidation,
409 #[error(transparent)]
411 Replication(#[from] ReplicationError),
412 #[error(transparent)]
414 ViewChange(#[from] ViewChangeError),
415}