Skip to main content

schedr_db/
scope.rs

1//! Several writes in one transaction: [`Database::atomically`] runs a piece of work with every
2//! query of this database (writes and reads, so it sees its own writes) going through one
3//! transaction, committed once at its end or rolled back on an error. The master uses it for a
4//! worker message's writes and for a round's assignments: one lease check and one commit
5//! instead of one per write (see archive/PROJECT.md, "Found by the stress suite").
6//!
7//! The transaction is found through a task-local: only the work's own future uses it, never
8//! another task on the same database (the lease's renewals, a gauge refresh, an input fetch).
9
10use std::future::Future;
11use std::sync::Arc;
12
13use sqlx::pool::PoolConnection;
14use sqlx::{AssertSqlSafe, Postgres, Sqlite};
15
16use crate::database::{Database, DbError, Pool};
17
18tokio::task_local! {
19    static CURRENT: Scope;
20}
21
22/// The transaction of the work running in this task, and the database it belongs to.
23#[derive(Debug, Clone)]
24pub(crate) struct Scope {
25    database: Arc<()>,
26    pub(crate) connection: Arc<tokio::sync::Mutex<Scoped>>,
27}
28
29/// The connection holding the transaction. Dropped while still open (the work was cancelled),
30/// it is closed rather than given back to the pool in the middle of a transaction.
31#[derive(Debug)]
32pub(crate) struct Scoped {
33    pub(crate) connection: Connection,
34    open: bool,
35    /// A query of the work failed or was cut off: the transaction is void (on Postgres
36    /// aborted, its `COMMIT` a silent rollback; on SQLite partly done), even if the work
37    /// handled the error and went on.
38    pub(crate) broken: bool,
39}
40
41/// One of the two backends' pooled connections.
42#[derive(Debug)]
43pub(crate) enum Connection {
44    Sqlite(PoolConnection<Sqlite>),
45    Postgres(PoolConnection<Postgres>),
46}
47
48impl Drop for Scoped {
49    fn drop(&mut self) {
50        if self.open {
51            match &mut self.connection {
52                Connection::Sqlite(connection) => connection.close_on_drop(),
53                Connection::Postgres(connection) => connection.close_on_drop(),
54            }
55        }
56    }
57}
58
59/// The transaction of the work running in this task, if it is on `db`.
60pub(crate) fn current(db: &Database) -> Option<Scope> {
61    CURRENT
62        .try_with(Scope::clone)
63        .ok()
64        .filter(|scope| Arc::ptr_eq(&scope.database, db.identity()))
65}
66
67impl Scoped {
68    /// Runs `statement` on the connection.
69    async fn run(&mut self, statement: AssertSqlSafe<String>) -> Result<(), sqlx::Error> {
70        match &mut self.connection {
71            Connection::Sqlite(connection) => sqlx::raw_sql(statement)
72                .execute(&mut **connection)
73                .await
74                .map(drop),
75            Connection::Postgres(connection) => sqlx::raw_sql(statement)
76                .execute(&mut **connection)
77                .await
78                .map(drop),
79        }
80    }
81
82    /// Ends the transaction with `statement` (`COMMIT` or `ROLLBACK`); the connection goes back
83    /// to the pool only if that worked (else it is closed, see [`Scoped`]'s `Drop`).
84    async fn end(&mut self, statement: &str) -> Result<(), sqlx::Error> {
85        self.run(AssertSqlSafe(statement.to_owned())).await?;
86        self.open = false;
87        Ok(())
88    }
89}
90
91impl Database {
92    /// Runs `work` in one transaction of this database: every query it makes on it (writes and
93    /// reads) goes through the transaction, which commits when `work` returns `Ok` and rolls
94    /// back when it returns `Err` (then nothing of it is stored). A fenced database checks its
95    /// lease once, at the start, and on Postgres holds the lease's row until the end (see
96    /// [`Database::fenced`]). Already inside one on this database, `work` joins it.
97    ///
98    /// # Errors
99    ///
100    /// `work`'s error, or [`DbError`] if the transaction can't start or commit
101    /// ([`DbError::NotLeading`] for a master whose lease was taken over;
102    /// [`DbError::CommitUnknown`] for a commit cut off, which may have stored it).
103    pub async fn atomically<T, E>(&self, work: impl Future<Output = Result<T, E>>) -> Result<T, E>
104    where
105        E: From<DbError>,
106    {
107        if current(self).is_some() {
108            return work.await;
109        }
110        let scoped = self
111            .limited(self.query_timeout(), self.begin_scope())
112            .await?;
113        let scope = Scope {
114            database: self.identity().clone(),
115            connection: Arc::new(tokio::sync::Mutex::new(scoped)),
116        };
117        let mut result = CURRENT.scope(scope.clone(), work).await;
118        // Stored or not, the round's probe is taken again (decision 485).
119        let _wrote = Wrote(self);
120        let mut scoped = scope.connection.lock().await;
121        if result.is_ok() && scoped.broken {
122            result = Err(DbError::TransactionFailed.into());
123        }
124        // A test's commit cut off before it stored: rolled back, its answer lost (see
125        // `Database::lose_commit_unstored`).
126        #[cfg(any(test, feature = "testing"))]
127        if result.is_ok() && self.faults().commit_lost_unstored() {
128            let _ = scoped.end("ROLLBACK").await;
129            return Err(DbError::CommitUnknown.into());
130        }
131        if result.is_ok() {
132            self.limited(self.query_timeout(), async {
133                Ok(scoped.end("COMMIT").await?)
134            })
135            .await
136            .map_err(DbError::from_commit)?;
137            // A test's commit stored, its answer lost (see `Database::lose_commit_answer`).
138            #[cfg(any(test, feature = "testing"))]
139            self.faults().committed();
140            #[cfg(any(test, feature = "testing"))]
141            if self.faults().commit_answer_lost() {
142                return Err(DbError::CommitUnknown.into());
143            }
144        } else {
145            // Nothing of it is stored either way: a rollback that fails closes the connection.
146            let _ = self
147                .limited(self.query_timeout(), async {
148                    Ok(scoped.end("ROLLBACK").await?)
149                })
150                .await;
151        }
152        result
153    }
154
155    /// A connection with a transaction begun on it: on Postgres in one message with the
156    /// statement limit and the fence ([`Database::begin_postgres`]); on SQLite taking the write
157    /// lock at once (`BEGIN IMMEDIATE`), then the fence.
158    async fn begin_scope(&self) -> Result<Scoped, DbError> {
159        match self.pool() {
160            Pool::Sqlite(pool) => {
161                let mut scoped = Scoped {
162                    connection: Connection::Sqlite(pool.acquire().await?),
163                    open: true,
164                    broken: false,
165                };
166                scoped
167                    .run(AssertSqlSafe("BEGIN IMMEDIATE".to_owned()))
168                    .await?;
169                let Connection::Sqlite(connection) = &mut scoped.connection else {
170                    unreachable!("an SQLite pool gives SQLite connections")
171                };
172                self.check_fence_sqlite(connection).await?;
173                Ok(scoped)
174            }
175            Pool::Postgres(pool) => {
176                let mut scoped = Scoped {
177                    connection: Connection::Postgres(pool.acquire().await?),
178                    open: true,
179                    broken: false,
180                };
181                let begin = self.begin_postgres();
182                scoped
183                    .run(AssertSqlSafe(begin.0))
184                    .await
185                    .map_err(DbError::from_begin)?;
186                Ok(scoped)
187            }
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests;
194
195/// Counts a write transaction's end when dropped: on every return of `atomically` after the
196/// work ran, its commit or rollback included (decision 485).
197struct Wrote<'a>(&'a Database);
198
199impl Drop for Wrote<'_> {
200    fn drop(&mut self) {
201        self.0.wrote();
202    }
203}