Skip to main content

weirdnet_sync/
lease.rs

1//! Majority-vote leases with fencing terms (since 0.8).
2//!
3//! The op log is eventually consistent, so it can't give mutual exclusion by itself. A lease
4//! comes from a small quorum protocol between *voters*: the user's devices that hold a role
5//! grant (for Ymir, `ymir.inference`; [`Voters::Role`]). A candidate asks every voter at once
6//! and holds the lease while a majority granted it, timed by its own monotonic clock and cut
7//! short by the assumed clock-rate drift. Each new holder gets a higher [`Term`], the fencing
8//! token: resources refuse commands with a term older than one they have seen
9//! ([`FenceGuard`]), so a paused or partitioned ex-holder can do no harm.
10//!
11//! Asks and answers are [`Message`] variants on `/weirdnet/sync/2`, sealed
12//! like every other request, so only active, admitted devices of the user take part. A
13//! voter answers only candidates that are in the same voter set. Safety needs no wall clock
14//! and no HLC; only rate drift within [`LeaseConfig::max_drift`].
15//!
16//! Voters keep the highest term per lease (persist [`Voter::export`]); after a restart a
17//! voter refuses takeovers for one maximum lease duration, so it can't hand out an
18//! overlapping lease.
19use std::collections::HashMap;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::{Arc, Condvar, Mutex};
22use std::time::{Duration, Instant};
23
24use serde::{Deserialize, Serialize};
25use weirdnet_net::profile::WEIRDNET;
26use weirdnet_net::{Multiaddr, Node, PeerId};
27
28use crate::error::{Result, SyncError};
29use crate::net::SyncState;
30use crate::protocol::{Message, decode, encode};
31use crate::roster::{CallerCheck, Roster};
32
33/// Default time a grant lasts at a voter.
34pub const DEFAULT_DURATION: Duration = Duration::from_secs(15);
35/// Default renewal interval (a third of the duration).
36pub const DEFAULT_RENEW_EVERY: Duration = Duration::from_secs(5);
37/// Default worst clock-rate drift assumed between devices.
38pub const DEFAULT_MAX_DRIFT: f64 = 0.01;
39/// Default delay per candidate rank after a lapse.
40pub const DEFAULT_STAGGER: Duration = Duration::from_millis(500);
41/// Taken off every lease besides the drift.
42const EPSILON: Duration = Duration::from_millis(50);
43/// The envelope type lease messages travel under.
44pub const LEASE_TYPE: &str = "weirdnet.lease";
45const MAX_NAME: usize = 200;
46
47/// A lease name, scoped by the app: `ymir.scheduler`, `ymir.jobs/<job id>`. 1 to 200 of
48/// `A-Z a-z 0-9 . - _ : / + #`.
49#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
50#[serde(try_from = "String", into = "String")]
51pub struct LeaseName(String);
52
53impl LeaseName {
54    pub fn new(name: impl Into<String>) -> Result<Self> {
55        let name = name.into();
56        let ok = !name.is_empty() && name.len() <= MAX_NAME && name.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:/+#".contains(c));
57        if ok { Ok(Self(name)) } else { Err(SyncError::Protocol(format!("bad lease name {name:?}"))) }
58    }
59
60    pub fn as_str(&self) -> &str {
61        &self.0
62    }
63}
64
65impl TryFrom<String> for LeaseName {
66    type Error = SyncError;
67    fn try_from(s: String) -> Result<Self> {
68        Self::new(s)
69    }
70}
71
72impl From<LeaseName> for String {
73    fn from(n: LeaseName) -> String {
74        n.0
75    }
76}
77
78impl std::fmt::Display for LeaseName {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.write_str(&self.0)
81    }
82}
83
84/// Fencing token: strictly increases per lease name across holders.
85#[derive(Debug, Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)]
86#[serde(transparent)]
87pub struct Term(pub u64);
88
89impl Term {
90    pub fn next(self) -> Term {
91        Term(self.0.saturating_add(1))
92    }
93}
94
95impl std::fmt::Display for Term {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        write!(f, "{}", self.0)
98    }
99}
100
101/// Per-lease limits a [`Voter`] applies (since 0.8.1): the longest grant, and how long it
102/// refuses another holder after a promise lapsed (its holder stopped renewing without letting
103/// go). Set them per lease-name prefix with [`Voter::with_limits`]; a job's own
104/// [`JobRules`](crate::jobs::JobRules) set them for its claim lease.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[non_exhaustive]
107pub struct LeaseLimits {
108    pub max_duration: Duration,
109    pub takeover_after: Duration,
110}
111
112impl LeaseLimits {
113    pub fn new(max_duration: Duration, takeover_after: Duration) -> Self {
114        Self { max_duration, takeover_after }
115    }
116}
117
118/// Who votes (and who may stand): devices with an active cert in the roster.
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum Voters {
122    /// Devices whose grant holds this role (`Roster::has_role`), for example `ymir.inference`.
123    Role(String),
124    /// A fixed set of peer ids (those with an active cert count).
125    Peers(Vec<String>),
126}
127
128impl Voters {
129    /// The voters now, sorted (the order is the candidate rank).
130    pub fn resolve(&self, roster: &Roster) -> Vec<String> {
131        let mut v: Vec<String> = match self {
132            Voters::Role(role) => roster.active().filter(|c| roster.has_role(&c.peer_id, role)).map(|c| c.peer_id.clone()).collect(),
133            Voters::Peers(peers) => peers.iter().filter(|p| roster.get(p).is_some_and(|c| c.active())).cloned().collect(),
134        };
135        v.sort();
136        v.dedup();
137        v
138    }
139
140    /// A digest of [`resolve`](Self::resolve): candidates send it with every ask and a voter
141    /// grants only when its own view of the voter set is the same, so a candidate with a stale
142    /// roster can't win a majority of a voter set that has since changed.
143    pub fn digest(&self, roster: &Roster) -> String {
144        let mut h = blake3::Hasher::new();
145        h.update(b"weirdnet-sync/v1/voters\n");
146        for v in self.resolve(roster) {
147            h.update(v.as_bytes());
148            h.update(b"\n");
149        }
150        h.finalize().to_hex()[..32].to_string()
151    }
152
153    pub fn contains(&self, roster: &Roster, peer: &str) -> bool {
154        match self {
155            Voters::Role(role) => roster.get(peer).is_some_and(|c| c.active()) && roster.has_role(peer, role),
156            Voters::Peers(peers) => peers.iter().any(|p| p == peer) && roster.get(peer).is_some_and(|c| c.active()),
157        }
158    }
159}
160
161/// How a lease is held.
162#[derive(Debug, Clone)]
163#[non_exhaustive]
164pub struct LeaseConfig {
165    /// How long a grant lasts at a voter (capped by the voter's maximum).
166    pub duration: Duration,
167    /// How often the [`Elector`] renews.
168    pub renew_every: Duration,
169    /// Assumed worst clock-rate drift; the holder's lease is shortened by it.
170    pub max_drift: f64,
171    pub voters: Voters,
172    /// Extra wait per candidate rank after a lapse, so the lowest rank tries first.
173    pub stagger: Duration,
174    /// Write a [`LeaseRecord`] under this record type on each new term (informational).
175    pub record_type: Option<String>,
176}
177
178impl LeaseConfig {
179    /// The defaults (15 s, renew every 5 s, 1 % drift, 500 ms stagger) with these voters.
180    pub fn new(voters: Voters) -> Self {
181        Self {
182            duration: DEFAULT_DURATION,
183            renew_every: DEFAULT_RENEW_EVERY,
184            max_drift: DEFAULT_MAX_DRIFT,
185            voters,
186            stagger: DEFAULT_STAGGER,
187            record_type: None,
188        }
189    }
190
191    /// Voters are the devices granted `role`.
192    pub fn for_role(role: impl Into<String>) -> Self {
193        Self::new(Voters::Role(role.into()))
194    }
195
196    /// Sets the duration and renews every third of it.
197    pub fn with_duration(mut self, duration: Duration) -> Self {
198        self.duration = duration;
199        self.renew_every = duration / 3;
200        self
201    }
202
203    pub fn with_stagger(mut self, stagger: Duration) -> Self {
204        self.stagger = stagger;
205        self
206    }
207
208    pub fn with_max_drift(mut self, drift: f64) -> Self {
209        self.max_drift = drift.clamp(0.0, 0.5);
210        self
211    }
212
213    pub fn with_record_type(mut self, typ: impl Into<String>) -> Self {
214        self.record_type = Some(typ.into());
215        self
216    }
217}
218
219/// A candidate asks for (or renews) a lease.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct LeaseAsk {
222    pub name: LeaseName,
223    pub term: Term,
224    pub duration_ms: u32,
225    pub renew: bool,
226    /// [`Voters::digest`] of the voter set the candidate counts its majority in.
227    pub voters: String,
228}
229
230/// A voter granted it.
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232pub struct LeaseGrant {
233    pub name: LeaseName,
234    pub term: Term,
235    pub duration_ms: u32,
236}
237
238/// A voter did not grant it: who it promised, for how much longer, and the highest term it
239/// has granted (ask with a higher one next time).
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct LeaseDeny {
242    pub name: LeaseName,
243    pub promised: Term,
244    pub holder: String,
245    pub remaining_ms: u32,
246    pub max_term: Term,
247}
248
249/// The holder lets go (also the answer to one).
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251pub struct LeaseFree {
252    pub name: LeaseName,
253    pub term: Term,
254}
255
256/// Who holds a lease, written to the op log on each new term for display. Nothing trusts it.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258pub struct LeaseRecord {
259    pub name: LeaseName,
260    pub term: Term,
261    pub holder: String,
262}
263
264#[derive(Debug, Clone)]
265struct Promise {
266    term: Term,
267    holder: String,
268    until: Instant,
269}
270
271#[derive(Debug, Clone, Default)]
272struct Slot {
273    max_term: Term,
274    /// Who `max_term` went to.
275    max_holder: String,
276    promise: Option<Promise>,
277}
278
279#[derive(Serialize, Deserialize)]
280struct Persisted {
281    v: u8,
282    terms: Vec<(LeaseName, Term, String)>,
283    /// The longest grant given (since 0.8.1), so a restart waits it out.
284    #[serde(default)]
285    longest_ms: u64,
286}
287
288type Persist = Arc<dyn Fn(&[u8]) -> std::io::Result<()> + Send + Sync>;
289
290/// The voter side (one per device, kept in [`SyncState::voter`]). Not secret.
291///
292/// Give it a store with [`with_persist`](Self::with_persist) (or use
293/// [`Identity::enable_voter`](crate::Identity::enable_voter)): every new term is then written
294/// before it is granted. Without one, a voter that crashes before the app saved
295/// [`export`](Self::export) may grant a term it already gave out, so two holders could share
296/// a fencing token (their leases still never overlap in time).
297#[derive(Clone)]
298pub struct Voter {
299    candidates: Voters,
300    max_duration: Duration,
301    grace_until: Instant,
302    slots: HashMap<LeaseName, Slot>,
303    persist: Option<Persist>,
304    /// Limits per lease-name prefix, longest prefix first.
305    limits: Vec<(String, LeaseLimits)>,
306    /// The longest grant given so far.
307    longest: Duration,
308}
309
310impl std::fmt::Debug for Voter {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        f.debug_struct("Voter")
313            .field("candidates", &self.candidates)
314            .field("max_duration", &self.max_duration)
315            .field("slots", &self.slots)
316            .field("persist", &self.persist.is_some())
317            .field("limits", &self.limits)
318            .finish()
319    }
320}
321
322impl Voter {
323    /// A voter answering candidates in `candidates` (normally the same [`Voters`] the
324    /// leases use). It refuses takeovers for [`DEFAULT_DURATION`] after it starts.
325    pub fn new(candidates: Voters) -> Self {
326        Self {
327            candidates,
328            max_duration: DEFAULT_DURATION,
329            grace_until: Instant::now() + DEFAULT_DURATION,
330            slots: HashMap::new(),
331            persist: None,
332            limits: Vec::new(),
333            longest: Duration::ZERO,
334        }
335    }
336
337    /// When it started (the grace runs from there).
338    fn started(&self) -> Instant {
339        self.grace_until - self.grace()
340    }
341
342    /// How long it refuses takeovers after starting: its longest possible grant.
343    fn grace(&self) -> Duration {
344        self.limits.iter().map(|(_, l)| l.max_duration).chain([self.max_duration, self.longest]).max().unwrap_or(self.max_duration)
345    }
346
347    /// Limits for lease names starting with `prefix` (since 0.8.1), for example
348    /// `ymir.train/` with 60 s grants and a 5 min takeover wait. The longest matching prefix
349    /// wins; the restart grace grows to the longest grant. A job's own rules take precedence
350    /// for its claim lease when this device has synced the job.
351    pub fn with_limits(mut self, prefix: impl Into<String>, max_duration: Duration, takeover_after: Duration) -> Self {
352        let started = self.started();
353        let prefix = prefix.into();
354        self.limits.retain(|(p, _)| *p != prefix);
355        self.limits.push((prefix, LeaseLimits::new(max_duration, takeover_after)));
356        self.limits.sort_by(|a, b| b.0.len().cmp(&a.0.len()).then_with(|| a.0.cmp(&b.0)));
357        self.grace_until = started + self.grace();
358        self
359    }
360
361    /// The limits for `name`: the longest matching prefix's, if any.
362    pub fn limits_for(&self, name: &LeaseName) -> Option<LeaseLimits> {
363        self.limits.iter().find(|(p, _)| name.as_str().starts_with(p.as_str())).map(|(_, l)| *l)
364    }
365
366    /// Copies another voter's maximum and per-prefix limits (keeping this one's terms).
367    pub(crate) fn with_settings_of(mut self, other: &Voter) -> Self {
368        let started = self.started();
369        self.max_duration = other.max_duration;
370        self.limits = other.limits.clone();
371        self.grace_until = started + self.grace();
372        self
373    }
374
375    /// Write [`export`](Self::export) with `store` before each new term is granted (renewals
376    /// write nothing). If the write fails the ask is denied.
377    pub fn with_persist(mut self, store: impl Fn(&[u8]) -> std::io::Result<()> + Send + Sync + 'static) -> Self {
378        self.persist = Some(Arc::new(store));
379        self
380    }
381
382    /// The longest grant it gives, which is also the restart grace (default 15 s).
383    pub fn with_max_duration(mut self, max: Duration) -> Self {
384        let started = self.started();
385        self.max_duration = max;
386        self.grace_until = started + self.grace();
387        self
388    }
389
390    /// The highest terms (and their holders), to persist; not secret.
391    pub fn export(&self) -> Vec<u8> {
392        let mut terms: Vec<_> = self.slots.iter().map(|(n, s)| (n.clone(), s.max_term, s.max_holder.clone())).collect();
393        terms.sort();
394        encode(&Persisted { v: 1, terms, longest_ms: self.longest.as_millis().min(u64::MAX as u128) as u64 }).unwrap_or_default()
395    }
396
397    /// A voter restarted from [`export`](Self::export): it never grants an old term again and
398    /// refuses takeovers for one maximum duration.
399    pub fn import(bytes: &[u8], candidates: Voters) -> Result<Self> {
400        let p: Persisted = decode(bytes)?;
401        let mut v = Self::new(candidates);
402        let started = v.started();
403        v.longest = Duration::from_millis(p.longest_ms);
404        v.grace_until = started + v.grace();
405        for (name, term, holder) in p.terms {
406            v.slots.insert(name, Slot { max_term: term, max_holder: holder, promise: None });
407        }
408        Ok(v)
409    }
410
411    /// The longest grant it gives (and its restart grace).
412    pub fn max_duration(&self) -> Duration {
413        self.max_duration
414    }
415
416    /// The highest term granted for `name`.
417    pub fn max_term(&self, name: &LeaseName) -> Term {
418        self.slots.get(name).map(|s| s.max_term).unwrap_or_default()
419    }
420
421    /// Who the highest term for `name` went to.
422    fn max_holder(&self, name: &LeaseName) -> Option<&str> {
423        self.slots.get(name).map(|s| s.max_holder.as_str())
424    }
425
426    pub fn candidates(&self) -> &Voters {
427        &self.candidates
428    }
429
430    /// The voter rule. `from` is the transport-authenticated asker.
431    pub fn on_ask(&mut self, from: &str, ask: &LeaseAsk, now: Instant) -> Message {
432        self.on_ask_with(from, ask, now, None)
433    }
434
435    /// [`on_ask`](Self::on_ask) with `limits` in place of the prefix limits (since 0.8.1;
436    /// the sync state passes a job's own rules here).
437    pub fn on_ask_with(&mut self, from: &str, ask: &LeaseAsk, now: Instant, limits: Option<LeaseLimits>) -> Message {
438        let in_grace = now < self.grace_until;
439        let grace_left = self.grace_until.saturating_duration_since(now);
440        let limits = limits.or_else(|| self.limits_for(&ask.name));
441        let max = limits.map(|l| l.max_duration).unwrap_or(self.max_duration);
442        let takeover_after = limits.map(|l| l.takeover_after).unwrap_or_default();
443        let duration = Duration::from_millis(ask.duration_ms as u64).min(max);
444        let longer = duration > self.longest;
445        let slot = self.slots.entry(ask.name.clone()).or_default();
446        let live = slot.promise.as_ref().filter(|p| p.until > now).cloned();
447        // A promise that ran out without its holder letting go holds others off for the
448        // takeover wait.
449        let lapsed = slot.promise.as_ref().filter(|p| p.until <= now && p.holder != from && now < p.until + takeover_after).cloned();
450        // Renewal (or re-establishing a lapsed promise): only the holder the term went to, and
451        // only while no higher term was granted here.
452        let renewal = ask.term == slot.max_term && slot.max_holder == from && ask.term.0 > 0;
453        // Takeover or first grant: a higher term, nobody else promised.
454        let takeover = ask.term > slot.max_term && live.as_ref().is_none_or(|p| p.holder == from) && lapsed.is_none() && !in_grace;
455        if renewal || takeover {
456            let before = slot.clone();
457            slot.max_term = ask.term;
458            slot.max_holder = from.to_string();
459            slot.promise = Some(Promise { term: ask.term, holder: from.to_string(), until: now + duration });
460            let longest_before = self.longest;
461            self.longest = self.longest.max(duration);
462            if (takeover || longer)
463                && let Some(store) = self.persist.clone()
464            {
465                // The new term must be durable before anyone acts on it.
466                if store(&self.export()).is_err() {
467                    self.longest = longest_before;
468                    let slot = self.slots.entry(ask.name.clone()).or_default();
469                    *slot = before;
470                    return Message::LeaseDeny(LeaseDeny {
471                        name: ask.name.clone(),
472                        promised: slot.max_term,
473                        holder: String::new(),
474                        remaining_ms: 0,
475                        max_term: slot.max_term,
476                    });
477                }
478            }
479            return Message::LeaseGrant(LeaseGrant { name: ask.name.clone(), term: ask.term, duration_ms: duration.as_millis() as u32 });
480        }
481        let (promised, holder, remaining) = match (&live, &lapsed) {
482            (Some(p), _) => (p.term, p.holder.clone(), p.until - now),
483            (None, Some(p)) => (p.term, p.holder.clone(), (p.until + takeover_after).saturating_duration_since(now)),
484            (None, None) if in_grace => (slot.max_term, slot.max_holder.clone(), grace_left),
485            (None, None) => (slot.max_term, String::new(), Duration::ZERO),
486        };
487        Message::LeaseDeny(LeaseDeny {
488            name: ask.name.clone(),
489            promised,
490            holder,
491            remaining_ms: remaining.as_millis().min(u32::MAX as u128) as u32,
492            max_term: slot.max_term,
493        })
494    }
495
496    /// The holder lets go of `term`.
497    pub fn on_free(&mut self, from: &str, free: &LeaseFree) {
498        if let Some(slot) = self.slots.get_mut(&free.name)
499            && slot.promise.as_ref().is_some_and(|p| p.term == free.term && p.holder == from)
500        {
501            slot.promise = None;
502        }
503    }
504}
505
506impl SyncState {
507    /// Makes this device a voter (or stops it voting with `None`).
508    pub fn set_voter(&mut self, voter: Option<Voter>) {
509        self.voter = voter;
510    }
511
512    /// A lease message from `from` (already opened under the head key).
513    pub(crate) fn on_lease(&mut self, from: &str, msg: Message) -> Message {
514        use crate::protocol::Refuse;
515        let check = self.roster.check_caller(&WEIRDNET, &self.user_key, from, None);
516        if check != CallerCheck::Linked {
517            return Message::Refuse(Refuse::new(check.reason().unwrap_or("unknown-device")));
518        }
519        // A job's claim lease follows the job's rules when this device has the job.
520        let job = match &msg {
521            Message::LeaseAsk(ask) if self.voter.is_some() => match self.job_lease_limits(&ask.name, from, ask.renew) {
522                Ok(limits) => limits,
523                Err(reason) => return Message::Refuse(Refuse::new(reason)),
524            },
525            _ => None,
526        };
527        let roster = &self.roster;
528        let Some(voter) = self.voter.as_mut() else { return Message::Refuse(Refuse::new("not-a-voter")) };
529        if !voter.candidates.contains(roster, from) {
530            return Message::Refuse(Refuse::new("not-a-candidate"));
531        }
532        let me = self.our_cert.peer_id.as_str();
533        match msg {
534            // Only a device that is itself in the voter set votes, and only for a candidate
535            // that counts the same voter set.
536            Message::LeaseAsk(_) if !voter.candidates.contains(roster, me) => Message::Refuse(Refuse::new("not-a-voter")),
537            Message::LeaseAsk(ask) if ask.voters != voter.candidates.digest(roster) => Message::Refuse(Refuse::new("voters-differ")),
538            Message::LeaseAsk(ask) => voter.on_ask_with(from, &ask, Instant::now(), job),
539            Message::LeaseFree(free) => {
540                voter.on_free(from, &free);
541                Message::LeaseFree(free)
542            }
543            _ => Message::Refuse(Refuse::new("unexpected")),
544        }
545    }
546}
547
548/// A held lease. Valid only while [`is_valid`](Self::is_valid); carry [`term`](Self::term) in
549/// every fenced command.
550#[derive(Debug, Clone, PartialEq, Eq)]
551pub struct LeaseHandle {
552    name: LeaseName,
553    term: Term,
554    holder: String,
555    valid_until: Instant,
556}
557
558impl LeaseHandle {
559    pub fn name(&self) -> &LeaseName {
560        &self.name
561    }
562
563    pub fn term(&self) -> Term {
564        self.term
565    }
566
567    /// This device's peer id.
568    pub fn holder(&self) -> &str {
569        &self.holder
570    }
571
572    pub fn is_valid(&self) -> bool {
573        Instant::now() < self.valid_until
574    }
575
576    pub fn remaining(&self) -> Duration {
577        self.valid_until.saturating_duration_since(Instant::now())
578    }
579}
580
581/// Why a lease was not got or kept.
582#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
583#[non_exhaustive]
584pub enum LeaseError {
585    /// Someone else holds it; try again after `retry_in`.
586    #[error("held by {holder} (term {term}), retry in {retry_in:?}")]
587    Held { holder: String, term: Term, retry_in: Duration },
588    /// Not enough voters answered with a grant.
589    #[error("no quorum: {reached} of {needed} grants")]
590    NoQuorum { reached: usize, needed: usize },
591    /// The lease ran out before a renewal reached a quorum: stop acting.
592    #[error("lease lost")]
593    Lost,
594    /// This device is not among the voters (only voters stand), or no longer is.
595    #[error("not a voter for this lease")]
596    NotEligible,
597    /// Not claimable yet (a job's retry backoff, since 0.8.1); try again after `retry_in`.
598    #[error("not yet, retry in {retry_in:?}")]
599    NotYet { retry_in: Duration },
600    #[error("{0}")]
601    Sync(String),
602}
603
604impl From<SyncError> for LeaseError {
605    fn from(e: SyncError) -> Self {
606        LeaseError::Sync(e.to_string())
607    }
608}
609
610/// What an [`Elector`] sees.
611#[derive(Debug, Clone, PartialEq, Eq)]
612#[non_exhaustive]
613pub enum LeaseState {
614    Held {
615        term: Term,
616    },
617    /// Learned from a voter's answer.
618    Follower {
619        holder: String,
620        term: Term,
621    },
622    /// Nobody known to hold it.
623    Vacant,
624    NoQuorum {
625        reached: usize,
626        needed: usize,
627    },
628}
629
630type SyncNode = Node<Vec<u8>, Vec<u8>>;
631type AddrBook = Arc<dyn Fn(&str) -> Vec<Multiaddr> + Send + Sync>;
632
633/// The candidate side: acquires, renews and releases leases through a sync node and its
634/// shared state (as served by [`crate::start_node`]). The state's lock is never held across
635/// the network.
636#[derive(Clone)]
637pub struct Leases {
638    node: Arc<SyncNode>,
639    state: Arc<Mutex<SyncState>>,
640    addrs: AddrBook,
641    terms: Arc<Mutex<HashMap<LeaseName, Term>>>,
642    /// Per lease, the term this device last asked for and some voter granted, though not a
643    /// majority (since 0.8.6). It is asked for again while no voter shows one as high, so
644    /// retrying while a holder lives doesn't climb a term per try.
645    tried: Arc<Mutex<HashMap<LeaseName, Term>>>,
646}
647
648enum Answer {
649    Grant(Duration),
650    Deny(LeaseDeny),
651    None,
652}
653
654impl Leases {
655    pub fn new(node: Arc<SyncNode>, state: Arc<Mutex<SyncState>>) -> Self {
656        Self { node, state, addrs: Arc::new(|_| Vec::new()), terms: Arc::default(), tried: Arc::default() }
657    }
658
659    /// The shared state the leases use.
660    pub fn state(&self) -> &Arc<Mutex<SyncState>> {
661        &self.state
662    }
663
664    /// Addresses to dial each voter on (default none: the node's known addresses).
665    pub fn with_addrs(mut self, addrs: impl Fn(&str) -> Vec<Multiaddr> + Send + Sync + 'static) -> Self {
666        self.addrs = Arc::new(addrs);
667        self
668    }
669
670    fn known_term(&self, name: &LeaseName) -> Term {
671        let local = self.terms.lock().map(|t| t.get(name).copied().unwrap_or_default()).unwrap_or_default();
672        let voted = self.state.lock().ok().and_then(|st| st.voter.as_ref().map(|v| v.max_term(name))).unwrap_or_default();
673        local.max(voted)
674    }
675
676    /// The highest term this device has seen for `name` (asked for, granted or voted on);
677    /// a holder whose term is below it has lost the lease (since 0.8.1).
678    pub fn term_seen(&self, name: &LeaseName) -> Term {
679        self.known_term(name)
680    }
681
682    /// The term to ask for next: the one last tried and not won while every term seen elsewhere
683    /// is below it (the voters that granted it grant it again as theirs), else one above every
684    /// term seen.
685    fn next_term(&self, name: &LeaseName, me: &str) -> Term {
686        let learned = self.terms.lock().map(|t| t.get(name).copied().unwrap_or_default()).unwrap_or_default();
687        let (voted, voted_mine) =
688            self.state.lock().ok().and_then(|st| st.voter.as_ref().map(|v| (v.max_term(name), v.max_holder(name) == Some(me)))).unwrap_or_default();
689        let tried = self.tried.lock().ok().and_then(|t| t.get(name).copied());
690        if let Some(tried) = tried {
691            let elsewhere = if voted_mine && voted == tried { learned } else { learned.max(voted) };
692            if elsewhere < tried {
693                return tried;
694            }
695        }
696        learned.max(voted).next()
697    }
698
699    fn learn(&self, name: &LeaseName, term: Term) {
700        if let Ok(mut t) = self.terms.lock() {
701            let e = t.entry(name.clone()).or_default();
702            *e = (*e).max(term);
703        }
704    }
705
706    /// Ask every voter at once (this device's own voter answers locally) and collect answers
707    /// until all came, `needed` grants came, or `wait` passed. Unreachable voters can't hold
708    /// a round up beyond `wait`; their threads finish on their own.
709    fn ask_all(&self, voters: &[String], me: &str, msg: &Message, needed: usize, wait: Duration) -> Vec<Answer> {
710        let (tx, rx) = std::sync::mpsc::channel();
711        for v in voters {
712            let (this, v, me, msg, tx) = (self.clone(), v.clone(), me.to_string(), msg.clone(), tx.clone());
713            std::thread::spawn(move || {
714                let _ = tx.send(this.ask_one(&v, &me, &msg));
715            });
716        }
717        drop(tx);
718        let deadline = Instant::now() + wait;
719        let mut out = Vec::new();
720        let mut grants = 0;
721        while out.len() < voters.len() && grants < needed {
722            let left = deadline.saturating_duration_since(Instant::now());
723            match rx.recv_timeout(left) {
724                Ok(a) => {
725                    if matches!(a, Answer::Grant(_)) {
726                        grants += 1;
727                    }
728                    out.push(a);
729                }
730                Err(_) => break,
731            }
732        }
733        out
734    }
735
736    /// Tell voters to drop a promise, waiting at most `wait` for them.
737    fn free_all(&self, voters: &[String], me: &str, free: LeaseFree, wait: Duration) {
738        let _ = self.ask_all(voters, me, &Message::LeaseFree(free), usize::MAX, wait);
739    }
740
741    fn ask_one(&self, voter: &str, me: &str, msg: &Message) -> Answer {
742        let reply = if voter == me {
743            match self.state.lock() {
744                Ok(mut st) => st.on_lease(me, msg.clone()),
745                Err(_) => return Answer::None,
746            }
747        } else {
748            match self.request(voter, msg) {
749                Ok(m) => m,
750                Err(_) => return Answer::None,
751            }
752        };
753        match reply {
754            Message::LeaseGrant(g) => Answer::Grant(Duration::from_millis(g.duration_ms as u64)),
755            Message::LeaseDeny(d) => Answer::Deny(d),
756            _ => Answer::None,
757        }
758    }
759
760    fn request(&self, voter: &str, msg: &Message) -> Result<Message> {
761        let peer: PeerId = voter.parse().map_err(|_| SyncError::Protocol("bad voter peer id".into()))?;
762        // Envelopes are bound to the asking peer (us), as in every other sync request.
763        let me = self.node.peer_id().to_string();
764        let env = {
765            let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
766            let key = st.current_key();
767            st.seal_envelope(&key, LEASE_TYPE, &me, msg)?
768        };
769        let addrs = (self.addrs)(voter);
770        let reply = self.node.request(peer, &addrs, encode(&env)?)?;
771        let env: crate::protocol::Envelope = decode(&reply)?;
772        let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
773        st.open_envelope(&env, &me)
774    }
775
776    fn voters(&self, cfg: &LeaseConfig) -> std::result::Result<(String, Vec<String>), LeaseError> {
777        let st = self.state.lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
778        Ok((st.our_cert.peer_id.clone(), cfg.voters.resolve(&st.roster)))
779    }
780
781    fn digest(&self, cfg: &LeaseConfig) -> String {
782        self.state.lock().map(|st| cfg.voters.digest(&st.roster)).unwrap_or_default()
783    }
784
785    /// Acquire `name` with a new term. Fails with [`LeaseError::Held`] while another
786    /// device holds it (with when to try again) or [`LeaseError::NoQuorum`].
787    pub fn acquire(&self, name: &LeaseName, cfg: &LeaseConfig) -> std::result::Result<LeaseHandle, LeaseError> {
788        let (me, voters) = self.voters(cfg)?;
789        let needed = voters.len() / 2 + 1;
790        if !voters.contains(&me) {
791            return Err(LeaseError::NotEligible);
792        }
793        let term = self.next_term(name, &me);
794        let ask = LeaseAsk {
795            name: name.clone(),
796            term,
797            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
798            renew: false,
799            voters: self.digest(cfg),
800        };
801        let t0 = Instant::now();
802        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
803        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
804        // A term only some voters granted is asked for again next time (they grant it again as
805        // this device's; a voter that gave it or a higher one to another device shows that and
806        // the next try goes above it), so retrying while a holder lives doesn't climb the terms.
807        if let Ok(mut t) = self.tried.lock() {
808            if granted.len() >= needed {
809                t.remove(name);
810            } else if !granted.is_empty() {
811                t.insert(name.clone(), term);
812            }
813        }
814        if granted.len() >= needed {
815            self.learn(name, term);
816            let handle = LeaseHandle { name: name.clone(), term, holder: me.clone(), valid_until: valid_until(t0, &granted, cfg) };
817            if let Some(typ) = &cfg.record_type
818                && let Ok(mut st) = self.state.lock()
819            {
820                let rec = LeaseRecord { name: name.clone(), term, holder: me };
821                if let Ok(bytes) = encode(&rec) {
822                    let _ = st.write(wall_ms(), typ, name.as_str(), &bytes);
823                }
824            }
825            return Ok(handle);
826        }
827        // Let go of the grants we did get, so the next candidate needn't wait them out.
828        if !granted.is_empty() {
829            self.free_all(&voters, &me, LeaseFree { name: name.clone(), term }, Duration::ZERO);
830        }
831        let denies: Vec<&LeaseDeny> = answers.iter().filter_map(|a| if let Answer::Deny(d) = a { Some(d) } else { None }).collect();
832        if let Some(max) = denies.iter().map(|d| d.max_term).max() {
833            self.learn(name, max);
834        }
835        if let Some(d) =
836            denies.iter().filter(|d| !d.holder.is_empty() && d.holder != me && d.remaining_ms > 0).max_by_key(|d| (d.promised, d.remaining_ms))
837        {
838            return Err(LeaseError::Held { holder: d.holder.clone(), term: d.promised, retry_in: Duration::from_millis(d.remaining_ms as u64) });
839        }
840        Err(LeaseError::NoQuorum { reached: granted.len(), needed })
841    }
842
843    /// Renew a held lease (same term). Until it runs out a failed renewal is
844    /// [`LeaseError::NoQuorum`] and the handle stays valid; after, [`LeaseError::Lost`].
845    pub fn renew(&self, handle: &mut LeaseHandle, cfg: &LeaseConfig) -> std::result::Result<(), LeaseError> {
846        let (me, voters) = self.voters(cfg)?;
847        let needed = voters.len() / 2 + 1;
848        let ask = LeaseAsk {
849            name: handle.name.clone(),
850            term: handle.term,
851            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
852            renew: true,
853            voters: self.digest(cfg),
854        };
855        let t0 = Instant::now();
856        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
857        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
858        if !voters.contains(&me) {
859            return if handle.is_valid() { Err(LeaseError::NotEligible) } else { Err(LeaseError::Lost) };
860        }
861        if granted.len() >= needed {
862            handle.valid_until = handle.valid_until.max(valid_until(t0, &granted, cfg));
863            return Ok(());
864        }
865        for a in &answers {
866            if let Answer::Deny(d) = a {
867                self.learn(&handle.name, d.max_term);
868            }
869        }
870        if handle.is_valid() { Err(LeaseError::NoQuorum { reached: granted.len(), needed }) } else { Err(LeaseError::Lost) }
871    }
872
873    /// Let go of a lease: voters drop the promise, so the next holder needn't wait it out.
874    pub fn release(&self, handle: LeaseHandle, cfg: &LeaseConfig) {
875        if let Ok((me, voters)) = self.voters(cfg) {
876            self.free_all(&voters, &me, LeaseFree { name: handle.name.clone(), term: handle.term }, ask_wait(cfg));
877        }
878    }
879
880    /// Keep acquiring and renewing `name` in the background (see [`Elector`]).
881    pub fn elect(&self, name: LeaseName, cfg: LeaseConfig) -> Elector {
882        Elector::start(self.clone(), name, cfg)
883    }
884}
885
886/// How long a round waits for answers: a third of the lease, so a lease got is still worth
887/// most of its duration.
888fn ask_wait(cfg: &LeaseConfig) -> Duration {
889    (cfg.duration / 3).max(Duration::from_millis(100))
890}
891
892fn valid_until(t0: Instant, granted: &[Duration], cfg: &LeaseConfig) -> Instant {
893    let shortest = granted.iter().min().copied().unwrap_or_default().min(cfg.duration);
894    let safe = shortest.mul_f64(1.0 - cfg.max_drift).saturating_sub(EPSILON);
895    t0 + safe
896}
897
898/// A random wait in `[0, max)`.
899fn jitter(max: Duration) -> Duration {
900    let mut b = [0u8; 8];
901    if max.is_zero() || getrandom::fill(&mut b).is_err() {
902        return Duration::ZERO;
903    }
904    let ms = max.as_millis().max(1) as u64;
905    Duration::from_millis(u64::from_le_bytes(b) % ms)
906}
907
908fn wall_ms() -> u64 {
909    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
910}
911
912struct Shared {
913    state: Mutex<(LeaseState, Option<LeaseHandle>)>,
914    changed: Condvar,
915    stop: AtomicBool,
916}
917
918/// Acquires and renews one lease in a background thread. No preemption: a live holder keeps
919/// it; after a lapse the lowest-ranked candidate tries first. Dropping it (or
920/// [`release`](Self::release)) lets go.
921pub struct Elector {
922    shared: Arc<Shared>,
923    thread: Option<std::thread::JoinHandle<()>>,
924}
925
926impl Elector {
927    fn start(leases: Leases, name: LeaseName, cfg: LeaseConfig) -> Self {
928        let shared = Arc::new(Shared { state: Mutex::new((LeaseState::Vacant, None)), changed: Condvar::new(), stop: AtomicBool::new(false) });
929        let s = shared.clone();
930        let thread =
931            std::thread::Builder::new().name(format!("lease {name}")).spawn(move || run_elector(leases, name, cfg, s)).expect("spawn lease thread");
932        Self { shared, thread: Some(thread) }
933    }
934
935    pub fn state(&self) -> LeaseState {
936        self.shared.state.lock().map(|s| s.0.clone()).unwrap_or(LeaseState::Vacant)
937    }
938
939    /// The lease while held and valid.
940    pub fn handle(&self) -> Option<LeaseHandle> {
941        self.shared.state.lock().ok().and_then(|s| s.1.clone()).filter(|h| h.is_valid())
942    }
943
944    /// Wait until `want` holds for the state, at most `timeout`. Returns the state then.
945    pub fn wait_for(&self, timeout: Duration, want: impl Fn(&LeaseState) -> bool) -> LeaseState {
946        let deadline = Instant::now() + timeout;
947        let mut g = match self.shared.state.lock() {
948            Ok(g) => g,
949            Err(_) => return LeaseState::Vacant,
950        };
951        while !want(&g.0) {
952            let left = deadline.saturating_duration_since(Instant::now());
953            if left.is_zero() {
954                break;
955            }
956            g = match self.shared.changed.wait_timeout(g, left) {
957                Ok((g, _)) => g,
958                Err(_) => return LeaseState::Vacant,
959            };
960        }
961        g.0.clone()
962    }
963
964    /// Stop and let go of the lease.
965    pub fn release(mut self) {
966        self.stop_now();
967    }
968
969    fn stop_now(&mut self) {
970        self.shared.stop.store(true, Ordering::SeqCst);
971        self.shared.changed.notify_all();
972        if let Some(t) = self.thread.take() {
973            let _ = t.join();
974        }
975    }
976}
977
978impl Drop for Elector {
979    fn drop(&mut self) {
980        self.stop_now();
981    }
982}
983
984fn set(shared: &Shared, state: LeaseState, handle: Option<LeaseHandle>) {
985    if let Ok(mut g) = shared.state.lock() {
986        *g = (state, handle);
987    }
988    shared.changed.notify_all();
989}
990
991fn sleep(shared: &Shared, d: Duration) {
992    let deadline = Instant::now() + d;
993    while !shared.stop.load(Ordering::SeqCst) {
994        let left = deadline.saturating_duration_since(Instant::now());
995        if left.is_zero() {
996            return;
997        }
998        std::thread::sleep(left.min(Duration::from_millis(20)));
999    }
1000}
1001
1002fn run_elector(leases: Leases, name: LeaseName, cfg: LeaseConfig, shared: Arc<Shared>) {
1003    let mut held: Option<LeaseHandle> = None;
1004    while !shared.stop.load(Ordering::SeqCst) {
1005        let (me, voters) = match leases.voters(&cfg) {
1006            Ok(v) => v,
1007            Err(_) => return,
1008        };
1009        let rank = voters.iter().position(|v| *v == me).unwrap_or(voters.len()) as u32;
1010        if let Some(h) = held.as_mut() {
1011            sleep(&shared, cfg.renew_every.min(h.remaining()));
1012            if shared.stop.load(Ordering::SeqCst) {
1013                break;
1014            }
1015            match leases.renew(h, &cfg) {
1016                Ok(()) => set(&shared, LeaseState::Held { term: h.term }, Some(h.clone())),
1017                Err(LeaseError::NoQuorum { .. }) if h.is_valid() => {}
1018                Err(_) => {
1019                    held = None;
1020                    set(&shared, LeaseState::Vacant, None);
1021                }
1022            }
1023            continue;
1024        }
1025        match leases.acquire(&name, &cfg) {
1026            Ok(h) => {
1027                set(&shared, LeaseState::Held { term: h.term }, Some(h.clone()));
1028                held = Some(h);
1029            }
1030            Err(LeaseError::Held { holder, term, retry_in }) => {
1031                set(&shared, LeaseState::Follower { holder, term }, None);
1032                sleep(&shared, retry_in.min(cfg.duration) + cfg.stagger * rank + jitter(cfg.stagger));
1033            }
1034            Err(LeaseError::NoQuorum { reached, needed }) => {
1035                // Two candidates that split the votes back off by rank plus a random part, so
1036                // they don't keep colliding.
1037                set(&shared, LeaseState::NoQuorum { reached, needed }, None);
1038                let base = (cfg.stagger * (rank + 1)).min(cfg.renew_every.max(Duration::from_millis(50)));
1039                sleep(&shared, base + jitter(cfg.stagger * 2));
1040            }
1041            Err(_) => {
1042                set(&shared, LeaseState::Vacant, None);
1043                sleep(&shared, cfg.renew_every.max(Duration::from_millis(50)));
1044            }
1045        }
1046    }
1047    if let Some(h) = held {
1048        leases.release(h, &cfg);
1049    }
1050    set(&shared, LeaseState::Vacant, None);
1051}
1052
1053/// Resource side: refuses commands that carry an older term than one already seen. Persist
1054/// [`export`](Self::export) so a restart keeps refusing.
1055#[derive(Debug, Clone, Default, PartialEq, Eq)]
1056pub struct FenceGuard {
1057    seen: HashMap<LeaseName, Term>,
1058}
1059
1060/// A command from an older term than the guard has seen.
1061#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
1062#[error("stale term: {seen} already seen")]
1063pub struct Stale {
1064    pub seen: Term,
1065}
1066
1067impl FenceGuard {
1068    pub fn new() -> Self {
1069        Self::default()
1070    }
1071
1072    /// Accepts `term` if it is at least the highest seen (and records it).
1073    pub fn check(&mut self, name: &LeaseName, term: Term) -> std::result::Result<(), Stale> {
1074        let seen = self.seen.entry(name.clone()).or_default();
1075        if term < *seen {
1076            return Err(Stale { seen: *seen });
1077        }
1078        *seen = term;
1079        Ok(())
1080    }
1081
1082    pub fn seen(&self, name: &LeaseName) -> Option<Term> {
1083        self.seen.get(name).copied()
1084    }
1085
1086    pub fn export(&self) -> Vec<u8> {
1087        let mut v: Vec<_> = self.seen.iter().map(|(n, t)| (n.clone(), *t)).collect();
1088        v.sort();
1089        encode(&v).unwrap_or_default()
1090    }
1091
1092    pub fn import(bytes: &[u8]) -> Result<Self> {
1093        let v: Vec<(LeaseName, Term)> = decode(bytes)?;
1094        Ok(Self { seen: v.into_iter().collect() })
1095    }
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100    use super::*;
1101
1102    fn name(s: &str) -> LeaseName {
1103        LeaseName::new(s).unwrap()
1104    }
1105
1106    fn ask(n: &str, term: u64, renew: bool) -> LeaseAsk {
1107        LeaseAsk { name: name(n), term: Term(term), duration_ms: 1_000, renew, voters: String::new() }
1108    }
1109
1110    /// An ask for an hour, so the voter's limits decide the grant.
1111    fn ask_long(n: &str, term: u64, renew: bool) -> LeaseAsk {
1112        LeaseAsk { duration_ms: 3_600_000, ..ask(n, term, renew) }
1113    }
1114
1115    fn fresh() -> Voter {
1116        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_secs(1));
1117        v.grace_until = Instant::now() - Duration::from_secs(1);
1118        v
1119    }
1120
1121    #[test]
1122    fn a_voter_promises_one_holder_at_a_time() {
1123        let mut v = fresh();
1124        let t = Instant::now();
1125        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
1126        // Another candidate, even with a higher term, waits for the promise to end.
1127        let Message::LeaseDeny(d) = v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(10)) else { panic!() };
1128        assert_eq!((d.holder.as_str(), d.promised, d.max_term), ("a", Term(1), Term(1)));
1129        assert!(d.remaining_ms > 900);
1130        // The holder renews; b still can't.
1131        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t + Duration::from_millis(500)), Message::LeaseGrant(_)));
1132        assert!(matches!(v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(1_200)), Message::LeaseDeny(_)));
1133        // After it lapses b takes over with a higher term, never the same or a lower one.
1134        let later = t + Duration::from_millis(1_600);
1135        assert!(matches!(v.on_ask("b", &ask("s", 1, false), later), Message::LeaseDeny(_)));
1136        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
1137        // a's renewal of the old term is refused now.
1138        assert!(matches!(v.on_ask("a", &ask("s", 1, true), later), Message::LeaseDeny(_)));
1139        // Release lets the next one in at once.
1140        v.on_free("b", &LeaseFree { name: name("s"), term: Term(2) });
1141        assert!(matches!(v.on_ask("a", &ask("s", 3, false), later), Message::LeaseGrant(_)));
1142        // Durations are capped.
1143        let mut long = ask("t", 1, false);
1144        long.duration_ms = 600_000;
1145        let Message::LeaseGrant(g) = v.on_ask("a", &long, later) else { panic!() };
1146        assert_eq!(g.duration_ms, 1_000);
1147    }
1148
1149    #[test]
1150    fn a_restarted_voter_refuses_takeovers_for_one_duration_and_keeps_its_terms() {
1151        let mut v = fresh();
1152        let t = Instant::now();
1153        v.on_ask("a", &ask("s", 4, false), t);
1154        let bytes = v.export();
1155        let mut back = Voter::import(&bytes, Voters::Peers(vec![])).unwrap().with_max_duration(Duration::from_secs(1));
1156        assert_eq!(back.max_term(&name("s")), Term(4));
1157        let now = Instant::now();
1158        // b can't take over during the grace, a can renew the term it holds.
1159        let Message::LeaseDeny(d) = back.on_ask("b", &ask("s", 5, false), now) else { panic!() };
1160        assert_eq!(d.holder, "a");
1161        assert!(d.remaining_ms > 0);
1162        assert!(matches!(back.on_ask("a", &ask("s", 4, true), now), Message::LeaseGrant(_)));
1163        // A new lease name is refused during the grace too.
1164        assert!(matches!(back.on_ask("b", &ask("other", 1, false), now), Message::LeaseDeny(_)));
1165    }
1166
1167    #[test]
1168    fn a_new_term_is_stored_before_it_is_granted() {
1169        use std::sync::atomic::AtomicUsize;
1170        let writes = Arc::new(AtomicUsize::new(0));
1171        let fail = Arc::new(AtomicBool::new(false));
1172        let (w, f) = (writes.clone(), fail.clone());
1173        let mut v = fresh().with_persist(move |bytes| {
1174            if f.load(Ordering::SeqCst) {
1175                return Err(std::io::Error::other("disk full"));
1176            }
1177            assert!(Voter::import(bytes, Voters::Peers(vec![])).is_ok());
1178            w.fetch_add(1, Ordering::SeqCst);
1179            Ok(())
1180        });
1181        let t = Instant::now();
1182        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
1183        assert_eq!(writes.load(Ordering::SeqCst), 1);
1184        // Renewals write nothing.
1185        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t), Message::LeaseGrant(_)));
1186        assert_eq!(writes.load(Ordering::SeqCst), 1);
1187        // A term that can't be stored is not granted, and leaves no trace.
1188        fail.store(true, Ordering::SeqCst);
1189        let later = t + Duration::from_secs(2);
1190        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseDeny(_)));
1191        assert_eq!(v.max_term(&name("s")), Term(1));
1192        fail.store(false, Ordering::SeqCst);
1193        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
1194        assert_eq!(writes.load(Ordering::SeqCst), 2);
1195    }
1196
1197    #[test]
1198    fn the_fence_refuses_older_terms() {
1199        let mut g = FenceGuard::new();
1200        let n = name("ymir.scheduler");
1201        g.check(&n, Term(3)).unwrap();
1202        g.check(&n, Term(3)).unwrap();
1203        assert_eq!(g.check(&n, Term(2)), Err(Stale { seen: Term(3) }));
1204        g.check(&n, Term(4)).unwrap();
1205        let back = FenceGuard::import(&g.export()).unwrap();
1206        assert_eq!(back.seen(&n), Some(Term(4)));
1207    }
1208
1209    #[test]
1210    fn names_are_checked_and_the_holder_stops_before_any_voter() {
1211        assert!(LeaseName::new("ymir.jobs/42").is_ok());
1212        assert!(LeaseName::new("").is_err());
1213        assert!(LeaseName::new("bad name").is_err());
1214        assert!(LeaseName::new("x".repeat(201)).is_err());
1215        let cfg = LeaseConfig::for_role("r");
1216        let t0 = Instant::now();
1217        let until = valid_until(t0, &[Duration::from_secs(15), Duration::from_secs(10)], &cfg);
1218        assert!(until < t0 + Duration::from_millis(9_900) && until > t0 + Duration::from_millis(9_800));
1219        assert_eq!((cfg.duration, cfg.renew_every, cfg.stagger, cfg.max_drift), (DEFAULT_DURATION, DEFAULT_RENEW_EVERY, DEFAULT_STAGGER, 0.01));
1220    }
1221
1222    #[test]
1223    fn skewed_clock_rates_within_the_drift_never_overlap_two_holders() {
1224        // The holder counts from before it sent the ask, the voter from when it got it. With
1225        // clock rates up to half the drift apart either way, the holder's lease (in real time)
1226        // ends before the voter's promise does, so a takeover can't overlap it.
1227        let cfg = LeaseConfig::for_role("r");
1228        let t0 = Instant::now();
1229        let safe = valid_until(t0, &[cfg.duration], &cfg) - t0;
1230        let half = cfg.max_drift / 2.0;
1231        for (holder_rate, voter_rate) in [(1.0 - half, 1.0 + half), (1.0, 1.0 + cfg.max_drift - 1e-9), (1.0 + half, 1.0 - half), (1.0, 1.0)] {
1232            let holder_real = safe.as_secs_f64() / holder_rate;
1233            let voter_real = cfg.duration.as_secs_f64() / voter_rate;
1234            assert!(holder_real < voter_real, "holder {holder_rate} voter {voter_rate}: {holder_real} >= {voter_real}");
1235        }
1236        // Wall clocks play no part: a lease is the same however far apart they are.
1237        assert_eq!(valid_until(t0, &[cfg.duration], &cfg), t0 + safe);
1238    }
1239
1240    #[test]
1241    fn prefix_limits_allow_longer_grants_and_hold_off_after_a_lapse() {
1242        let long = Duration::from_secs(60);
1243        let wait = Duration::from_secs(300);
1244        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_millis(10)).with_limits("ymir.train/", long, wait);
1245        let t0 = Instant::now() + long; // past the grace
1246        let n = "ymir.train/j1";
1247        match v.on_ask("a", &ask_long(n, 1, false), t0) {
1248            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 60_000, "the prefix's 60 s, not the default maximum"),
1249            m => panic!("{m:?}"),
1250        }
1251        match v.on_ask("a", &ask_long("other", 1, false), t0) {
1252            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 10),
1253            m => panic!("{m:?}"),
1254        }
1255        // a stops renewing: its promise lapses at t0 + 60 s, and b waits 5 more minutes.
1256        let lapsed = t0 + long + Duration::from_secs(1);
1257        match v.on_ask("b", &ask_long(n, 2, false), lapsed) {
1258            Message::LeaseDeny(d) => {
1259                assert_eq!((d.holder.as_str(), d.promised), ("a", Term(1)));
1260                assert_eq!(d.remaining_ms, 299_000);
1261            }
1262            m => panic!("{m:?}"),
1263        }
1264        // a itself may come back on its term inside the wait (a network blip).
1265        assert!(matches!(v.on_ask("a", &ask_long(n, 1, true), lapsed), Message::LeaseGrant(_)));
1266        let later = lapsed + long + wait;
1267        assert!(matches!(v.on_ask("b", &ask_long(n, 2, false), later), Message::LeaseGrant(_)));
1268        // A released lease has no wait.
1269        v.on_free("b", &LeaseFree { name: name(n), term: Term(2) });
1270        assert!(matches!(v.on_ask("c", &ask_long(n, 3, false), later), Message::LeaseGrant(_)));
1271        // A job's own limits replace the prefix's.
1272        let job = LeaseLimits::new(Duration::from_secs(20), Duration::ZERO);
1273        match v.on_ask_with("c", &ask_long(n, 3, true), later, Some(job)) {
1274            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 20_000),
1275            m => panic!("{m:?}"),
1276        }
1277    }
1278
1279    #[test]
1280    fn a_restarted_voter_waits_out_its_longest_grant() {
1281        let long = Duration::from_secs(60);
1282        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_millis(10)).with_limits("j/", long, Duration::ZERO);
1283        assert!(matches!(v.on_ask("a", &ask_long("j/1", 1, false), Instant::now() + long), Message::LeaseGrant(_)));
1284        let bytes = v.export();
1285        // Restarted without the prefix limits: the stored longest grant still sets the grace.
1286        let mut r = Voter::import(&bytes, Voters::Peers(vec![])).unwrap().with_max_duration(Duration::from_millis(10));
1287        let now = Instant::now() + Duration::from_secs(30);
1288        assert!(matches!(r.on_ask("b", &ask_long("j/1", 2, false), now), Message::LeaseDeny(_)), "still inside a's possible 60 s");
1289        // A 0.8.0 voter.cbor (no longest grant) still loads.
1290        #[derive(Serialize)]
1291        struct Old {
1292            v: u8,
1293            terms: Vec<(LeaseName, Term, String)>,
1294        }
1295        let old = encode(&Old { v: 1, terms: vec![(name("j/1"), Term(4), "a".into())] }).unwrap();
1296        assert_eq!(Voter::import(&old, Voters::Peers(vec![])).unwrap().max_term(&name("j/1")), Term(4));
1297    }
1298}