schedr_master/lease.rs
1//! Leading: one master per database (see archive/PROJECT.md, Components and roles: production
2//! path).
3//!
4//! A master takes the database's lease before it starts (a second one waits as a standby),
5//! renews it every third of [`Leadership::period`], and leads only while its last renewal is
6//! recent enough **by its own monotonic clock**: a renewal begun at `t` makes it lead until
7//! `t + period − query limit`, before the lease itself can expire by the database's clock (it
8//! was set at or after `t`), so a master cut off from the database pauses before another can
9//! take over.
10//!
11//! What rules out two masters writing at once is the database itself: the master writes
12//! through [`Leadership::fenced_db`], whose every write checks the lease in its own
13//! transaction (see `schedr_db::Database::fenced`), and is refused once another master took it
14//! over, however late it arrives.
15//!
16//! A renewal that finds the lease no longer its own (another holder, or the takeover counter
17//! moved on) means another master led meanwhile: this one's view is stale and it must end.
18//! A renewal never takes the lease back.
19
20use std::time::{Duration, Instant};
21
22use schedr_db::{Database, DbError};
23
24#[cfg(test)]
25mod tests;
26
27/// The default lease period (`lease_period`).
28pub const DEFAULT_LEASE_PERIOD: Duration = Duration::from_secs(30);
29
30/// What a renewal found.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Renewal {
33 /// Still held: leading for the period less a query limit from the renewal.
34 Held,
35 /// The database didn't answer: leading only until the last renewal's time is up.
36 Failed,
37 /// Another master took over (or holds it): this one must end.
38 TakenOver,
39}
40
41/// This master's hold on the lease.
42#[derive(Debug)]
43pub struct Leadership {
44 db: Database,
45 holder: String,
46 period: Duration,
47 epoch: i64,
48 until: Instant,
49}
50
51impl Leadership {
52 /// Waits until this master (`holder`, its incarnation) takes the lease for `period`,
53 /// trying every third of it; `on_wait` is told once when another master holds it (a
54 /// standby). The lease's table is created first if needed. Failures (the database not
55 /// there yet, two masters creating the table at once) are logged and tried again.
56 pub async fn take(
57 db: Database,
58 holder: String,
59 period: Duration,
60 on_wait: impl FnOnce(),
61 ) -> Self {
62 let mut on_wait = Some(on_wait);
63 loop {
64 let started = Instant::now();
65 match Self::try_take_at(&db, &holder, period).await {
66 Ok(Some(epoch)) => {
67 return Self {
68 until: started + lead_time(&db, period),
69 db,
70 holder,
71 period,
72 epoch,
73 };
74 }
75 Ok(None) => {
76 if let Some(on_wait) = on_wait.take() {
77 on_wait();
78 }
79 }
80 Err(error) => tracing::warn!(%error, "can't take the master's lease; trying again"),
81 }
82 tokio::time::sleep(period / 3).await;
83 }
84 }
85
86 /// Takes the lease for `holder` if no other master holds it: `None` if one does.
87 ///
88 /// # Errors
89 ///
90 /// [`DbError`] if the table can't be created or the lease read.
91 pub async fn try_take(
92 db: Database,
93 holder: String,
94 period: Duration,
95 ) -> Result<Option<Self>, DbError> {
96 let started = Instant::now();
97 let epoch = Self::try_take_at(&db, &holder, period).await?;
98 Ok(epoch.map(|epoch| Self {
99 until: started + lead_time(&db, period),
100 db,
101 holder,
102 period,
103 epoch,
104 }))
105 }
106
107 /// One try at the lease, the table created first: its takeover counter if taken.
108 async fn try_take_at(
109 db: &Database,
110 holder: &str,
111 period: Duration,
112 ) -> Result<Option<i64>, DbError> {
113 db.create_lease_table().await?;
114 db.take_lease(holder, period).await
115 }
116
117 /// Renews the lease, begun at `now` (within the query limit).
118 pub async fn renew(&mut self, now: Instant) -> Renewal {
119 match self
120 .db
121 .renew_lease(&self.holder, self.epoch, self.period)
122 .await
123 {
124 Ok(true) => {
125 self.until = now + lead_time(&self.db, self.period);
126 Renewal::Held
127 }
128 Ok(false) => Renewal::TakenOver,
129 Err(error) => {
130 tracing::warn!(%error, "the master's lease wasn't renewed");
131 Renewal::Failed
132 }
133 }
134 }
135
136 /// Whether this master leads at `now` (its last renewal recent enough).
137 #[must_use]
138 pub fn leads(&self, now: Instant) -> bool {
139 now < self.until
140 }
141
142 /// Until when this master leads unless renewed.
143 #[must_use]
144 pub const fn until(&self) -> Instant {
145 self.until
146 }
147
148 /// The database for this master's work: its writes are refused once another master took
149 /// the lease over.
150 #[must_use]
151 pub fn fenced_db(&self) -> Database {
152 self.db.fenced(&self.holder, self.epoch)
153 }
154
155 /// The lease period.
156 #[must_use]
157 pub const fn period(&self) -> Duration {
158 self.period
159 }
160
161 /// This master's name in the lease (its incarnation).
162 #[must_use]
163 pub fn holder(&self) -> &str {
164 &self.holder
165 }
166
167 /// The takeover counter when this master took the lease.
168 #[must_use]
169 pub const fn epoch(&self) -> i64 {
170 self.epoch
171 }
172
173 /// Gives the lease up (a clean shutdown): a standby takes over at once.
174 pub async fn release(&self) {
175 if let Err(error) = self.db.release_lease(&self.holder).await {
176 tracing::warn!(%error, "the master's lease wasn't given up; it expires by itself");
177 }
178 }
179}
180
181/// How long a renewal lets a master lead: the period less the query limit, so a query begun
182/// while leading ends before the lease can expire by the database's clock.
183fn lead_time(db: &Database, period: Duration) -> Duration {
184 period.saturating_sub(db.query_timeout())
185}