foundationdb/recipes/leader_election/types.rs
1// Copyright 2024 foundationdb-rs developers
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Public values exchanged with the Dynamo-style lease protocol.
9
10use super::{LeaderElectionError, Result};
11use crate::recipes::ranked_register::Rank;
12use std::time::Duration;
13
14/// Identifies one caller process incarnation participating in an election.
15///
16/// Keep one ID for the lifetime of a process incarnation, then use a fresh ID
17/// after restart. Reusing an ID across concurrent callers is protocol misuse:
18/// fencing ranks preserve durable data safety, but the callers cannot safely
19/// coordinate leadership or protected work as one incarnation.
20#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct ParticipantId(String);
22
23impl ParticipantId {
24 /// Maximum tuple-encoded size of a process-incarnation ID.
25 ///
26 /// The limit includes the tuple string type code, terminator, and escaping
27 /// of embedded NUL bytes. It leaves enough space for the rest of the
28 /// durable election state below FoundationDB's 100,000-byte value limit.
29 pub const MAX_ENCODED_BYTES: usize = 95_000;
30
31 /// Creates a non-empty process-incarnation ID within the encoded-size limit.
32 ///
33 /// The value is persisted as the durable owner when this participant leads,
34 /// so it must distinguish a restarted process from its previous incarnation.
35 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(value)))]
36 pub fn new(value: impl Into<String>) -> Result<Self> {
37 let value = value.into();
38 if value.is_empty() {
39 return Err(LeaderElectionError::InvalidParticipantId);
40 }
41 let encoded_size = value
42 .bytes()
43 .filter(|byte| *byte == 0)
44 .fold(value.len().saturating_add(2), |size, _| {
45 size.saturating_add(1)
46 });
47 if encoded_size > Self::MAX_ENCODED_BYTES {
48 return Err(LeaderElectionError::ParticipantIdTooLarge {
49 encoded_size,
50 limit: Self::MAX_ENCODED_BYTES,
51 });
52 }
53 Ok(Self(value))
54 }
55
56 /// Returns the caller-supplied process-incarnation ID as text.
57 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
58 pub fn as_str(&self) -> &str {
59 &self.0
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn participant_id_accepts_the_encoded_size_limit() {
69 let value = "\0".repeat((ParticipantId::MAX_ENCODED_BYTES - 2) / 2);
70
71 assert!(ParticipantId::new(value).is_ok());
72 }
73
74 #[test]
75 fn participant_id_rejects_an_encoded_size_above_the_limit() {
76 let value = "\0".repeat(ParticipantId::MAX_ENCODED_BYTES / 2);
77
78 match ParticipantId::new(value) {
79 Err(LeaderElectionError::ParticipantIdTooLarge {
80 encoded_size,
81 limit,
82 }) => {
83 assert_eq!(encoded_size, ParticipantId::MAX_ENCODED_BYTES + 2);
84 assert_eq!(limit, ParticipantId::MAX_ENCODED_BYTES);
85 }
86 result => panic!("expected an oversized participant ID error, got {result:?}"),
87 }
88 }
89
90 const LEASE: Duration = Duration::from_secs(10);
91
92 fn secs(value: u64) -> Duration {
93 Duration::from_secs(value)
94 }
95
96 fn observed(owner: &str, rank: u64, lease_duration: Duration, at: Duration) -> LocalState {
97 LocalState::Observation(Observation::new(
98 ParticipantId::new(owner).unwrap(),
99 Rank::from(rank),
100 lease_duration,
101 at,
102 ))
103 }
104
105 fn next_observation(owner: &str, rank: u64, timer: ObservationTimer) -> NextState {
106 NextState::Observation {
107 owner: ParticipantId::new(owner).unwrap(),
108 rank: Rank::from(rank),
109 lease_duration: LEASE,
110 timer,
111 }
112 }
113
114 #[test]
115 fn input_measures_elapsed_from_the_anchor_and_saturates() {
116 let leader = LocalState::Leadership(Leadership::new(Rank::from(3), LEASE, secs(5)));
117 assert_eq!(LocalState::unknown().input(secs(9)), PollInput::Unknown);
118 assert_eq!(
119 leader.input(secs(9)),
120 PollInput::Leadership {
121 rank: Rank::from(3),
122 lease_duration: LEASE,
123 elapsed: secs(4),
124 }
125 );
126 assert_eq!(
127 observed("a", 3, LEASE, secs(5)).input(secs(2)),
128 PollInput::Observation {
129 owner: ParticipantId::new("a").unwrap(),
130 rank: Rank::from(3),
131 lease_duration: LEASE,
132 elapsed: Duration::ZERO,
133 }
134 );
135 }
136
137 #[test]
138 fn adopt_anchors_leadership_at_attempt_start() {
139 let next = NextState::Leadership {
140 rank: Rank::from(4),
141 lease_duration: LEASE,
142 };
143 for local in [LocalState::unknown(), observed("a", 3, LEASE, secs(1))] {
144 let adopted = local.adopt(secs(5), secs(9), &next);
145 let leadership = adopted.leadership().unwrap();
146 assert_eq!(leadership.rank(), Rank::from(4));
147 assert_eq!(leadership.lease_duration(), LEASE);
148 assert_eq!(leadership.last_renewed_at(), secs(5));
149 }
150 }
151
152 #[test]
153 fn adopt_anchors_a_reset_observation_after_success() {
154 let adopted = observed("a", 3, LEASE, secs(1)).adopt(
155 secs(5),
156 secs(9),
157 &next_observation("a", 3, ObservationTimer::Reset),
158 );
159 assert_eq!(adopted, observed("a", 3, LEASE, secs(9)));
160 }
161
162 #[test]
163 fn adopt_preserve_keeps_the_matching_anchor() {
164 let adopted = observed("a", 3, LEASE, secs(1)).adopt(
165 secs(5),
166 secs(9),
167 &next_observation("a", 3, ObservationTimer::Preserve),
168 );
169 assert_eq!(adopted, observed("a", 3, LEASE, secs(1)));
170 }
171
172 #[test]
173 fn adopt_preserve_falls_back_to_reset_when_self_does_not_match() {
174 let next = next_observation("a", 3, ObservationTimer::Preserve);
175 for local in [
176 LocalState::unknown(),
177 LocalState::Leadership(Leadership::new(Rank::from(3), LEASE, secs(1))),
178 observed("b", 3, LEASE, secs(1)),
179 observed("a", 2, LEASE, secs(1)),
180 observed("a", 3, LEASE + Duration::from_nanos(1), secs(1)),
181 ] {
182 assert_eq!(
183 local.adopt(secs(5), secs(9), &next),
184 observed("a", 3, LEASE, secs(9))
185 );
186 }
187 }
188}
189
190/// What the polling caller claims about the durable state, with the time
191/// elapsed since its anchor measured on the caller's own monotonic clock.
192///
193/// The recipe holds no time: it only compares the claimed tuple with durable
194/// state and `elapsed` with the claimed `lease_duration`. Local callers build
195/// it with [`LocalState::input`]. A transport service relaying a remote caller
196/// builds it from the request and must authenticate that caller.
197///
198/// Honest `elapsed` reporting is a protocol precondition: the exact-tuple
199/// check only rejects stale or mismatched callers. A caller, even an
200/// authenticated one, that inflates `elapsed` for the exact current tuple can
201/// take over early. A service that does not trust its callers must enforce
202/// timing itself.
203#[derive(Debug, Clone, PartialEq, Eq)]
204pub enum PollInput {
205 /// The caller has not adopted any poll result. It follows any durable owner.
206 Unknown,
207 /// An exact durable owner record the caller observed and is not authorized to renew.
208 ///
209 /// Only an exact match of `owner`, `rank`, and `lease_duration` with
210 /// durable state, with `elapsed` at least `lease_duration`, permits a
211 /// takeover (or a reacquisition when `owner` is the polling participant).
212 Observation {
213 owner: ParticipantId,
214 rank: Rank,
215 lease_duration: Duration,
216 elapsed: Duration,
217 },
218 /// The durable owner record the polling participant claims to hold.
219 ///
220 /// The owner is the participant passed to
221 /// [`super::LeaderElection::poll`]. It renews only on an exact durable
222 /// match with `elapsed` strictly below `lease_duration`.
223 Leadership {
224 rank: Rank,
225 lease_duration: Duration,
226 elapsed: Duration,
227 },
228}
229
230/// Whether a follower's observation timer restarts or keeps running.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum ObservationTimer {
233 /// The observed record is new or changed: anchor a fresh timer once the
234 /// enclosing transaction is known to have committed.
235 Reset,
236 /// The observed record is exactly the one claimed by the input: keep the
237 /// existing anchor.
238 Preserve,
239}
240
241/// The clock-free state a caller carries to its next poll.
242///
243/// It holds no time. The caller anchors it on its own monotonic clock, see
244/// [`LocalState::adopt`] for the anchoring rules.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum NextState {
247 /// The polling participant staged itself as owner of this exact record.
248 ///
249 /// `lease_duration` is the polling handle's configured duration, which is
250 /// the one persisted with `rank`.
251 Leadership {
252 rank: Rank,
253 lease_duration: Duration,
254 },
255 /// The exact durable owner record observed by this poll.
256 Observation {
257 owner: ParticipantId,
258 rank: Rank,
259 lease_duration: Duration,
260 timer: ObservationTimer,
261 },
262}
263
264/// Optional caller-owned helper holding the local anchors between polls.
265///
266/// No variant is persisted or transferable to another process incarnation.
267/// Its anchors are readings of the caller's monotonic clock. Build each
268/// poll's [`PollInput`] with [`Self::input`], then replace it with
269/// [`Self::adopt`] only after the enclosing
270/// [`Database::run`](crate::Database::run) succeeds.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub enum LocalState {
273 /// No durable state has been adopted by this caller.
274 Unknown,
275 /// An exact durable owner record this caller is not authorized to renew.
276 ///
277 /// The preserved observation time can permit a conditional takeover only
278 /// if a later poll sees the same owner, revision, and lease duration.
279 Observation(Observation),
280 /// The exact durable owner record this caller may attempt to renew locally.
281 ///
282 /// It does not prove current durable ownership. A later poll must still
283 /// match the record and find this caller's local lease interval unexpired.
284 Leadership(Leadership),
285}
286
287impl LocalState {
288 /// Returns the initial state for a caller that has not adopted a poll result.
289 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug"))]
290 pub fn unknown() -> Self {
291 Self::Unknown
292 }
293
294 /// Returns the poll input claiming this state, with elapsed time measured to `now`.
295 ///
296 /// `now` is a reading of the caller's monotonic clock taken before the
297 /// enclosing [`Database::run`](crate::Database::run). Keep the same input
298 /// for every retry attempt of that run. Elapsed time saturates at zero if
299 /// `now` precedes the anchor.
300 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
301 pub fn input(&self, now: Duration) -> PollInput {
302 match self {
303 Self::Unknown => PollInput::Unknown,
304 Self::Observation(observation) => PollInput::Observation {
305 owner: observation.owner.clone(),
306 rank: observation.rank,
307 lease_duration: observation.lease_duration,
308 elapsed: now.saturating_sub(observation.first_observed_at),
309 },
310 Self::Leadership(leadership) => PollInput::Leadership {
311 rank: leadership.rank,
312 lease_duration: leadership.lease_duration,
313 elapsed: now.saturating_sub(leadership.last_renewed_at),
314 },
315 }
316 }
317
318 /// Anchors a committed poll's [`NextState`] and returns the state for the next poll.
319 ///
320 /// Call it only after the enclosing [`Database::run`](crate::Database::run)
321 /// succeeds. `attempt_started_at` is the reading passed to [`Self::input`]
322 /// for that run and `adopted_at` a fresh reading taken after it succeeded.
323 ///
324 /// - Leadership is anchored at `attempt_started_at`, before the durable
325 /// read, so read, retry, and commit delay only shorten local validity.
326 /// - A reset observation is anchored at `adopted_at`, so its timer starts
327 /// only once its durable read is known to have committed.
328 /// - A preserved observation keeps this state's anchor when this state is
329 /// the same observation, and otherwise falls back to a reset.
330 #[cfg_attr(
331 feature = "trace",
332 tracing::instrument(level = "debug", skip(self, next))
333 )]
334 pub fn adopt(
335 self,
336 attempt_started_at: Duration,
337 adopted_at: Duration,
338 next: &NextState,
339 ) -> Self {
340 match next {
341 NextState::Leadership {
342 rank,
343 lease_duration,
344 } => Self::Leadership(Leadership::new(*rank, *lease_duration, attempt_started_at)),
345 NextState::Observation {
346 owner,
347 rank,
348 lease_duration,
349 timer,
350 } => match self {
351 Self::Observation(observation)
352 if *timer == ObservationTimer::Preserve
353 && observation.owner == *owner
354 && observation.rank == *rank
355 && observation.lease_duration == *lease_duration =>
356 {
357 Self::Observation(observation)
358 }
359 _ => Self::Observation(Observation::new(
360 owner.clone(),
361 *rank,
362 *lease_duration,
363 adopted_at,
364 )),
365 },
366 }
367 }
368
369 /// Returns the adopted observation, if this caller is following an owner.
370 ///
371 /// `None` means either no state has been adopted or this caller holds a
372 /// local leadership token. It does not query durable state.
373 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
374 pub fn observation(&self) -> Option<&Observation> {
375 match self {
376 Self::Observation(observation) => Some(observation),
377 Self::Unknown | Self::Leadership(_) => None,
378 }
379 }
380
381 /// Returns the adopted local leadership token, if any.
382 ///
383 /// It is not proof that the caller remains the durable owner. Poll with
384 /// [`Self::input`]. To resign, pass this caller's own participant with
385 /// [`Leadership::rank`] and [`Leadership::lease_duration`] to
386 /// [`super::LeaderElection::resign`].
387 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
388 pub fn leadership(&self) -> Option<&Leadership> {
389 match self {
390 Self::Leadership(leadership) => Some(leadership),
391 Self::Unknown | Self::Observation(_) => None,
392 }
393 }
394}
395
396/// An exact durable owner record adopted after a successful outer transaction.
397///
398/// This records the owner, revision, and persisted duration observed together,
399/// plus the caller-clock instant at which that result was adopted. It is valid
400/// for takeover timing only while a later poll finds the same durable record.
401#[derive(Debug, Clone, PartialEq, Eq)]
402pub struct Observation {
403 owner: ParticipantId,
404 rank: Rank,
405 lease_duration: Duration,
406 first_observed_at: Duration,
407}
408
409impl Observation {
410 pub(crate) fn new(
411 owner: ParticipantId,
412 rank: Rank,
413 lease_duration: Duration,
414 first_observed_at: Duration,
415 ) -> Self {
416 Self {
417 owner,
418 rank,
419 lease_duration,
420 first_observed_at,
421 }
422 }
423
424 /// Returns the owner in the exact durable record this caller observed.
425 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
426 pub fn owner(&self) -> &ParticipantId {
427 &self.owner
428 }
429
430 /// Returns the exact observed durable revision as a fencing rank.
431 ///
432 /// A changed rank makes this observation ineligible to authorize a
433 /// takeover, even if the owner text is unchanged.
434 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
435 pub fn rank(&self) -> Rank {
436 self.rank
437 }
438
439 /// Returns the lease duration persisted with the observed revision.
440 ///
441 /// Followers use this value, rather than a handle's configured duration,
442 /// when deciding whether the unchanged record is old enough to challenge.
443 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
444 pub fn lease_duration(&self) -> Duration {
445 self.lease_duration
446 }
447
448 /// Returns the caller-clock time when this observation was adopted.
449 ///
450 /// Compare it only with readings from the same caller's monotonic clock.
451 /// It is not a durable timestamp or a deadline for the observed owner.
452 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
453 pub fn first_observed_at(&self) -> Duration {
454 self.first_observed_at
455 }
456}
457
458/// The exact durable owner record a caller may attempt to renew before local expiry.
459///
460/// It is caller-local evidence held by [`LocalState`] for the participant that
461/// polled, not a lease granted by a durable clock: a poll must still verify
462/// the participant, rank, and persisted duration against durable state. A
463/// later successful leader poll, including renewal by this same participant,
464/// supersedes this token's fencing rank.
465#[derive(Debug, Clone, PartialEq, Eq)]
466pub struct Leadership {
467 rank: Rank,
468 lease_duration: Duration,
469 last_renewed_at: Duration,
470}
471
472impl Leadership {
473 pub(crate) fn new(rank: Rank, lease_duration: Duration, last_renewed_at: Duration) -> Self {
474 Self {
475 rank,
476 lease_duration,
477 last_renewed_at,
478 }
479 }
480
481 /// Returns this token's durable revision as a fencing rank.
482 ///
483 /// A later successful leader poll supersedes this rank, including renewal
484 /// by the same participant.
485 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
486 pub fn rank(&self) -> Rank {
487 self.rank
488 }
489
490 /// Returns the lease duration persisted with this token.
491 ///
492 /// It bounds local renewability from [`Self::last_renewed_at`], not the
493 /// durable owner's lifetime.
494 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
495 pub fn lease_duration(&self) -> Duration {
496 self.lease_duration
497 }
498
499 /// Returns the caller-clock reading taken before the successful poll's run.
500 ///
501 /// A renewal is locally eligible only while elapsed time from this value is
502 /// less than [`Self::lease_duration`]. It must be compared only with the
503 /// same caller's monotonic clock.
504 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
505 pub fn last_renewed_at(&self) -> Duration {
506 self.last_renewed_at
507 }
508}
509
510/// The role and fencing rank prepared by one poll transaction attempt.
511///
512/// The rank may protect work staged in the same transaction, but it authorizes
513/// no committed or external work until the enclosing
514/// [`Database::run`](crate::Database::run) succeeds.
515#[derive(Debug, Clone, PartialEq, Eq)]
516pub enum PollOutcome {
517 /// The transaction staged this caller as owner with a fresh fencing rank.
518 ///
519 /// [`PollTransition`] classifies how that staged ownership was reached.
520 Leader {
521 rank: Rank,
522 transition: PollTransition,
523 },
524 /// A durable owner was observed, but no leadership transition was staged.
525 ///
526 /// The fields form the exact record carried by
527 /// [`NextState::Observation`].
528 Follower {
529 owner: ParticipantId,
530 rank: Rank,
531 lease_duration: Duration,
532 },
533}
534
535/// The state-machine transition classified by one poll attempt.
536///
537/// This is an outcome label, not separately persisted durable state. It is
538/// meaningful only with the [`PollOutcome`] produced by the committed outer
539/// transaction.
540#[derive(Debug, Clone, Copy, PartialEq, Eq)]
541pub enum PollTransition {
542 /// A released or never-created durable state was acquired immediately.
543 Acquired,
544 /// An exact, locally unexpired [`Leadership`] token was renewed.
545 Renewed,
546 /// An unchanged foreign [`Observation`] was replaced after its persisted duration.
547 TookOver,
548 /// An expired [`Observation`] of this same participant was acquired again.
549 Reacquired,
550 /// A durable owner was observed without a permitted leadership transition.
551 ///
552 /// This is returned for [`PollOutcome::Follower`] and never stages an
553 /// ownership mutation.
554 Followed,
555}
556
557impl PollOutcome {
558 /// Returns whether this attempt staged an ownership transition.
559 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
560 pub fn is_leader(&self) -> bool {
561 matches!(self, Self::Leader { .. })
562 }
563
564 /// Returns the observed or newly staged durable revision as a fencing rank.
565 ///
566 /// Only [`Self::is_leader`] outcomes provide a new rank that can protect
567 /// work staged by this poll transaction.
568 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
569 pub fn rank(&self) -> Rank {
570 match self {
571 Self::Leader { rank, .. } | Self::Follower { rank, .. } => *rank,
572 }
573 }
574
575 /// Returns the transition classification for this attempt.
576 ///
577 /// [`PollOutcome::Follower`] always reports [`PollTransition::Followed`].
578 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
579 pub fn transition(&self) -> PollTransition {
580 match self {
581 Self::Leader { transition, .. } => *transition,
582 Self::Follower { .. } => PollTransition::Followed,
583 }
584 }
585
586 /// Returns whether this attempt staged replacement of a foreign owner.
587 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
588 pub fn is_takeover(&self) -> bool {
589 self.transition() == PollTransition::TookOver
590 }
591
592 /// Returns whether this attempt staged reacquisition of this participant's expired record.
593 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
594 pub fn is_reacquisition(&self) -> bool {
595 self.transition() == PollTransition::Reacquired
596 }
597
598 /// Returns the observed owner when this attempt produced follower state.
599 ///
600 /// The owner is an observation, not an authorization for the caller.
601 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
602 pub fn owner(&self) -> Option<&ParticipantId> {
603 match self {
604 Self::Follower { owner, .. } => Some(owner),
605 Self::Leader { .. } => None,
606 }
607 }
608
609 /// Returns the observed persisted lease duration when following.
610 ///
611 /// This duration is relevant to a later poll only with the matching
612 /// observation carried by [`PollResult::next`].
613 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
614 pub fn lease_duration(&self) -> Option<Duration> {
615 match self {
616 Self::Follower { lease_duration, .. } => Some(*lease_duration),
617 Self::Leader { .. } => None,
618 }
619 }
620}
621
622/// The result prepared by [`super::LeaderElection::poll`].
623///
624/// Keep this value inside the transaction callback until the enclosing
625/// [`Database::run`](crate::Database::run) succeeds. Before then, the
626/// transaction can retry, be cancelled, or fail to commit. On success, inspect
627/// [`Self::outcome`] and carry [`Self::next`] into the next poll, for example
628/// with [`LocalState::adopt`].
629#[derive(Debug, Clone, PartialEq, Eq)]
630pub struct PollResult {
631 outcome: PollOutcome,
632 next: NextState,
633}
634
635impl PollResult {
636 pub(super) fn new(outcome: PollOutcome, next: NextState) -> Self {
637 Self { outcome, next }
638 }
639
640 /// Returns the role and fencing rank prepared by this transaction attempt.
641 ///
642 /// See [`PollOutcome`] for when the rank is usable for protected work.
643 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
644 pub fn outcome(&self) -> &PollOutcome {
645 &self.outcome
646 }
647
648 /// Returns the clock-free state to carry into the next poll.
649 ///
650 /// Adopt it only after the enclosing [`Database::run`](crate::Database::run)
651 /// succeeds, anchoring it on the caller's clock as described by
652 /// [`LocalState::adopt`].
653 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
654 pub fn next(&self) -> &NextState {
655 &self.next
656 }
657}
658
659/// A read-only snapshot of durable state for diagnostics and observability.
660///
661/// It makes no liveness, expiry, or leadership-validity claim. Use
662/// [`super::LeaderElection::poll`] with a caller-owned [`PollInput`] for
663/// protocol decisions instead of deriving authority from this snapshot.
664#[derive(Debug, Clone, PartialEq, Eq)]
665pub struct ElectionState {
666 owner: Option<ParticipantId>,
667 rank: Rank,
668 lease_duration: Option<Duration>,
669}
670
671impl ElectionState {
672 pub(crate) fn new(
673 owner: Option<ParticipantId>,
674 rank: Rank,
675 lease_duration: Option<Duration>,
676 ) -> Self {
677 Self {
678 owner,
679 rank,
680 lease_duration,
681 }
682 }
683
684 /// Returns the durable owner, if the observed state is not released.
685 ///
686 /// `Some` does not show whether that owner is running or locally renewable.
687 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
688 pub fn owner(&self) -> Option<&ParticipantId> {
689 self.owner.as_ref()
690 }
691
692 /// Returns the durable revision as a fencing rank.
693 ///
694 /// A rank is retained after resignation so a later acquisition receives a
695 /// strictly newer fencing epoch.
696 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
697 pub fn rank(&self) -> Rank {
698 self.rank
699 }
700
701 /// Returns the last persisted lease duration, if this state has been created.
702 ///
703 /// It is historical state, not a persisted expiration deadline.
704 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
705 pub fn lease_duration(&self) -> Option<Duration> {
706 self.lease_duration
707 }
708}
709
710/// Result of a conditional resignation attempt.
711///
712/// It describes what the current transaction staged and is final only after
713/// the enclosing [`Database::run`](crate::Database::run) succeeds.
714#[derive(Debug, Clone, Copy, PartialEq, Eq)]
715pub enum ResignOutcome {
716 /// The exact claimed owner record staged a release in the current transaction.
717 Resigned,
718 /// The durable owner, revision, or persisted duration no longer matched.
719 ///
720 /// No release mutation was staged, preventing an old delayed resignation
721 /// from releasing a newer leader.
722 Rejected,
723}
724
725impl ResignOutcome {
726 /// Returns whether the current transaction staged the matching resignation.
727 ///
728 /// This is not proof of release until the outer transaction commits.
729 #[cfg_attr(feature = "trace", tracing::instrument(level = "debug", skip(self)))]
730 pub fn is_resigned(&self) -> bool {
731 matches!(self, Self::Resigned)
732 }
733}