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`](crate::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/// Who votes (and who may stand): devices with an active cert in the roster.
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum Voters {
105    /// Devices whose grant holds this role (`Roster::has_role`), for example `ymir.inference`.
106    Role(String),
107    /// A fixed set of peer ids (those with an active cert count).
108    Peers(Vec<String>),
109}
110
111impl Voters {
112    /// The voters now, sorted (the order is the candidate rank).
113    pub fn resolve(&self, roster: &Roster) -> Vec<String> {
114        let mut v: Vec<String> = match self {
115            Voters::Role(role) => roster.active().filter(|c| roster.has_role(&c.peer_id, role)).map(|c| c.peer_id.clone()).collect(),
116            Voters::Peers(peers) => peers.iter().filter(|p| roster.get(p).is_some_and(|c| c.active())).cloned().collect(),
117        };
118        v.sort();
119        v.dedup();
120        v
121    }
122
123    /// A digest of [`resolve`](Self::resolve): candidates send it with every ask and a voter
124    /// grants only when its own view of the voter set is the same, so a candidate with a stale
125    /// roster can't win a majority of a voter set that has since changed.
126    pub fn digest(&self, roster: &Roster) -> String {
127        let mut h = blake3::Hasher::new();
128        h.update(b"weirdnet-sync/v1/voters\n");
129        for v in self.resolve(roster) {
130            h.update(v.as_bytes());
131            h.update(b"\n");
132        }
133        h.finalize().to_hex()[..32].to_string()
134    }
135
136    pub fn contains(&self, roster: &Roster, peer: &str) -> bool {
137        match self {
138            Voters::Role(role) => roster.get(peer).is_some_and(|c| c.active()) && roster.has_role(peer, role),
139            Voters::Peers(peers) => peers.iter().any(|p| p == peer) && roster.get(peer).is_some_and(|c| c.active()),
140        }
141    }
142}
143
144/// How a lease is held.
145#[derive(Debug, Clone)]
146#[non_exhaustive]
147pub struct LeaseConfig {
148    /// How long a grant lasts at a voter (capped by the voter's maximum).
149    pub duration: Duration,
150    /// How often the [`Elector`] renews.
151    pub renew_every: Duration,
152    /// Assumed worst clock-rate drift; the holder's lease is shortened by it.
153    pub max_drift: f64,
154    pub voters: Voters,
155    /// Extra wait per candidate rank after a lapse, so the lowest rank tries first.
156    pub stagger: Duration,
157    /// Write a [`LeaseRecord`] under this record type on each new term (informational).
158    pub record_type: Option<String>,
159}
160
161impl LeaseConfig {
162    /// The defaults (15 s, renew every 5 s, 1 % drift, 500 ms stagger) with these voters.
163    pub fn new(voters: Voters) -> Self {
164        Self {
165            duration: DEFAULT_DURATION,
166            renew_every: DEFAULT_RENEW_EVERY,
167            max_drift: DEFAULT_MAX_DRIFT,
168            voters,
169            stagger: DEFAULT_STAGGER,
170            record_type: None,
171        }
172    }
173
174    /// Voters are the devices granted `role`.
175    pub fn for_role(role: impl Into<String>) -> Self {
176        Self::new(Voters::Role(role.into()))
177    }
178
179    /// Sets the duration and renews every third of it.
180    pub fn with_duration(mut self, duration: Duration) -> Self {
181        self.duration = duration;
182        self.renew_every = duration / 3;
183        self
184    }
185
186    pub fn with_stagger(mut self, stagger: Duration) -> Self {
187        self.stagger = stagger;
188        self
189    }
190
191    pub fn with_max_drift(mut self, drift: f64) -> Self {
192        self.max_drift = drift.clamp(0.0, 0.5);
193        self
194    }
195
196    pub fn with_record_type(mut self, typ: impl Into<String>) -> Self {
197        self.record_type = Some(typ.into());
198        self
199    }
200}
201
202/// A candidate asks for (or renews) a lease.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204pub struct LeaseAsk {
205    pub name: LeaseName,
206    pub term: Term,
207    pub duration_ms: u32,
208    pub renew: bool,
209    /// [`Voters::digest`] of the voter set the candidate counts its majority in.
210    pub voters: String,
211}
212
213/// A voter granted it.
214#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
215pub struct LeaseGrant {
216    pub name: LeaseName,
217    pub term: Term,
218    pub duration_ms: u32,
219}
220
221/// A voter did not grant it: who it promised, for how much longer, and the highest term it
222/// has granted (ask with a higher one next time).
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
224pub struct LeaseDeny {
225    pub name: LeaseName,
226    pub promised: Term,
227    pub holder: String,
228    pub remaining_ms: u32,
229    pub max_term: Term,
230}
231
232/// The holder lets go (also the answer to one).
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct LeaseFree {
235    pub name: LeaseName,
236    pub term: Term,
237}
238
239/// Who holds a lease, written to the op log on each new term for display. Nothing trusts it.
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
241pub struct LeaseRecord {
242    pub name: LeaseName,
243    pub term: Term,
244    pub holder: String,
245}
246
247#[derive(Debug, Clone)]
248struct Promise {
249    term: Term,
250    holder: String,
251    until: Instant,
252}
253
254#[derive(Debug, Clone, Default)]
255struct Slot {
256    max_term: Term,
257    /// Who `max_term` went to.
258    max_holder: String,
259    promise: Option<Promise>,
260}
261
262#[derive(Serialize, Deserialize)]
263struct Persisted {
264    v: u8,
265    terms: Vec<(LeaseName, Term, String)>,
266}
267
268type Persist = Arc<dyn Fn(&[u8]) -> std::io::Result<()> + Send + Sync>;
269
270/// The voter side (one per device, kept in [`SyncState::voter`]). Not secret.
271///
272/// Give it a store with [`with_persist`](Self::with_persist) (or use
273/// [`Identity::enable_voter`](crate::Identity::enable_voter)): every new term is then written
274/// before it is granted. Without one, a voter that crashes before the app saved
275/// [`export`](Self::export) may grant a term it already gave out, so two holders could share
276/// a fencing token (their leases still never overlap in time).
277#[derive(Clone)]
278pub struct Voter {
279    candidates: Voters,
280    max_duration: Duration,
281    grace_until: Instant,
282    slots: HashMap<LeaseName, Slot>,
283    persist: Option<Persist>,
284}
285
286impl std::fmt::Debug for Voter {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        f.debug_struct("Voter")
289            .field("candidates", &self.candidates)
290            .field("max_duration", &self.max_duration)
291            .field("slots", &self.slots)
292            .field("persist", &self.persist.is_some())
293            .finish()
294    }
295}
296
297impl Voter {
298    /// A voter answering candidates in `candidates` (normally the same [`Voters`] the
299    /// leases use). It refuses takeovers for [`DEFAULT_DURATION`] after it starts.
300    pub fn new(candidates: Voters) -> Self {
301        Self { candidates, max_duration: DEFAULT_DURATION, grace_until: Instant::now() + DEFAULT_DURATION, slots: HashMap::new(), persist: None }
302    }
303
304    /// Write [`export`](Self::export) with `store` before each new term is granted (renewals
305    /// write nothing). If the write fails the ask is denied.
306    pub fn with_persist(mut self, store: impl Fn(&[u8]) -> std::io::Result<()> + Send + Sync + 'static) -> Self {
307        self.persist = Some(Arc::new(store));
308        self
309    }
310
311    /// The longest grant it gives, which is also the restart grace (default 15 s).
312    pub fn with_max_duration(mut self, max: Duration) -> Self {
313        let started = self.grace_until - self.max_duration;
314        self.max_duration = max;
315        self.grace_until = started + max;
316        self
317    }
318
319    /// The highest terms (and their holders), to persist; not secret.
320    pub fn export(&self) -> Vec<u8> {
321        let mut terms: Vec<_> = self.slots.iter().map(|(n, s)| (n.clone(), s.max_term, s.max_holder.clone())).collect();
322        terms.sort();
323        encode(&Persisted { v: 1, terms }).unwrap_or_default()
324    }
325
326    /// A voter restarted from [`export`](Self::export): it never grants an old term again and
327    /// refuses takeovers for one maximum duration.
328    pub fn import(bytes: &[u8], candidates: Voters) -> Result<Self> {
329        let p: Persisted = decode(bytes)?;
330        let mut v = Self::new(candidates);
331        for (name, term, holder) in p.terms {
332            v.slots.insert(name, Slot { max_term: term, max_holder: holder, promise: None });
333        }
334        Ok(v)
335    }
336
337    /// The longest grant it gives (and its restart grace).
338    pub fn max_duration(&self) -> Duration {
339        self.max_duration
340    }
341
342    /// The highest term granted for `name`.
343    pub fn max_term(&self, name: &LeaseName) -> Term {
344        self.slots.get(name).map(|s| s.max_term).unwrap_or_default()
345    }
346
347    pub fn candidates(&self) -> &Voters {
348        &self.candidates
349    }
350
351    /// The voter rule. `from` is the transport-authenticated asker.
352    pub fn on_ask(&mut self, from: &str, ask: &LeaseAsk, now: Instant) -> Message {
353        let in_grace = now < self.grace_until;
354        let grace_left = self.grace_until.saturating_duration_since(now);
355        let duration = Duration::from_millis(ask.duration_ms as u64).min(self.max_duration);
356        let slot = self.slots.entry(ask.name.clone()).or_default();
357        let live = slot.promise.as_ref().filter(|p| p.until > now).cloned();
358        // Renewal (or re-establishing a lapsed promise): only the holder the term went to, and
359        // only while no higher term was granted here.
360        let renewal = ask.term == slot.max_term && slot.max_holder == from && ask.term.0 > 0;
361        // Takeover or first grant: a higher term, nobody else promised.
362        let takeover = ask.term > slot.max_term && live.as_ref().is_none_or(|p| p.holder == from) && !in_grace;
363        if renewal || takeover {
364            let before = slot.clone();
365            slot.max_term = ask.term;
366            slot.max_holder = from.to_string();
367            slot.promise = Some(Promise { term: ask.term, holder: from.to_string(), until: now + duration });
368            if takeover && let Some(store) = self.persist.clone() {
369                // The new term must be durable before anyone acts on it.
370                if store(&self.export()).is_err() {
371                    let slot = self.slots.entry(ask.name.clone()).or_default();
372                    *slot = before;
373                    return Message::LeaseDeny(LeaseDeny {
374                        name: ask.name.clone(),
375                        promised: slot.max_term,
376                        holder: String::new(),
377                        remaining_ms: 0,
378                        max_term: slot.max_term,
379                    });
380                }
381            }
382            return Message::LeaseGrant(LeaseGrant { name: ask.name.clone(), term: ask.term, duration_ms: duration.as_millis() as u32 });
383        }
384        let (promised, holder, remaining) = match &live {
385            Some(p) => (p.term, p.holder.clone(), p.until - now),
386            None if in_grace => (slot.max_term, slot.max_holder.clone(), grace_left),
387            None => (slot.max_term, String::new(), Duration::ZERO),
388        };
389        Message::LeaseDeny(LeaseDeny {
390            name: ask.name.clone(),
391            promised,
392            holder,
393            remaining_ms: remaining.as_millis().min(u32::MAX as u128) as u32,
394            max_term: slot.max_term,
395        })
396    }
397
398    /// The holder lets go of `term`.
399    pub fn on_free(&mut self, from: &str, free: &LeaseFree) {
400        if let Some(slot) = self.slots.get_mut(&free.name)
401            && slot.promise.as_ref().is_some_and(|p| p.term == free.term && p.holder == from)
402        {
403            slot.promise = None;
404        }
405    }
406}
407
408impl SyncState {
409    /// Makes this device a voter (or stops it voting with `None`).
410    pub fn set_voter(&mut self, voter: Option<Voter>) {
411        self.voter = voter;
412    }
413
414    /// A lease message from `from` (already opened under the head key).
415    pub(crate) fn on_lease(&mut self, from: &str, msg: Message) -> Message {
416        use crate::protocol::Refuse;
417        let check = self.roster.check_caller(&WEIRDNET, &self.user_key, from, None);
418        if check != CallerCheck::Linked {
419            return Message::Refuse(Refuse::new(check.reason().unwrap_or("unknown-device")));
420        }
421        let roster = &self.roster;
422        let Some(voter) = self.voter.as_mut() else { return Message::Refuse(Refuse::new("not-a-voter")) };
423        if !voter.candidates.contains(roster, from) {
424            return Message::Refuse(Refuse::new("not-a-candidate"));
425        }
426        let me = self.our_cert.peer_id.as_str();
427        match msg {
428            // Only a device that is itself in the voter set votes, and only for a candidate
429            // that counts the same voter set.
430            Message::LeaseAsk(_) if !voter.candidates.contains(roster, me) => Message::Refuse(Refuse::new("not-a-voter")),
431            Message::LeaseAsk(ask) if ask.voters != voter.candidates.digest(roster) => Message::Refuse(Refuse::new("voters-differ")),
432            Message::LeaseAsk(ask) => voter.on_ask(from, &ask, Instant::now()),
433            Message::LeaseFree(free) => {
434                voter.on_free(from, &free);
435                Message::LeaseFree(free)
436            }
437            _ => Message::Refuse(Refuse::new("unexpected")),
438        }
439    }
440}
441
442/// A held lease. Valid only while [`is_valid`](Self::is_valid); carry [`term`](Self::term) in
443/// every fenced command.
444#[derive(Debug, Clone, PartialEq, Eq)]
445pub struct LeaseHandle {
446    name: LeaseName,
447    term: Term,
448    holder: String,
449    valid_until: Instant,
450}
451
452impl LeaseHandle {
453    pub fn name(&self) -> &LeaseName {
454        &self.name
455    }
456
457    pub fn term(&self) -> Term {
458        self.term
459    }
460
461    /// This device's peer id.
462    pub fn holder(&self) -> &str {
463        &self.holder
464    }
465
466    pub fn is_valid(&self) -> bool {
467        Instant::now() < self.valid_until
468    }
469
470    pub fn remaining(&self) -> Duration {
471        self.valid_until.saturating_duration_since(Instant::now())
472    }
473}
474
475/// Why a lease was not got or kept.
476#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
477#[non_exhaustive]
478pub enum LeaseError {
479    /// Someone else holds it; try again after `retry_in`.
480    #[error("held by {holder} (term {term}), retry in {retry_in:?}")]
481    Held { holder: String, term: Term, retry_in: Duration },
482    /// Not enough voters answered with a grant.
483    #[error("no quorum: {reached} of {needed} grants")]
484    NoQuorum { reached: usize, needed: usize },
485    /// The lease ran out before a renewal reached a quorum: stop acting.
486    #[error("lease lost")]
487    Lost,
488    /// This device is not among the voters (only voters stand), or no longer is.
489    #[error("not a voter for this lease")]
490    NotEligible,
491    #[error("{0}")]
492    Sync(String),
493}
494
495impl From<SyncError> for LeaseError {
496    fn from(e: SyncError) -> Self {
497        LeaseError::Sync(e.to_string())
498    }
499}
500
501/// What an [`Elector`] sees.
502#[derive(Debug, Clone, PartialEq, Eq)]
503#[non_exhaustive]
504pub enum LeaseState {
505    Held {
506        term: Term,
507    },
508    /// Learned from a voter's answer.
509    Follower {
510        holder: String,
511        term: Term,
512    },
513    /// Nobody known to hold it.
514    Vacant,
515    NoQuorum {
516        reached: usize,
517        needed: usize,
518    },
519}
520
521type SyncNode = Node<Vec<u8>, Vec<u8>>;
522type AddrBook = Arc<dyn Fn(&str) -> Vec<Multiaddr> + Send + Sync>;
523
524/// The candidate side: acquires, renews and releases leases through a sync node and its
525/// shared state (as served by [`crate::start_node`]). The state's lock is never held across
526/// the network.
527#[derive(Clone)]
528pub struct Leases {
529    node: Arc<SyncNode>,
530    state: Arc<Mutex<SyncState>>,
531    addrs: AddrBook,
532    terms: Arc<Mutex<HashMap<LeaseName, Term>>>,
533}
534
535enum Answer {
536    Grant(Duration),
537    Deny(LeaseDeny),
538    None,
539}
540
541impl Leases {
542    pub fn new(node: Arc<SyncNode>, state: Arc<Mutex<SyncState>>) -> Self {
543        Self { node, state, addrs: Arc::new(|_| Vec::new()), terms: Arc::default() }
544    }
545
546    /// The shared state the leases use.
547    pub fn state(&self) -> &Arc<Mutex<SyncState>> {
548        &self.state
549    }
550
551    /// Addresses to dial each voter on (default none: the node's known addresses).
552    pub fn with_addrs(mut self, addrs: impl Fn(&str) -> Vec<Multiaddr> + Send + Sync + 'static) -> Self {
553        self.addrs = Arc::new(addrs);
554        self
555    }
556
557    fn known_term(&self, name: &LeaseName) -> Term {
558        let local = self.terms.lock().map(|t| t.get(name).copied().unwrap_or_default()).unwrap_or_default();
559        let voted = self.state.lock().ok().and_then(|st| st.voter.as_ref().map(|v| v.max_term(name))).unwrap_or_default();
560        local.max(voted)
561    }
562
563    fn learn(&self, name: &LeaseName, term: Term) {
564        if let Ok(mut t) = self.terms.lock() {
565            let e = t.entry(name.clone()).or_default();
566            *e = (*e).max(term);
567        }
568    }
569
570    /// Ask every voter at once (this device's own voter answers locally) and collect answers
571    /// until all came, `needed` grants came, or `wait` passed. Unreachable voters can't hold
572    /// a round up beyond `wait`; their threads finish on their own.
573    fn ask_all(&self, voters: &[String], me: &str, msg: &Message, needed: usize, wait: Duration) -> Vec<Answer> {
574        let (tx, rx) = std::sync::mpsc::channel();
575        for v in voters {
576            let (this, v, me, msg, tx) = (self.clone(), v.clone(), me.to_string(), msg.clone(), tx.clone());
577            std::thread::spawn(move || {
578                let _ = tx.send(this.ask_one(&v, &me, &msg));
579            });
580        }
581        drop(tx);
582        let deadline = Instant::now() + wait;
583        let mut out = Vec::new();
584        let mut grants = 0;
585        while out.len() < voters.len() && grants < needed {
586            let left = deadline.saturating_duration_since(Instant::now());
587            match rx.recv_timeout(left) {
588                Ok(a) => {
589                    if matches!(a, Answer::Grant(_)) {
590                        grants += 1;
591                    }
592                    out.push(a);
593                }
594                Err(_) => break,
595            }
596        }
597        out
598    }
599
600    /// Tell voters to drop a promise, waiting at most `wait` for them.
601    fn free_all(&self, voters: &[String], me: &str, free: LeaseFree, wait: Duration) {
602        let _ = self.ask_all(voters, me, &Message::LeaseFree(free), usize::MAX, wait);
603    }
604
605    fn ask_one(&self, voter: &str, me: &str, msg: &Message) -> Answer {
606        let reply = if voter == me {
607            match self.state.lock() {
608                Ok(mut st) => st.on_lease(me, msg.clone()),
609                Err(_) => return Answer::None,
610            }
611        } else {
612            match self.request(voter, msg) {
613                Ok(m) => m,
614                Err(_) => return Answer::None,
615            }
616        };
617        match reply {
618            Message::LeaseGrant(g) => Answer::Grant(Duration::from_millis(g.duration_ms as u64)),
619            Message::LeaseDeny(d) => Answer::Deny(d),
620            _ => Answer::None,
621        }
622    }
623
624    fn request(&self, voter: &str, msg: &Message) -> Result<Message> {
625        let peer: PeerId = voter.parse().map_err(|_| SyncError::Protocol("bad voter peer id".into()))?;
626        // Envelopes are bound to the asking peer (us), as in every other sync request.
627        let me = self.node.peer_id().to_string();
628        let env = {
629            let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
630            let key = st.current_key();
631            st.seal_envelope(&key, LEASE_TYPE, &me, msg)?
632        };
633        let addrs = (self.addrs)(voter);
634        let reply = self.node.request(peer, &addrs, encode(&env)?)?;
635        let env: crate::protocol::Envelope = decode(&reply)?;
636        let st = self.state.lock().map_err(|_| SyncError::Protocol("sync state lock poisoned".into()))?;
637        st.open_envelope(&env, &me)
638    }
639
640    fn voters(&self, cfg: &LeaseConfig) -> std::result::Result<(String, Vec<String>), LeaseError> {
641        let st = self.state.lock().map_err(|_| LeaseError::Sync("sync state lock poisoned".into()))?;
642        Ok((st.our_cert.peer_id.clone(), cfg.voters.resolve(&st.roster)))
643    }
644
645    fn digest(&self, cfg: &LeaseConfig) -> String {
646        self.state.lock().map(|st| cfg.voters.digest(&st.roster)).unwrap_or_default()
647    }
648
649    /// Acquire `name` with a new term. Fails with [`LeaseError::Held`] while another
650    /// device holds it (with when to try again) or [`LeaseError::NoQuorum`].
651    pub fn acquire(&self, name: &LeaseName, cfg: &LeaseConfig) -> std::result::Result<LeaseHandle, LeaseError> {
652        let (me, voters) = self.voters(cfg)?;
653        let needed = voters.len() / 2 + 1;
654        if !voters.contains(&me) {
655            return Err(LeaseError::NotEligible);
656        }
657        let term = self.known_term(name).next();
658        let ask = LeaseAsk {
659            name: name.clone(),
660            term,
661            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
662            renew: false,
663            voters: self.digest(cfg),
664        };
665        let t0 = Instant::now();
666        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
667        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
668        // A term some voter granted is used up; one nobody granted can be asked for again, so
669        // retrying while a holder lives doesn't inflate the terms.
670        if !granted.is_empty() {
671            self.learn(name, term);
672        }
673        if granted.len() >= needed {
674            let handle = LeaseHandle { name: name.clone(), term, holder: me.clone(), valid_until: valid_until(t0, &granted, cfg) };
675            if let Some(typ) = &cfg.record_type
676                && let Ok(mut st) = self.state.lock()
677            {
678                let rec = LeaseRecord { name: name.clone(), term, holder: me };
679                if let Ok(bytes) = encode(&rec) {
680                    let _ = st.write(wall_ms(), typ, name.as_str(), &bytes);
681                }
682            }
683            return Ok(handle);
684        }
685        // Let go of the grants we did get, so the next candidate needn't wait them out.
686        if !granted.is_empty() {
687            self.free_all(&voters, &me, LeaseFree { name: name.clone(), term }, Duration::ZERO);
688        }
689        let denies: Vec<&LeaseDeny> = answers.iter().filter_map(|a| if let Answer::Deny(d) = a { Some(d) } else { None }).collect();
690        if let Some(max) = denies.iter().map(|d| d.max_term).max() {
691            self.learn(name, max);
692        }
693        if let Some(d) =
694            denies.iter().filter(|d| !d.holder.is_empty() && d.holder != me && d.remaining_ms > 0).max_by_key(|d| (d.promised, d.remaining_ms))
695        {
696            return Err(LeaseError::Held { holder: d.holder.clone(), term: d.promised, retry_in: Duration::from_millis(d.remaining_ms as u64) });
697        }
698        Err(LeaseError::NoQuorum { reached: granted.len(), needed })
699    }
700
701    /// Renew a held lease (same term). Until it runs out a failed renewal is
702    /// [`LeaseError::NoQuorum`] and the handle stays valid; after, [`LeaseError::Lost`].
703    pub fn renew(&self, handle: &mut LeaseHandle, cfg: &LeaseConfig) -> std::result::Result<(), LeaseError> {
704        let (me, voters) = self.voters(cfg)?;
705        let needed = voters.len() / 2 + 1;
706        let ask = LeaseAsk {
707            name: handle.name.clone(),
708            term: handle.term,
709            duration_ms: cfg.duration.as_millis().min(u32::MAX as u128) as u32,
710            renew: true,
711            voters: self.digest(cfg),
712        };
713        let t0 = Instant::now();
714        let answers = self.ask_all(&voters, &me, &Message::LeaseAsk(ask), needed, ask_wait(cfg));
715        let granted: Vec<Duration> = answers.iter().filter_map(|a| if let Answer::Grant(d) = a { Some(*d) } else { None }).collect();
716        if !voters.contains(&me) {
717            return if handle.is_valid() { Err(LeaseError::NotEligible) } else { Err(LeaseError::Lost) };
718        }
719        if granted.len() >= needed {
720            handle.valid_until = handle.valid_until.max(valid_until(t0, &granted, cfg));
721            return Ok(());
722        }
723        for a in &answers {
724            if let Answer::Deny(d) = a {
725                self.learn(&handle.name, d.max_term);
726            }
727        }
728        if handle.is_valid() { Err(LeaseError::NoQuorum { reached: granted.len(), needed }) } else { Err(LeaseError::Lost) }
729    }
730
731    /// Let go of a lease: voters drop the promise, so the next holder needn't wait it out.
732    pub fn release(&self, handle: LeaseHandle, cfg: &LeaseConfig) {
733        if let Ok((me, voters)) = self.voters(cfg) {
734            self.free_all(&voters, &me, LeaseFree { name: handle.name.clone(), term: handle.term }, ask_wait(cfg));
735        }
736    }
737
738    /// Keep acquiring and renewing `name` in the background (see [`Elector`]).
739    pub fn elect(&self, name: LeaseName, cfg: LeaseConfig) -> Elector {
740        Elector::start(self.clone(), name, cfg)
741    }
742}
743
744/// How long a round waits for answers: a third of the lease, so a lease got is still worth
745/// most of its duration.
746fn ask_wait(cfg: &LeaseConfig) -> Duration {
747    (cfg.duration / 3).max(Duration::from_millis(100))
748}
749
750fn valid_until(t0: Instant, granted: &[Duration], cfg: &LeaseConfig) -> Instant {
751    let shortest = granted.iter().min().copied().unwrap_or_default().min(cfg.duration);
752    let safe = shortest.mul_f64(1.0 - cfg.max_drift).saturating_sub(EPSILON);
753    t0 + safe
754}
755
756/// A random wait in `[0, max)`.
757fn jitter(max: Duration) -> Duration {
758    let mut b = [0u8; 8];
759    if max.is_zero() || getrandom::fill(&mut b).is_err() {
760        return Duration::ZERO;
761    }
762    let ms = max.as_millis().max(1) as u64;
763    Duration::from_millis(u64::from_le_bytes(b) % ms)
764}
765
766fn wall_ms() -> u64 {
767    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
768}
769
770struct Shared {
771    state: Mutex<(LeaseState, Option<LeaseHandle>)>,
772    changed: Condvar,
773    stop: AtomicBool,
774}
775
776/// Acquires and renews one lease in a background thread. No preemption: a live holder keeps
777/// it; after a lapse the lowest-ranked candidate tries first. Dropping it (or
778/// [`release`](Self::release)) lets go.
779pub struct Elector {
780    shared: Arc<Shared>,
781    thread: Option<std::thread::JoinHandle<()>>,
782}
783
784impl Elector {
785    fn start(leases: Leases, name: LeaseName, cfg: LeaseConfig) -> Self {
786        let shared = Arc::new(Shared { state: Mutex::new((LeaseState::Vacant, None)), changed: Condvar::new(), stop: AtomicBool::new(false) });
787        let s = shared.clone();
788        let thread =
789            std::thread::Builder::new().name(format!("lease {name}")).spawn(move || run_elector(leases, name, cfg, s)).expect("spawn lease thread");
790        Self { shared, thread: Some(thread) }
791    }
792
793    pub fn state(&self) -> LeaseState {
794        self.shared.state.lock().map(|s| s.0.clone()).unwrap_or(LeaseState::Vacant)
795    }
796
797    /// The lease while held and valid.
798    pub fn handle(&self) -> Option<LeaseHandle> {
799        self.shared.state.lock().ok().and_then(|s| s.1.clone()).filter(|h| h.is_valid())
800    }
801
802    /// Wait until `want` holds for the state, at most `timeout`. Returns the state then.
803    pub fn wait_for(&self, timeout: Duration, want: impl Fn(&LeaseState) -> bool) -> LeaseState {
804        let deadline = Instant::now() + timeout;
805        let mut g = match self.shared.state.lock() {
806            Ok(g) => g,
807            Err(_) => return LeaseState::Vacant,
808        };
809        while !want(&g.0) {
810            let left = deadline.saturating_duration_since(Instant::now());
811            if left.is_zero() {
812                break;
813            }
814            g = match self.shared.changed.wait_timeout(g, left) {
815                Ok((g, _)) => g,
816                Err(_) => return LeaseState::Vacant,
817            };
818        }
819        g.0.clone()
820    }
821
822    /// Stop and let go of the lease.
823    pub fn release(mut self) {
824        self.stop_now();
825    }
826
827    fn stop_now(&mut self) {
828        self.shared.stop.store(true, Ordering::SeqCst);
829        self.shared.changed.notify_all();
830        if let Some(t) = self.thread.take() {
831            let _ = t.join();
832        }
833    }
834}
835
836impl Drop for Elector {
837    fn drop(&mut self) {
838        self.stop_now();
839    }
840}
841
842fn set(shared: &Shared, state: LeaseState, handle: Option<LeaseHandle>) {
843    if let Ok(mut g) = shared.state.lock() {
844        *g = (state, handle);
845    }
846    shared.changed.notify_all();
847}
848
849fn sleep(shared: &Shared, d: Duration) {
850    let deadline = Instant::now() + d;
851    while !shared.stop.load(Ordering::SeqCst) {
852        let left = deadline.saturating_duration_since(Instant::now());
853        if left.is_zero() {
854            return;
855        }
856        std::thread::sleep(left.min(Duration::from_millis(20)));
857    }
858}
859
860fn run_elector(leases: Leases, name: LeaseName, cfg: LeaseConfig, shared: Arc<Shared>) {
861    let mut held: Option<LeaseHandle> = None;
862    while !shared.stop.load(Ordering::SeqCst) {
863        let (me, voters) = match leases.voters(&cfg) {
864            Ok(v) => v,
865            Err(_) => return,
866        };
867        let rank = voters.iter().position(|v| *v == me).unwrap_or(voters.len()) as u32;
868        if let Some(h) = held.as_mut() {
869            sleep(&shared, cfg.renew_every.min(h.remaining()));
870            if shared.stop.load(Ordering::SeqCst) {
871                break;
872            }
873            match leases.renew(h, &cfg) {
874                Ok(()) => set(&shared, LeaseState::Held { term: h.term }, Some(h.clone())),
875                Err(LeaseError::NoQuorum { .. }) if h.is_valid() => {}
876                Err(_) => {
877                    held = None;
878                    set(&shared, LeaseState::Vacant, None);
879                }
880            }
881            continue;
882        }
883        match leases.acquire(&name, &cfg) {
884            Ok(h) => {
885                set(&shared, LeaseState::Held { term: h.term }, Some(h.clone()));
886                held = Some(h);
887            }
888            Err(LeaseError::Held { holder, term, retry_in }) => {
889                set(&shared, LeaseState::Follower { holder, term }, None);
890                sleep(&shared, retry_in.min(cfg.duration) + cfg.stagger * rank + jitter(cfg.stagger));
891            }
892            Err(LeaseError::NoQuorum { reached, needed }) => {
893                // Two candidates that split the votes back off by rank plus a random part, so
894                // they don't keep colliding.
895                set(&shared, LeaseState::NoQuorum { reached, needed }, None);
896                let base = (cfg.stagger * (rank + 1)).min(cfg.renew_every.max(Duration::from_millis(50)));
897                sleep(&shared, base + jitter(cfg.stagger * 2));
898            }
899            Err(_) => {
900                set(&shared, LeaseState::Vacant, None);
901                sleep(&shared, cfg.renew_every.max(Duration::from_millis(50)));
902            }
903        }
904    }
905    if let Some(h) = held {
906        leases.release(h, &cfg);
907    }
908    set(&shared, LeaseState::Vacant, None);
909}
910
911/// Resource side: refuses commands that carry an older term than one already seen. Persist
912/// [`export`](Self::export) so a restart keeps refusing.
913#[derive(Debug, Clone, Default, PartialEq, Eq)]
914pub struct FenceGuard {
915    seen: HashMap<LeaseName, Term>,
916}
917
918/// A command from an older term than the guard has seen.
919#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
920#[error("stale term: {seen} already seen")]
921pub struct Stale {
922    pub seen: Term,
923}
924
925impl FenceGuard {
926    pub fn new() -> Self {
927        Self::default()
928    }
929
930    /// Accepts `term` if it is at least the highest seen (and records it).
931    pub fn check(&mut self, name: &LeaseName, term: Term) -> std::result::Result<(), Stale> {
932        let seen = self.seen.entry(name.clone()).or_default();
933        if term < *seen {
934            return Err(Stale { seen: *seen });
935        }
936        *seen = term;
937        Ok(())
938    }
939
940    pub fn seen(&self, name: &LeaseName) -> Option<Term> {
941        self.seen.get(name).copied()
942    }
943
944    pub fn export(&self) -> Vec<u8> {
945        let mut v: Vec<_> = self.seen.iter().map(|(n, t)| (n.clone(), *t)).collect();
946        v.sort();
947        encode(&v).unwrap_or_default()
948    }
949
950    pub fn import(bytes: &[u8]) -> Result<Self> {
951        let v: Vec<(LeaseName, Term)> = decode(bytes)?;
952        Ok(Self { seen: v.into_iter().collect() })
953    }
954}
955
956#[cfg(test)]
957mod tests {
958    use super::*;
959
960    fn name(s: &str) -> LeaseName {
961        LeaseName::new(s).unwrap()
962    }
963
964    fn ask(n: &str, term: u64, renew: bool) -> LeaseAsk {
965        LeaseAsk { name: name(n), term: Term(term), duration_ms: 1_000, renew, voters: String::new() }
966    }
967
968    fn fresh() -> Voter {
969        let mut v = Voter::new(Voters::Peers(vec![])).with_max_duration(Duration::from_secs(1));
970        v.grace_until = Instant::now() - Duration::from_secs(1);
971        v
972    }
973
974    #[test]
975    fn a_voter_promises_one_holder_at_a_time() {
976        let mut v = fresh();
977        let t = Instant::now();
978        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
979        // Another candidate, even with a higher term, waits for the promise to end.
980        let Message::LeaseDeny(d) = v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(10)) else { panic!() };
981        assert_eq!((d.holder.as_str(), d.promised, d.max_term), ("a", Term(1), Term(1)));
982        assert!(d.remaining_ms > 900);
983        // The holder renews; b still can't.
984        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t + Duration::from_millis(500)), Message::LeaseGrant(_)));
985        assert!(matches!(v.on_ask("b", &ask("s", 2, false), t + Duration::from_millis(1_200)), Message::LeaseDeny(_)));
986        // After it lapses b takes over with a higher term, never the same or a lower one.
987        let later = t + Duration::from_millis(1_600);
988        assert!(matches!(v.on_ask("b", &ask("s", 1, false), later), Message::LeaseDeny(_)));
989        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
990        // a's renewal of the old term is refused now.
991        assert!(matches!(v.on_ask("a", &ask("s", 1, true), later), Message::LeaseDeny(_)));
992        // Release lets the next one in at once.
993        v.on_free("b", &LeaseFree { name: name("s"), term: Term(2) });
994        assert!(matches!(v.on_ask("a", &ask("s", 3, false), later), Message::LeaseGrant(_)));
995        // Durations are capped.
996        let mut long = ask("t", 1, false);
997        long.duration_ms = 600_000;
998        let Message::LeaseGrant(g) = v.on_ask("a", &long, later) else { panic!() };
999        assert_eq!(g.duration_ms, 1_000);
1000    }
1001
1002    #[test]
1003    fn a_restarted_voter_refuses_takeovers_for_one_duration_and_keeps_its_terms() {
1004        let mut v = fresh();
1005        let t = Instant::now();
1006        v.on_ask("a", &ask("s", 4, false), t);
1007        let bytes = v.export();
1008        let mut back = Voter::import(&bytes, Voters::Peers(vec![])).unwrap().with_max_duration(Duration::from_secs(1));
1009        assert_eq!(back.max_term(&name("s")), Term(4));
1010        let now = Instant::now();
1011        // b can't take over during the grace, a can renew the term it holds.
1012        let Message::LeaseDeny(d) = back.on_ask("b", &ask("s", 5, false), now) else { panic!() };
1013        assert_eq!(d.holder, "a");
1014        assert!(d.remaining_ms > 0);
1015        assert!(matches!(back.on_ask("a", &ask("s", 4, true), now), Message::LeaseGrant(_)));
1016        // A new lease name is refused during the grace too.
1017        assert!(matches!(back.on_ask("b", &ask("other", 1, false), now), Message::LeaseDeny(_)));
1018    }
1019
1020    #[test]
1021    fn a_new_term_is_stored_before_it_is_granted() {
1022        use std::sync::atomic::AtomicUsize;
1023        let writes = Arc::new(AtomicUsize::new(0));
1024        let fail = Arc::new(AtomicBool::new(false));
1025        let (w, f) = (writes.clone(), fail.clone());
1026        let mut v = fresh().with_persist(move |bytes| {
1027            if f.load(Ordering::SeqCst) {
1028                return Err(std::io::Error::other("disk full"));
1029            }
1030            assert!(Voter::import(bytes, Voters::Peers(vec![])).is_ok());
1031            w.fetch_add(1, Ordering::SeqCst);
1032            Ok(())
1033        });
1034        let t = Instant::now();
1035        assert!(matches!(v.on_ask("a", &ask("s", 1, false), t), Message::LeaseGrant(_)));
1036        assert_eq!(writes.load(Ordering::SeqCst), 1);
1037        // Renewals write nothing.
1038        assert!(matches!(v.on_ask("a", &ask("s", 1, true), t), Message::LeaseGrant(_)));
1039        assert_eq!(writes.load(Ordering::SeqCst), 1);
1040        // A term that can't be stored is not granted, and leaves no trace.
1041        fail.store(true, Ordering::SeqCst);
1042        let later = t + Duration::from_secs(2);
1043        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseDeny(_)));
1044        assert_eq!(v.max_term(&name("s")), Term(1));
1045        fail.store(false, Ordering::SeqCst);
1046        assert!(matches!(v.on_ask("b", &ask("s", 2, false), later), Message::LeaseGrant(_)));
1047        assert_eq!(writes.load(Ordering::SeqCst), 2);
1048    }
1049
1050    #[test]
1051    fn the_fence_refuses_older_terms() {
1052        let mut g = FenceGuard::new();
1053        let n = name("ymir.scheduler");
1054        g.check(&n, Term(3)).unwrap();
1055        g.check(&n, Term(3)).unwrap();
1056        assert_eq!(g.check(&n, Term(2)), Err(Stale { seen: Term(3) }));
1057        g.check(&n, Term(4)).unwrap();
1058        let back = FenceGuard::import(&g.export()).unwrap();
1059        assert_eq!(back.seen(&n), Some(Term(4)));
1060    }
1061
1062    #[test]
1063    fn names_are_checked_and_the_holder_stops_before_any_voter() {
1064        assert!(LeaseName::new("ymir.jobs/42").is_ok());
1065        assert!(LeaseName::new("").is_err());
1066        assert!(LeaseName::new("bad name").is_err());
1067        assert!(LeaseName::new("x".repeat(201)).is_err());
1068        let cfg = LeaseConfig::for_role("r");
1069        let t0 = Instant::now();
1070        let until = valid_until(t0, &[Duration::from_secs(15), Duration::from_secs(10)], &cfg);
1071        assert!(until < t0 + Duration::from_millis(9_900) && until > t0 + Duration::from_millis(9_800));
1072        assert_eq!((cfg.duration, cfg.renew_every, cfg.stagger, cfg.max_drift), (DEFAULT_DURATION, DEFAULT_RENEW_EVERY, DEFAULT_STAGGER, 0.01));
1073    }
1074
1075    #[test]
1076    fn skewed_clock_rates_within_the_drift_never_overlap_two_holders() {
1077        // The holder counts from before it sent the ask, the voter from when it got it. With
1078        // clock rates up to half the drift apart either way, the holder's lease (in real time)
1079        // ends before the voter's promise does, so a takeover can't overlap it.
1080        let cfg = LeaseConfig::for_role("r");
1081        let t0 = Instant::now();
1082        let safe = valid_until(t0, &[cfg.duration], &cfg) - t0;
1083        let half = cfg.max_drift / 2.0;
1084        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)] {
1085            let holder_real = safe.as_secs_f64() / holder_rate;
1086            let voter_real = cfg.duration.as_secs_f64() / voter_rate;
1087            assert!(holder_real < voter_real, "holder {holder_rate} voter {voter_rate}: {holder_real} >= {voter_real}");
1088        }
1089        // Wall clocks play no part: a lease is the same however far apart they are.
1090        assert_eq!(valid_until(t0, &[cfg.duration], &cfg), t0 + safe);
1091    }
1092}