Skip to main content

schedr_db/
lease.rs

1//! The master's lease: one master per database (see archive/PROJECT.md, Components and roles:
2//! production path). A one-row table, taken and renewed by one statement each, timed by the
3//! **database's** clock, so it needs no session state: it works through any connection
4//! pooler (`PgBouncer` in transaction pooling too), and on SQLite.
5//!
6//! The row says who holds the lease, until when, and how many times it changed hands (the
7//! takeover counter, `epoch`): a master that finds the counter moved on knows another one led
8//! meanwhile.
9
10use std::time::Duration;
11
12use crate::database::{Database, DbError, Pool};
13
14#[cfg(test)]
15mod tests;
16
17/// The table, created before the migrations so a master can hold the lease while it migrates.
18const CREATE_SQLITE: &str = "CREATE TABLE IF NOT EXISTS master_lease (
19    id         INTEGER PRIMARY KEY CHECK (id = 1),
20    holder     TEXT NOT NULL,
21    epoch      INTEGER NOT NULL,
22    expires_at TEXT NOT NULL
23)";
24
25const CREATE_POSTGRES: &str = "CREATE TABLE IF NOT EXISTS master_lease (
26    id         INTEGER PRIMARY KEY CHECK (id = 1),
27    holder     TEXT NOT NULL,
28    epoch      INTEGER NOT NULL,
29    expires_at TIMESTAMPTZ NOT NULL
30)";
31
32/// SQLite's clock in the stored time format (six fraction digits, so text compares in time
33/// order); `$2` is the period as an SQLite modifier (`+15.000 seconds`).
34const TAKE_SQLITE: &str = "INSERT INTO master_lease (id, holder, epoch, expires_at)
35    VALUES (1, $1, 1, strftime('%Y-%m-%dT%H:%M:%f', 'now', $2) || '000Z')
36    ON CONFLICT (id) DO UPDATE SET
37        epoch = CASE WHEN master_lease.holder = excluded.holder
38            THEN master_lease.epoch ELSE master_lease.epoch + 1 END,
39        holder = excluded.holder,
40        expires_at = excluded.expires_at
41    WHERE master_lease.holder = excluded.holder
42        OR master_lease.expires_at < strftime('%Y-%m-%dT%H:%M:%f', 'now') || '000Z'
43    RETURNING epoch";
44
45/// `$2` is the period in milliseconds.
46const TAKE_POSTGRES: &str = "INSERT INTO master_lease (id, holder, epoch, expires_at)
47    VALUES (1, $1, 1, clock_timestamp() + $2 * interval '1 millisecond')
48    ON CONFLICT (id) DO UPDATE SET
49        epoch = CASE WHEN master_lease.holder = excluded.holder
50            THEN master_lease.epoch ELSE master_lease.epoch + 1 END,
51        holder = excluded.holder,
52        expires_at = excluded.expires_at
53    WHERE master_lease.holder = excluded.holder
54        OR master_lease.expires_at < clock_timestamp()
55    RETURNING epoch";
56
57/// Before a takeover on Postgres, in its transaction: the row locked against every master's
58/// write in progress (they hold it `FOR KEY SHARE`), so the takeover waits for them to commit.
59const LOCK_POSTGRES: &str = "SELECT 1 FROM master_lease WHERE id = 1 FOR UPDATE";
60
61/// Renewing extends only the holder's own lease, at the same takeover counter: never taking
62/// it back after a takeover. `$3` as in the take.
63const RENEW_SQLITE: &str = "UPDATE master_lease
64    SET expires_at = strftime('%Y-%m-%dT%H:%M:%f', 'now', $3) || '000Z'
65    WHERE holder = $1 AND epoch = $2
66    RETURNING epoch";
67
68const RENEW_POSTGRES: &str = "UPDATE master_lease
69    SET expires_at = clock_timestamp() + $3 * interval '1 millisecond'
70    WHERE holder = $1 AND epoch = $2
71    RETURNING epoch";
72
73/// Who holds the lease now (it hasn't expired), by the database's clock.
74const HOLDER_SQLITE: &str = "SELECT holder FROM master_lease
75    WHERE expires_at > strftime('%Y-%m-%dT%H:%M:%f', 'now') || '000Z'";
76
77const HOLDER_POSTGRES: &str =
78    "SELECT holder FROM master_lease WHERE expires_at > clock_timestamp()";
79
80const HELD_SQLITE: &str = "SELECT holder, expires_at FROM master_lease
81    WHERE expires_at > strftime('%Y-%m-%dT%H:%M:%f', 'now') || '000Z'";
82
83const HELD_POSTGRES: &str = "SELECT holder, to_char(expires_at AT TIME ZONE 'UTC', \
84    'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') FROM master_lease WHERE expires_at > clock_timestamp()";
85
86const RELEASE_SQLITE: &str = "UPDATE master_lease
87    SET expires_at = strftime('%Y-%m-%dT%H:%M:%f', 'now', '-1 seconds') || '000Z'
88    WHERE holder = $1";
89
90const RELEASE_POSTGRES: &str = "UPDATE master_lease
91    SET expires_at = clock_timestamp() - interval '1 second' WHERE holder = $1";
92
93/// A master's write checks its lease first, in the write's transaction (see
94/// [`Database::fenced`]).
95const FENCE_SQLITE: &str = "SELECT 1 FROM master_lease WHERE holder = $1 AND epoch = $2";
96
97/// As [`FENCE_SQLITE`] on Postgres, sent with the transaction's start (no parameters there:
98/// the lease reaches it through `schedr.holder` and `schedr.epoch`, set for the transaction
99/// only). The share lock lets renewals through (they change no key) but makes a takeover
100/// wait; a lease taken over raises [`NOT_LEADING`].
101const FENCE_POSTGRES: &str = "DO $fence$ BEGIN
102    IF NOT EXISTS (SELECT 1 FROM master_lease
103        WHERE holder = current_setting('schedr.holder')
104        AND epoch = current_setting('schedr.epoch')::integer
105        FOR KEY SHARE)
106    THEN RAISE EXCEPTION 'the lease was taken over' USING ERRCODE = 'SR001';
107    END IF;
108END $fence$;";
109
110/// The SQLSTATE [`FENCE_POSTGRES`] raises.
111pub(crate) const NOT_LEADING: &str = "SR001";
112
113impl Database {
114    /// Creates the lease's table if it isn't there (before the migrations, which create it
115    /// too; a race between two masters creating it is an error the caller tries again).
116    ///
117    /// # Errors
118    ///
119    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
120    pub async fn create_lease_table(&self) -> Result<(), DbError> {
121        self.limited(self.query_timeout(), async {
122            match self.pool() {
123                Pool::Sqlite(pool) => {
124                    sqlx::query(CREATE_SQLITE).execute(pool).await?;
125                }
126                Pool::Postgres(pool) => {
127                    sqlx::query(CREATE_POSTGRES).execute(pool).await?;
128                }
129            }
130            Ok(())
131        })
132        .await
133    }
134
135    /// Takes the lease for `holder` (a master's incarnation) until `period` from now by the
136    /// database's clock: the takeover counter if `holder` holds it now, `None` if another
137    /// master does and its lease hasn't expired. On Postgres a takeover waits for the writes
138    /// of the master before it that are in progress.
139    ///
140    /// # Errors
141    ///
142    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
143    pub async fn take_lease(&self, holder: &str, period: Duration) -> Result<Option<i64>, DbError> {
144        let epoch: Option<i32> = self
145            .limited(self.query_timeout(), async {
146                Ok(match self.pool() {
147                    Pool::Sqlite(pool) => {
148                        sqlx::query_scalar(TAKE_SQLITE)
149                            .bind(holder)
150                            .bind(sqlite_period(period))
151                            .fetch_optional(pool)
152                            .await?
153                    }
154                    Pool::Postgres(pool) => {
155                        // Not `pool.begin()`: a start cut short mustn't go back to the pool (B84).
156                        let mut starting = crate::query::Starting::new(pool.acquire().await?);
157                        let mut tx = starting.begin("BEGIN").await?;
158                        sqlx::query(LOCK_POSTGRES).execute(&mut *tx).await?;
159                        let epoch = sqlx::query_scalar(TAKE_POSTGRES)
160                            .bind(holder)
161                            .bind(millis(period))
162                            .fetch_optional(&mut *tx)
163                            .await?;
164                        tx.commit().await?;
165                        epoch
166                    }
167                })
168            })
169            .await?;
170        Ok(epoch.map(i64::from))
171    }
172
173    /// Renews `holder`'s lease taken at takeover counter `epoch` until `period` from now by
174    /// the database's clock: `false` if it is no longer `holder`'s at `epoch` (another master
175    /// took it over; it is left as it is).
176    ///
177    /// # Errors
178    ///
179    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
180    pub async fn renew_lease(
181        &self,
182        holder: &str,
183        epoch: i64,
184        period: Duration,
185    ) -> Result<bool, DbError> {
186        let epoch = i32::try_from(epoch).unwrap_or(i32::MAX);
187        let renewed: Option<i32> = self
188            .limited(self.query_timeout(), async {
189                Ok(match self.pool() {
190                    Pool::Sqlite(pool) => {
191                        sqlx::query_scalar(RENEW_SQLITE)
192                            .bind(holder)
193                            .bind(epoch)
194                            .bind(sqlite_period(period))
195                            .fetch_optional(pool)
196                            .await?
197                    }
198                    Pool::Postgres(pool) => {
199                        sqlx::query_scalar(RENEW_POSTGRES)
200                            .bind(holder)
201                            .bind(epoch)
202                            .bind(millis(period))
203                            .fetch_optional(pool)
204                            .await?
205                    }
206                })
207            })
208            .await?;
209        Ok(renewed.is_some())
210    }
211
212    /// The master holding the lease now, by the database's clock: `None` if none does (no
213    /// master took it, or its lease expired).
214    ///
215    /// # Errors
216    ///
217    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
218    pub async fn lease_holder(&self) -> Result<Option<String>, DbError> {
219        self.limited(self.query_timeout(), async {
220            Ok(match self.pool() {
221                Pool::Sqlite(pool) => {
222                    sqlx::query_scalar(HOLDER_SQLITE)
223                        .fetch_optional(pool)
224                        .await?
225                }
226                Pool::Postgres(pool) => {
227                    sqlx::query_scalar(HOLDER_POSTGRES)
228                        .fetch_optional(pool)
229                        .await?
230                }
231            })
232        })
233        .await
234    }
235
236    /// The master holding the lease now and when its lease runs out (UTC, as stored), by the
237    /// database's clock: `None` if none does (decision 452: a master that isn't leading names
238    /// the leader to its workers).
239    ///
240    /// # Errors
241    ///
242    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
243    pub async fn lease_held(&self) -> Result<Option<(String, String)>, DbError> {
244        self.limited(self.query_timeout(), async {
245            Ok(match self.pool() {
246                Pool::Sqlite(pool) => sqlx::query_as(HELD_SQLITE).fetch_optional(pool).await?,
247                Pool::Postgres(pool) => sqlx::query_as(HELD_POSTGRES).fetch_optional(pool).await?,
248            })
249        })
250        .await
251    }
252
253    /// Gives the lease up if `holder` has it (a clean shutdown), so a standby takes over at
254    /// once instead of when it expires.
255    ///
256    /// # Errors
257    ///
258    /// [`DbError::Sqlx`] if the statement fails, [`DbError::QueryTimeout`] past the limit.
259    pub async fn release_lease(&self, holder: &str) -> Result<(), DbError> {
260        self.limited(self.query_timeout(), async {
261            match self.pool() {
262                Pool::Sqlite(pool) => {
263                    sqlx::query(RELEASE_SQLITE)
264                        .bind(holder)
265                        .execute(pool)
266                        .await?;
267                }
268                Pool::Postgres(pool) => {
269                    sqlx::query(RELEASE_POSTGRES)
270                        .bind(holder)
271                        .execute(pool)
272                        .await?;
273                }
274            }
275            Ok(())
276        })
277        .await
278    }
279
280    /// In a write's transaction on SQLite: [`DbError::NotLeading`] if this database is a
281    /// master's ([`Self::fenced`]) and its lease was taken over.
282    pub(crate) async fn check_fence_sqlite(
283        &self,
284        tx: &mut sqlx::SqliteConnection,
285    ) -> Result<(), DbError> {
286        let Some(fence) = self.fence() else {
287            return Ok(());
288        };
289        let held: Option<i32> = sqlx::query_scalar(FENCE_SQLITE)
290            .bind(&fence.holder)
291            .bind(fence.epoch)
292            .fetch_optional(tx)
293            .await?;
294        held.map(|_| ()).ok_or(DbError::NotLeading)
295    }
296
297    /// The start of a write's transaction on Postgres, in one message: `BEGIN`, each
298    /// statement limited to the query limit, the transaction ended by Postgres if it stays idle
299    /// that long (a stalled client's locks released, B10), and the fence if this database is a
300    /// master's
301    /// (holding the lease's row until the write commits). Values are written into the text (a
302    /// message of several statements takes no parameters), each as a quoted literal.
303    pub(crate) fn begin_postgres(&self) -> sqlx::AssertSqlSafe<String> {
304        let limit = format!("{}ms", self.query_timeout().as_millis().max(1));
305        let fence = self.fence().map_or_else(String::new, |fence| {
306            format!(
307                " SELECT set_config('schedr.holder', {}, true), \
308                 set_config('schedr.epoch', {}, true); {FENCE_POSTGRES}",
309                literal(&fence.holder),
310                literal(&fence.epoch.to_string()),
311            )
312        });
313        // Safe: fixed text, and values only as literals quoted by `literal`.
314        // The idle limit too: a transaction whose client stalls between statements (a network
315        // partition, a frozen master) is ended by Postgres, and its locks with it, the lease's
316        // row among them; it would otherwise block a takeover for as long as the stall (B10).
317        sqlx::AssertSqlSafe(format!(
318            "BEGIN; SELECT set_config('statement_timeout', {limit}, true), \
319             set_config('idle_in_transaction_session_timeout', {limit}, true);{fence}",
320            limit = literal(&limit)
321        ))
322    }
323}
324
325/// `text` as a Postgres string literal: `E'…'` with quotes and backslashes escaped, so it
326/// reads the same whatever `standard_conforming_strings` is.
327fn literal(text: &str) -> String {
328    format!("E'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))
329}
330
331/// A period as an SQLite time modifier (`+15.000 seconds`).
332fn sqlite_period(period: Duration) -> String {
333    format!("+{:.3} seconds", period.as_secs_f64())
334}
335
336/// A period in milliseconds, for Postgres.
337fn millis(period: Duration) -> i64 {
338    i64::try_from(period.as_millis()).unwrap_or(i64::MAX)
339}