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    pub fn candidates(&self) -> &Voters {
422        &self.candidates
423    }
424
425    /// The voter rule. `from` is the transport-authenticated asker.
426    pub fn on_ask(&mut self, from: &str, ask: &LeaseAsk, now: Instant) -> Message {
427        self.on_ask_with(from, ask, now, None)
428    }
429
430    /// [`on_ask`](Self::on_ask) with `limits` in place of the prefix limits (since 0.8.1;
431    /// the sync state passes a job's own rules here).
432    pub fn on_ask_with(&mut self, from: &str, ask: &LeaseAsk, now: Instant, limits: Option<LeaseLimits>) -> Message {
433        let in_grace = now < self.grace_until;
434        let grace_left = self.grace_until.saturating_duration_since(now);
435        let limits = limits.or_else(|| self.limits_for(&ask.name));
436        let max = limits.map(|l| l.max_duration).unwrap_or(self.max_duration);
437        let takeover_after = limits.map(|l| l.takeover_after).unwrap_or_default();
438        let duration = Duration::from_millis(ask.duration_ms as u64).min(max);
439        let longer = duration > self.longest;
440        let slot = self.slots.entry(ask.name.clone()).or_default();
441        let live = slot.promise.as_ref().filter(|p| p.until > now).cloned();
442        // A promise that ran out without its holder letting go holds others off for the
443        // takeover wait.
444        let lapsed = slot.promise.as_ref().filter(|p| p.until <= now && p.holder != from && now < p.until + takeover_after).cloned();
445        // Renewal (or re-establishing a lapsed promise): only the holder the term went to, and
446        // only while no higher term was granted here.
447        let renewal = ask.term == slot.max_term && slot.max_holder == from && ask.term.0 > 0;
448        // Takeover or first grant: a higher term, nobody else promised.
449        let takeover = ask.term > slot.max_term && live.as_ref().is_none_or(|p| p.holder == from) && lapsed.is_none() && !in_grace;
450        if renewal || takeover {
451            let before = slot.clone();
452            slot.max_term = ask.term;
453            slot.max_holder = from.to_string();
454            slot.promise = Some(Promise { term: ask.term, holder: from.to_string(), until: now + duration });
455            let longest_before = self.longest;
456            self.longest = self.longest.max(duration);
457            if (takeover || longer)
458                && let Some(store) = self.persist.clone()
459            {
460                // The new term must be durable before anyone acts on it.
461                if store(&self.export()).is_err() {
462                    self.longest = longest_before;
463                    let slot = self.slots.entry(ask.name.clone()).or_default();
464                    *slot = before;
465                    return Message::LeaseDeny(LeaseDeny {
466                        name: ask.name.clone(),
467                        promised: slot.max_term,
468                        holder: String::new(),
469                        remaining_ms: 0,
470                        max_term: slot.max_term,
471                    });
472                }
473            }
474            return Message::LeaseGrant(LeaseGrant { name: ask.name.clone(), term: ask.term, duration_ms: duration.as_millis() as u32 });
475        }
476        let (promised, holder, remaining) = match (&live, &lapsed) {
477            (Some(p), _) => (p.term, p.holder.clone(), p.until - now),
478            (None, Some(p)) => (p.term, p.holder.clone(), (p.until + takeover_after).saturating_duration_since(now)),
479            (None, None) if in_grace => (slot.max_term, slot.max_holder.clone(), grace_left),
480            (None, None) => (slot.max_term, String::new(), Duration::ZERO),
481        };
482        Message::LeaseDeny(LeaseDeny {
483            name: ask.name.clone(),
484            promised,
485            holder,
486            remaining_ms: remaining.as_millis().min(u32::MAX as u128) as u32,
487            max_term: slot.max_term,
488        })
489    }
490
491    /// The holder lets go of `term`.
492    pub fn on_free(&mut self, from: &str, free: &LeaseFree) {
493        if let Some(slot) = self.slots.get_mut(&free.name)
494            && slot.promise.as_ref().is_some_and(|p| p.term == free.term && p.holder == from)
495        {
496            slot.promise = None;
497        }
498    }
499}
500
501impl SyncState {
502    /// Makes this device a voter (or stops it voting with `None`).
503    pub fn set_voter(&mut self, voter: Option<Voter>) {
504        self.voter = voter;
505    }
506
507    /// A lease message from `from` (already opened under the head key).
508    pub(crate) fn on_lease(&mut self, from: &str, msg: Message) -> Message {
509        use crate::protocol::Refuse;
510        let check = self.roster.check_caller(&WEIRDNET, &self.user_key, from, None);
511        if check != CallerCheck::Linked {
512            return Message::Refuse(Refuse::new(check.reason().unwrap_or("unknown-device")));
513        }
514        // A job's claim lease follows the job's rules when this device has the job.
515        let job = match &msg {
516            Message::LeaseAsk(ask) if self.voter.is_some() => match self.job_lease_limits(&ask.name, from, ask.renew) {
517                Ok(limits) => limits,
518                Err(reason) => return Message::Refuse(Refuse::new(reason)),
519            },
520            _ => None,
521        };
522        let roster = &self.roster;
523        let Some(voter) = self.voter.as_mut() else { return Message::Refuse(Refuse::new("not-a-voter")) };
524        if !voter.candidates.contains(roster, from) {
525            return Message::Refuse(Refuse::new("not-a-candidate"));
526        }
527        let me = self.our_cert.peer_id.as_str();
528        match msg {
529            // Only a device that is itself in the voter set votes, and only for a candidate
530            // that counts the same voter set.
531            Message::LeaseAsk(_) if !voter.candidates.contains(roster, me) => Message::Refuse(Refuse::new("not-a-voter")),
532            Message::LeaseAsk(ask) if ask.voters != voter.candidates.digest(roster) => Message::Refuse(Refuse::new("voters-differ")),
533            Message::LeaseAsk(ask) => voter.on_ask_with(from, &ask, Instant::now(), job),
534            Message::LeaseFree(free) => {
535                voter.on_free(from, &free);
536                Message::LeaseFree(free)
537            }
538            _ => Message::Refuse(Refuse::new("unexpected")),
539        }
540    }
541}
542
543/// A held lease. Valid only while [`is_valid`](Self::is_valid); carry [`term`](Self::term) in
544/// every fenced command.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub struct LeaseHandle {
547    name: LeaseName,
548    term: Term,
549    holder: String,
550    valid_until: Instant,
551}
552
553impl LeaseHandle {
554    pub fn name(&self) -> &LeaseName {
555        &self.name
556    }
557
558    pub fn term(&self) -> Term {
559        self.term
560    }
561
562    /// This device's peer id.
563    pub fn holder(&self) -> &str {
564        &self.holder
565    }
566
567    pub fn is_valid(&self) -> bool {
568        Instant::now() < self.valid_until
569    }
570
571    pub fn remaining(&self) -> Duration {
572        self.valid_until.saturating_duration_since(Instant::now())
573    }
574}
575
576/// Why a lease was not got or kept.
577#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
578#[non_exhaustive]
579pub enum LeaseError {
580    /// Someone else holds it; try again after `retry_in`.
581    #[error("held by {holder} (term {term}), retry in {retry_in:?}")]
582    Held { holder: String, term: Term, retry_in: Duration },
583    /// Not enough voters answered with a grant.
584    #[error("no quorum: {reached} of {needed} grants")]
585    NoQuorum { reached: usize, needed: usize },
586    /// The lease ran out before a renewal reached a quorum: stop acting.
587    #[error("lease lost")]
588    Lost,
589    /// This device is not among the voters (only voters stand), or no longer is.
590    #[error("not a voter for this lease")]
591    NotEligible,
592    /// Not claimable yet (a job's retry backoff, since 0.8.1); try again after `retry_in`.
593    #[error("not yet, retry in {retry_in:?}")]
594    NotYet { retry_in: Duration },
595    #[error("{0}")]
596    Sync(String),
597}
598
599impl From<SyncError> for LeaseError {
600    fn from(e: SyncError) -> Self {
601        LeaseError::Sync(e.to_string())
602    }
603}
604
605/// What an [`Elector`] sees.
606#[derive(Debug, Clone, PartialEq, Eq)]
607#[non_exhaustive]
608pub enum LeaseState {
609    Held {
610        term: Term,
611    },
612    /// Learned from a voter's answer.
613    Follower {
614        holder: String,
615        term: Term,
616    },
617    /// Nobody known to hold it.
618    Vacant,
619    NoQuorum {
620        reached: usize,
621        needed: usize,
622    },
623}
624
625type SyncNode = Node<Vec<u8>, Vec<u8>>;
626type AddrBook = Arc<dyn Fn(&str) -> Vec<Multiaddr> + Send + Sync>;
627
628/// The candidate side: acquires, renews and releases leases through a sync node and its
629/// shared state (as served by [`crate::start_node`]). The state's lock is never held across
630/// the network.
631#[derive(Clone)]
632pub struct Leases {
633    node: Arc<SyncNode>,
634    state: Arc<Mutex<SyncState>>,
635    addrs: AddrBook,
636    terms: Arc<Mutex<HashMap<LeaseName, Term>>>,
637}
638
639enum Answer {
640    Grant(Duration),
641    Deny(LeaseDeny),
642    None,
643}
644
645impl Leases {
646    pub fn new(node: Arc<SyncNode>, state: Arc<Mutex<SyncState>>) -> Self {
647        Self { node, state, addrs: Arc::new(|_| Vec::new()), terms: Arc::default() }
648    }
649
650    /// The shared state the leases use.
651    pub fn state(&self) -> &Arc<Mutex<SyncState>> {
652        &self.state
653    }
654
655    /// Addresses to dial each voter on (default none: the node's known addresses).
656    pub fn with_addrs(mut self, addrs: impl Fn(&str) -> Vec<Multiaddr> + Send + Sync + 'static) -> Self {
657        self.addrs = Arc::new(addrs);
658        self
659    }
660
661    fn known_term(&self, name: &LeaseName) -> Term {
662        let local = self.terms.lock().map(|t| t.get(name).copied().unwrap_or_default()).unwrap_or_default();
663        let voted = self.state.lock().ok().and_then(|st| st.voter.as_ref().map(|v| v.max_term(name))).unwrap_or_default();
664        local.max(voted)
665    }
666
667    /// The highest term this device has seen for `name` (asked for, granted or voted on);
668    /// a holder whose term is below it has lost the lease (since 0.8.1).
669    pub fn term_seen(&self, name: &LeaseName) -> Term {
670        self.known_term(name)
671    }
672
673    fn learn(&self, name: &LeaseName, term: Term) {
674        if let Ok(mut t) = self.terms.lock() {
675            let e = t.entry(name.clone()).or_default();
676            *e = (*e).max(term);
677        }
678    }
679
680    /// Ask every voter at once (this device's own voter answers locally) and collect answers
681    /// until all came, `needed` grants came, or `wait` passed. Unreachable voters can't hold
682    /// a round up beyond `wait`; their threads finish on their own.
683    fn ask_all(&self, voters: &[String], me: &str, msg: &Message, needed: usize, wait: Duration) -> Vec<Answer> {
684        let (tx, rx) = std::sync::mpsc::channel();
685        for v in voters {
686            let (this, v, me, msg, tx) = (self.clone(), v.clone(), me.to_string(), msg.clone(), tx.clone());
687            std::thread::spawn(move || {
688                let _ = tx.send(this.ask_one(&v, &me, &msg));
689            });
690        }
691        drop(tx);
692        let deadline = Instant::now() + wait;
693        let mut out = Vec::new();
694        let mut grants = 0;
695        while out.len() < voters.len() && grants < needed {
696            let left = deadline.saturating_duration_since(Instant::now());
697            match rx.recv_timeout(left) {
698                Ok(a) => {
699                    if matches!(a, Answer::Grant(_)) {
700                        grants += 1;
701                    }
702                    out.push(a);
703                }
704                Err(_) => break,
705            }
706        }
707        out
708    }
709
710    /// Tell voters to drop a promise, waiting at most `wait` for them.
711    fn free_all(&self, voters: &[String], me: &str, free: LeaseFree, wait: Duration) {
712        let _ = self.ask_all(voters, me, &Message::LeaseFree(free), usize::MAX, wait);
713    }
714
715    fn ask_one(&self, voter: &str, me: &str, msg: &Message) -> Answer {
716        let reply = if voter == me {
717            match self.state.lock() {
718                Ok(mut st) => st.on_lease(me, msg.clone()),
719                Err(_) => return Answer::None,
720            }
721        } else {
722            match self.request(voter, msg) {
723                Ok(m) => m,
724                Err(_) => return Answer::None,
725            }
726        };
727        match reply {
728            Message::LeaseGrant(g) => Answer::Grant(Duration::from_millis(g.duration_ms as u64)),
729            Message::LeaseDeny(d) => Answer::Deny(d),
730            _ => Answer::None,
731        }
732    }
733
734    fn request(&self, voter: &str, msg: &Message) -> Result<Message> {
735        let peer: PeerId = voter.parse().map_err(|_| SyncError::Protocol("bad voter peer id".into()))?;
736        // Envelopes are bound to the asking peer (us), as in every other sync request.
737        let me = self.node.peer_id().to_string();
738        let env = {
739            let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
740            let key = st.current_key();
741            st.seal_envelope(&key, LEASE_TYPE, &me, msg)?
742        };
743        let addrs = (self.addrs)(voter);
744        let reply = self.node.request(peer, &addrs, encode(&env)?)?;
745        let env: crate::protocol::Envelope = decode(&reply)?;
746        let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
747        st.open_envelope(&env, &me)
748    }
749
750    fn voters(&self, cfg: &LeaseConfig) -> std::result::Result<(String, Vec<String>), LeaseError> {
751        let st = self.state.lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
752        Ok((st.our_cert.peer_id.clone(), cfg.voters.resolve(&st.roster)))
753    }
754
755    fn digest(&self, cfg: &LeaseConfig) -> String {
756        self.state.lock().map(|st| cfg.voters.digest(&st.roster)).unwrap_or_default()
757    }
758
759    /// Acquire `name` with a new term. Fails with [`LeaseError::Held`] while another
760    /// device holds it (with when to try again) or [`LeaseError::NoQuorum`].
761    pub fn acquire(&self, name: &LeaseName, cfg: &LeaseConfig) -> std::result::Result<LeaseHandle, LeaseError> {
762        let (me, voters) = self.voters(cfg)?;
763        let needed = voters.len() / 2 + 1;
764        if !voters.contains(&me) {
765            return Err(LeaseError::NotEligible);
766        }
767        let term = self.known_term(name).next();
768        let ask = LeaseAsk {
769            name: name.clone(),
770            term,
771            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
772            renew: false,
773            voters: self.digest(cfg),
774        };
775        let t0 = Instant::now();
776        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
777        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
778        // A term some voter granted is used up; one nobody granted can be asked for again, so
779        // retrying while a holder lives doesn't inflate the terms.
780        if !granted.is_empty() {
781            self.learn(name, term);
782        }
783        if granted.len() >= needed {
784            let handle = LeaseHandle { name: name.clone(), term, holder: me.clone(), valid_until: valid_until(t0, &granted, cfg) };
785            if let Some(typ) = &cfg.record_type
786                && let Ok(mut st) = self.state.lock()
787            {
788                let rec = LeaseRecord { name: name.clone(), term, holder: me };
789                if let Ok(bytes) = encode(&rec) {
790                    let _ = st.write(wall_ms(), typ, name.as_str(), &bytes);
791                }
792            }
793            return Ok(handle);
794        }
795        // Let go of the grants we did get, so the next candidate needn't wait them out.
796        if !granted.is_empty() {
797            self.free_all(&voters, &me, LeaseFree { name: name.clone(), term }, Duration::ZERO);
798        }
799        let denies: Vec<&LeaseDeny> = answers.iter().filter_map(|a| if let Answer::Deny(d) = a { Some(d) } else { None }).collect();
800        if let Some(max) = denies.iter().map(|d| d.max_term).max() {
801            self.learn(name, max);
802        }
803        if let Some(d) =
804            denies.iter().filter(|d| !d.holder.is_empty() && d.holder != me && d.remaining_ms > 0).max_by_key(|d| (d.promised, d.remaining_ms))
805        {
806            return Err(LeaseError::Held { holder: d.holder.clone(), term: d.promised, retry_in: Duration::from_millis(d.remaining_ms as u64) });
807        }
808        Err(LeaseError::NoQuorum { reached: granted.len(), needed })
809    }
810
811    /// Renew a held lease (same term). Until it runs out a failed renewal is
812    /// [`LeaseError::NoQuorum`] and the handle stays valid; after, [`LeaseError::Lost`].
813    pub fn renew(&self, handle: &mut LeaseHandle, cfg: &LeaseConfig) -> std::result::Result<(), LeaseError> {
814        let (me, voters) = self.voters(cfg)?;
815        let needed = voters.len() / 2 + 1;
816        let ask = LeaseAsk {
817            name: handle.name.clone(),
818            term: handle.term,
819            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
820            renew: true,
821            voters: self.digest(cfg),
822        };
823        let t0 = Instant::now();
824        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
825        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
826        if !voters.contains(&me) {
827            return if handle.is_valid() { Err(LeaseError::NotEligible) } else { Err(LeaseError::Lost) };
828        }
829        if granted.len() >= needed {
830            handle.valid_until = handle.valid_until.max(valid_until(t0, &granted, cfg));
831            return Ok(());
832        }
833        for a in &answers {
834            if let Answer::Deny(d) = a {
835                self.learn(&handle.name, d.max_term);
836            }
837        }
838        if handle.is_valid() { Err(LeaseError::NoQuorum { reached: granted.len(), needed }) } else { Err(LeaseError::Lost) }
839    }
840
841    /// Let go of a lease: voters drop the promise, so the next holder needn't wait it out.
842    pub fn release(&self, handle: LeaseHandle, cfg: &LeaseConfig) {
843        if let Ok((me, voters)) = self.voters(cfg) {
844            self.free_all(&voters, &me, LeaseFree { name: handle.name.clone(), term: handle.term }, ask_wait(cfg));
845        }
846    }
847
848    /// Keep acquiring and renewing `name` in the background (see [`Elector`]).
849    pub fn elect(&self, name: LeaseName, cfg: LeaseConfig) -> Elector {
850        Elector::start(self.clone(), name, cfg)
851    }
852}
853
854/// How long a round waits for answers: a third of the lease, so a lease got is still worth
855/// most of its duration.
856fn ask_wait(cfg: &LeaseConfig) -> Duration {
857    (cfg.duration / 3).max(Duration::from_millis(100))
858}
859
860fn valid_until(t0: Instant, granted: &[Duration], cfg: &LeaseConfig) -> Instant {
861    let shortest = granted.iter().min().copied().unwrap_or_default().min(cfg.duration);
862    let safe = shortest.mul_f64(1.0 - cfg.max_drift).saturating_sub(EPSILON);
863    t0 + safe
864}
865
866/// A random wait in `[0, max)`.
867fn jitter(max: Duration) -> Duration {
868    let mut b = [0u8; 8];
869    if max.is_zero() || getrandom::fill(&mut b).is_err() {
870        return Duration::ZERO;
871    }
872    let ms = max.as_millis().max(1) as u64;
873    Duration::from_millis(u64::from_le_bytes(b) % ms)
874}
875
876fn wall_ms() -> u64 {
877    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
878}
879
880struct Shared {
881    state: Mutex<(LeaseState, Option<LeaseHandle>)>,
882    changed: Condvar,
883    stop: AtomicBool,
884}
885
886/// Acquires and renews one lease in a background thread. No preemption: a live holder keeps
887/// it; after a lapse the lowest-ranked candidate tries first. Dropping it (or
888/// [`release`](Self::release)) lets go.
889pub struct Elector {
890    shared: Arc<Shared>,
891    thread: Option<std::thread::JoinHandle<()>>,
892}
893
894impl Elector {
895    fn start(leases: Leases, name: LeaseName, cfg: LeaseConfig) -> Self {
896        let shared = Arc::new(Shared { state: Mutex::new((LeaseState::Vacant, None)), changed: Condvar::new(), stop: AtomicBool::new(false) });
897        let s = shared.clone();
898        let thread =
899            std::thread::Builder::new().name(format!("lease {name}")).spawn(move || run_elector(leases, name, cfg, s)).expect("spawn lease thread");
900        Self { shared, thread: Some(thread) }
901    }
902
903    pub fn state(&self) -> LeaseState {
904        self.shared.state.lock().map(|s| s.0.clone()).unwrap_or(LeaseState::Vacant)
905    }
906
907    /// The lease while held and valid.
908    pub fn handle(&self) -> Option<LeaseHandle> {
909        self.shared.state.lock().ok().and_then(|s| s.1.clone()).filter(|h| h.is_valid())
910    }
911
912    /// Wait until `want` holds for the state, at most `timeout`. Returns the state then.
913    pub fn wait_for(&self, timeout: Duration, want: impl Fn(&LeaseState) -> bool) -> LeaseState {
914        let deadline = Instant::now() + timeout;
915        let mut g = match self.shared.state.lock() {
916            Ok(g) => g,
917            Err(_) => return LeaseState::Vacant,
918        };
919        while !want(&g.0) {
920            let left = deadline.saturating_duration_since(Instant::now());
921            if left.is_zero() {
922                break;
923            }
924            g = match self.shared.changed.wait_timeout(g, left) {
925                Ok((g, _)) => g,
926                Err(_) => return LeaseState::Vacant,
927            };
928        }
929        g.0.clone()
930    }
931
932    /// Stop and let go of the lease.
933    pub fn release(mut self) {
934        self.stop_now();
935    }
936
937    fn stop_now(&mut self) {
938        self.shared.stop.store(true, Ordering::SeqCst);
939        self.shared.changed.notify_all();
940        if let Some(t) = self.thread.take() {
941            let _ = t.join();
942        }
943    }
944}
945
946impl Drop for Elector {
947    fn drop(&mut self) {
948        self.stop_now();
949    }
950}
951
952fn set(shared: &Shared, state: LeaseState, handle: Option<LeaseHandle>) {
953    if let Ok(mut g) = shared.state.lock() {
954        *g = (state, handle);
955    }
956    shared.changed.notify_all();
957}
958
959fn sleep(shared: &Shared, d: Duration) {
960    let deadline = Instant::now() + d;
961    while !shared.stop.load(Ordering::SeqCst) {
962        let left = deadline.saturating_duration_since(Instant::now());
963        if left.is_zero() {
964            return;
965        }
966        std::thread::sleep(left.min(Duration::from_millis(20)));
967    }
968}
969
970fn run_elector(leases: Leases, name: LeaseName, cfg: LeaseConfig, shared: Arc<Shared>) {
971    let mut held: Option<LeaseHandle> = None;
972    while !shared.stop.load(Ordering::SeqCst) {
973        let (me, voters) = match leases.voters(&cfg) {
974            Ok(v) => v,
975            Err(_) => return,
976        };
977        let rank = voters.iter().position(|v| *v == me).unwrap_or(voters.len()) as u32;
978        if let Some(h) = held.as_mut() {
979            sleep(&shared, cfg.renew_every.min(h.remaining()));
980            if shared.stop.load(Ordering::SeqCst) {
981                break;
982            }
983            match leases.renew(h, &cfg) {
984                Ok(()) => set(&shared, LeaseState::Held { term: h.term }, Some(h.clone())),
985                Err(LeaseError::NoQuorum { .. }) if h.is_valid() => {}
986                Err(_) => {
987                    held = None;
988                    set(&shared, LeaseState::Vacant, None);
989                }
990            }
991            continue;
992        }
993        match leases.acquire(&name, &cfg) {
994            Ok(h) => {
995                set(&shared, LeaseState::Held { term: h.term }, Some(h.clone()));
996                held = Some(h);
997            }
998            Err(LeaseError::Held { holder, term, retry_in }) => {
999                set(&shared, LeaseState::Follower { holder, term }, None);
1000                sleep(&shared, retry_in.min(cfg.duration) + cfg.stagger * rank + jitter(cfg.stagger));
1001            }
1002            Err(LeaseError::NoQuorum { reached, needed }) => {
1003                // Two candidates that split the votes back off by rank plus a random part, so
1004                // they don't keep colliding.
1005                set(&shared, LeaseState::NoQuorum { reached, needed }, None);
1006                let base = (cfg.stagger * (rank + 1)).min(cfg.renew_every.max(Duration::from_millis(50)));
1007                sleep(&shared, base + jitter(cfg.stagger * 2));
1008            }
1009            Err(_) => {
1010                set(&shared, LeaseState::Vacant, None);
1011                sleep(&shared, cfg.renew_every.max(Duration::from_millis(50)));
1012            }
1013        }
1014    }
1015    if let Some(h) = held {
1016        leases.release(h, &cfg);
1017    }
1018    set(&shared, LeaseState::Vacant, None);
1019}
1020
1021/// Resource side: refuses commands that carry an older term than one already seen. Persist
1022/// [`export`](Self::export) so a restart keeps refusing.
1023#[derive(Debug, Clone, Default, PartialEq, Eq)]
1024pub struct FenceGuard {
1025    seen: HashMap<LeaseName, Term>,
1026}
1027
1028/// A command from an older term than the guard has seen.
1029#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
1030#[error("stale term: {seen} already seen")]
1031pub struct Stale {
1032    pub seen: Term,
1033}
1034
1035impl FenceGuard {
1036    pub fn new() -> Self {
1037        Self::default()
1038    }
1039
1040    /// Accepts `term` if it is at least the highest seen (and records it).
1041    pub fn check(&mut self, name: &LeaseName, term: Term) -> std::result::Result<(), Stale> {
1042        let seen = self.seen.entry(name.clone()).or_default();
1043        if term < *seen {
1044            return Err(Stale { seen: *seen });
1045        }
1046        *seen = term;
1047        Ok(())
1048    }
1049
1050    pub fn seen(&self, name: &LeaseName) -> Option<Term> {
1051        self.seen.get(name).copied()
1052    }
1053
1054    pub fn export(&self) -> Vec<u8> {
1055        let mut v: Vec<_> = self.seen.iter().map(|(n, t)| (n.clone(), *t)).collect();
1056        v.sort();
1057        encode(&v).unwrap_or_default()
1058    }
1059
1060    pub fn import(bytes: &[u8]) -> Result<Self> {
1061        let v: Vec<(LeaseName, Term)> = decode(bytes)?;
1062        Ok(Self { seen: v.into_iter().collect() })
1063    }
1064}
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069
1070    fn name(s: &str) -> LeaseName {
1071        LeaseName::new(s).unwrap()
1072    }
1073
1074    fn ask(n: &str, term: u64, renew: bool) -> LeaseAsk {
1075        LeaseAsk { name: name(n), term: Term(term), duration_ms: 1_000, renew, voters: String::new() }
1076    }
1077
1078    /// An ask for an hour, so the voter's limits decide the grant.
1079    fn ask_long(n: &str, term: u64, renew: bool) -> LeaseAsk {
1080        LeaseAsk { duration_ms: 3_600_000, ..ask(n, term, renew) }
1081    }
1082
1083    fn fresh() -> Voter {
1084        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_secs(1));
1085        v.grace_until = Instant::now() - Duration::from_secs(1);
1086        v
1087    }
1088
1089    #[test]
1090    fn a_voter_promises_one_holder_at_a_time() {
1091        let mut v = fresh();
1092        let t = Instant::now();
1093        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
1094        // Another candidate, even with a higher term, waits for the promise to end.
1095        let Message::LeaseDeny(d) = v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(10)) else { panic!() };
1096        assert_eq!((d.holder.as_str(), d.promised, d.max_term), ("a", Term(1), Term(1)));
1097        assert!(d.remaining_ms > 900);
1098        // The holder renews; b still can't.
1099        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t + Duration::from_millis(500)), Message::LeaseGrant(_)));
1100        assert!(matches!(v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(1_200)), Message::LeaseDeny(_)));
1101        // After it lapses b takes over with a higher term, never the same or a lower one.
1102        let later = t + Duration::from_millis(1_600);
1103        assert!(matches!(v.on_ask("b", &ask("s", 1, false), later), Message::LeaseDeny(_)));
1104        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
1105        // a's renewal of the old term is refused now.
1106        assert!(matches!(v.on_ask("a", &ask("s", 1, true), later), Message::LeaseDeny(_)));
1107        // Release lets the next one in at once.
1108        v.on_free("b", &LeaseFree { name: name("s"), term: Term(2) });
1109        assert!(matches!(v.on_ask("a", &ask("s", 3, false), later), Message::LeaseGrant(_)));
1110        // Durations are capped.
1111        let mut long = ask("t", 1, false);
1112        long.duration_ms = 600_000;
1113        let Message::LeaseGrant(g) = v.on_ask("a", &long, later) else { panic!() };
1114        assert_eq!(g.duration_ms, 1_000);
1115    }
1116
1117    #[test]
1118    fn a_restarted_voter_refuses_takeovers_for_one_duration_and_keeps_its_terms() {
1119        let mut v = fresh();
1120        let t = Instant::now();
1121        v.on_ask("a", &ask("s", 4, false), t);
1122        let bytes = v.export();
1123        let mut back = Voter::import(&bytes, Voters::Peers(vec![])).unwrap().with_max_duration(Duration::from_secs(1));
1124        assert_eq!(back.max_term(&name("s")), Term(4));
1125        let now = Instant::now();
1126        // b can't take over during the grace, a can renew the term it holds.
1127        let Message::LeaseDeny(d) = back.on_ask("b", &ask("s", 5, false), now) else { panic!() };
1128        assert_eq!(d.holder, "a");
1129        assert!(d.remaining_ms > 0);
1130        assert!(matches!(back.on_ask("a", &ask("s", 4, true), now), Message::LeaseGrant(_)));
1131        // A new lease name is refused during the grace too.
1132        assert!(matches!(back.on_ask("b", &ask("other", 1, false), now), Message::LeaseDeny(_)));
1133    }
1134
1135    #[test]
1136    fn a_new_term_is_stored_before_it_is_granted() {
1137        use std::sync::atomic::AtomicUsize;
1138        let writes = Arc::new(AtomicUsize::new(0));
1139        let fail = Arc::new(AtomicBool::new(false));
1140        let (w, f) = (writes.clone(), fail.clone());
1141        let mut v = fresh().with_persist(move |bytes| {
1142            if f.load(Ordering::SeqCst) {
1143                return Err(std::io::Error::other("disk full"));
1144            }
1145            assert!(Voter::import(bytes, Voters::Peers(vec![])).is_ok());
1146            w.fetch_add(1, Ordering::SeqCst);
1147            Ok(())
1148        });
1149        let t = Instant::now();
1150        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
1151        assert_eq!(writes.load(Ordering::SeqCst), 1);
1152        // Renewals write nothing.
1153        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t), Message::LeaseGrant(_)));
1154        assert_eq!(writes.load(Ordering::SeqCst), 1);
1155        // A term that can't be stored is not granted, and leaves no trace.
1156        fail.store(true, Ordering::SeqCst);
1157        let later = t + Duration::from_secs(2);
1158        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseDeny(_)));
1159        assert_eq!(v.max_term(&name("s")), Term(1));
1160        fail.store(false, Ordering::SeqCst);
1161        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
1162        assert_eq!(writes.load(Ordering::SeqCst), 2);
1163    }
1164
1165    #[test]
1166    fn the_fence_refuses_older_terms() {
1167        let mut g = FenceGuard::new();
1168        let n = name("ymir.scheduler");
1169        g.check(&n, Term(3)).unwrap();
1170        g.check(&n, Term(3)).unwrap();
1171        assert_eq!(g.check(&n, Term(2)), Err(Stale { seen: Term(3) }));
1172        g.check(&n, Term(4)).unwrap();
1173        let back = FenceGuard::import(&g.export()).unwrap();
1174        assert_eq!(back.seen(&n), Some(Term(4)));
1175    }
1176
1177    #[test]
1178    fn names_are_checked_and_the_holder_stops_before_any_voter() {
1179        assert!(LeaseName::new("ymir.jobs/42").is_ok());
1180        assert!(LeaseName::new("").is_err());
1181        assert!(LeaseName::new("bad name").is_err());
1182        assert!(LeaseName::new("x".repeat(201)).is_err());
1183        let cfg = LeaseConfig::for_role("r");
1184        let t0 = Instant::now();
1185        let until = valid_until(t0, &[Duration::from_secs(15), Duration::from_secs(10)], &cfg);
1186        assert!(until < t0 + Duration::from_millis(9_900) && until > t0 + Duration::from_millis(9_800));
1187        assert_eq!((cfg.duration, cfg.renew_every, cfg.stagger, cfg.max_drift), (DEFAULT_DURATION, DEFAULT_RENEW_EVERY, DEFAULT_STAGGER, 0.01));
1188    }
1189
1190    #[test]
1191    fn skewed_clock_rates_within_the_drift_never_overlap_two_holders() {
1192        // The holder counts from before it sent the ask, the voter from when it got it. With
1193        // clock rates up to half the drift apart either way, the holder's lease (in real time)
1194        // ends before the voter's promise does, so a takeover can't overlap it.
1195        let cfg = LeaseConfig::for_role("r");
1196        let t0 = Instant::now();
1197        let safe = valid_until(t0, &[cfg.duration], &cfg) - t0;
1198        let half = cfg.max_drift / 2.0;
1199        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)] {
1200            let holder_real = safe.as_secs_f64() / holder_rate;
1201            let voter_real = cfg.duration.as_secs_f64() / voter_rate;
1202            assert!(holder_real < voter_real, "holder {holder_rate} voter {voter_rate}: {holder_real} >= {voter_real}");
1203        }
1204        // Wall clocks play no part: a lease is the same however far apart they are.
1205        assert_eq!(valid_until(t0, &[cfg.duration], &cfg), t0 + safe);
1206    }
1207
1208    #[test]
1209    fn prefix_limits_allow_longer_grants_and_hold_off_after_a_lapse() {
1210        let long = Duration::from_secs(60);
1211        let wait = Duration::from_secs(300);
1212        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_millis(10)).with_limits("ymir.train/", long, wait);
1213        let t0 = Instant::now() + long; // past the grace
1214        let n = "ymir.train/j1";
1215        match v.on_ask("a", &ask_long(n, 1, false), t0) {
1216            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 60_000, "the prefix's 60 s, not the default maximum"),
1217            m => panic!("{m:?}"),
1218        }
1219        match v.on_ask("a", &ask_long("other", 1, false), t0) {
1220            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 10),
1221            m => panic!("{m:?}"),
1222        }
1223        // a stops renewing: its promise lapses at t0 + 60 s, and b waits 5 more minutes.
1224        let lapsed = t0 + long + Duration::from_secs(1);
1225        match v.on_ask("b", &ask_long(n, 2, false), lapsed) {
1226            Message::LeaseDeny(d) => {
1227                assert_eq!((d.holder.as_str(), d.promised), ("a", Term(1)));
1228                assert_eq!(d.remaining_ms, 299_000);
1229            }
1230            m => panic!("{m:?}"),
1231        }
1232        // a itself may come back on its term inside the wait (a network blip).
1233        assert!(matches!(v.on_ask("a", &ask_long(n, 1, true), lapsed), Message::LeaseGrant(_)));
1234        let later = lapsed + long + wait;
1235        assert!(matches!(v.on_ask("b", &ask_long(n, 2, false), later), Message::LeaseGrant(_)));
1236        // A released lease has no wait.
1237        v.on_free("b", &LeaseFree { name: name(n), term: Term(2) });
1238        assert!(matches!(v.on_ask("c", &ask_long(n, 3, false), later), Message::LeaseGrant(_)));
1239        // A job's own limits replace the prefix's.
1240        let job = LeaseLimits::new(Duration::from_secs(20), Duration::ZERO);
1241        match v.on_ask_with("c", &ask_long(n, 3, true), later, Some(job)) {
1242            Message::LeaseGrant(g) => assert_eq!(g.duration_ms, 20_000),
1243            m => panic!("{m:?}"),
1244        }
1245    }
1246
1247    #[test]
1248    fn a_restarted_voter_waits_out_its_longest_grant() {
1249        let long = Duration::from_secs(60);
1250        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_millis(10)).with_limits("j/", long, Duration::ZERO);
1251        assert!(matches!(v.on_ask("a", &ask_long("j/1", 1, false), Instant::now() + long), Message::LeaseGrant(_)));
1252        let bytes = v.export();
1253        // Restarted without the prefix limits: the stored longest grant still sets the grace.
1254        let mut r = Voter::import(&bytes, Voters::Peers(vec![])).unwrap().with_max_duration(Duration::from_millis(10));
1255        let now = Instant::now() + Duration::from_secs(30);
1256        assert!(matches!(r.on_ask("b", &ask_long("j/1", 2, false), now), Message::LeaseDeny(_)), "still inside a's possible 60 s");
1257        // A 0.8.0 voter.cbor (no longest grant) still loads.
1258        #[derive(Serialize)]
1259        struct Old {
1260            v: u8,
1261            terms: Vec<(LeaseName, Term, String)>,
1262        }
1263        let old = encode(&Old { v: 1, terms: vec![(name("j/1"), Term(4), "a".into())] }).unwrap();
1264        assert_eq!(Voter::import(&old, Voters::Peers(vec![])).unwrap().max_term(&name("j/1")), Term(4));
1265    }
1266}