Skip to main content

core_crypto_keystore/transaction/
mod.rs

1mod conn;
2mod fetch_from_database;
3mod finalize;
4mod mls;
5#[cfg(feature = "proteus-keystore")]
6mod proteus;
7mod savepoint;
8
9use std::sync::Arc;
10
11use async_lock::MutexGuardArc;
12use parking_lot::Mutex;
13use rusqlite::Connection;
14
15pub(crate) use self::{conn::TransactionConnection, mls::read_mls_entity};
16use crate::{CryptoKeystoreResult, Database, UniqueArc, connection::TransactionGuard, entities::InboxMessage};
17
18const GUARD_EXPECTATION: &str = "connection guard is present for the lifetime of the transaction wrapper";
19
20/// This is a guard over an in-flight transaction.
21///
22/// In a perfect world we'd be able to use [`rusqlite::Transaction`], but that type
23/// is intentionally `!Send + !Sync`, which prevents us from being able to keep a
24/// long-lived transaction around.
25///
26/// Dropping the transaction without committing performs an implicit rollback.
27///
28/// This type is always wrapped in a [`UniqueArc`], which keeps things efficient,
29/// at the cost of prohibiting `Clone`. In case you need to share this around,
30/// there are weak references available via [`UniqueArc::downgrade`].
31/// Alternately, wrap the entire thing in an `Arc<Mutex<Option<UniqueArc<Self>>>>` or similar.
32/// Just be aware that you'll need to take the unique arc out in order to commit.
33pub struct Transaction {
34    /// The lock guard is never used directly, but is held to ensure that only one transaction
35    /// is ever live simultaneously. Sqlite already gives us that protection, but we can `.await`
36    /// the transaction guard instead of just catching the error if we try to double-up.
37    _lock_guard: TransactionGuard,
38    /// The database reference is kept only to invalidate the weak pointer when this transaction
39    /// is either committed or rolled back.
40    ///
41    /// **IMPORTANT**: do not attempt to take `self.database.conn().await`. THIS WILL DEADLOCK.
42    /// Use `self.conn` instead.
43    ///
44    /// We have to hold a separate long-lived lock to the database's internal connection because
45    /// the mutex guarding it is async, but we depend on non-async `Drop` behavior.
46    database: Arc<Database>,
47    /// Guard over the actual database connection. We have to hold this for the entire lifetime
48    /// of this transaction. That's a bit selfish on one hand, because it opens the door to
49    /// potential deadlocks if we write things wrong. On the other hand it is required because
50    /// our `Drop` impl would otherwise need to asynchronously lock the database to get the connection,
51    /// and async `Drop` is not yet a thing.
52    ///
53    /// The `Option` ensures we can safely invalidate this transaction after commit and rollback.
54    /// Can't mess with the database after either of those!
55    ///
56    /// The synchronous Mutex here does a few things:
57    ///
58    /// - turns `Connection: Send + !Sync` -> `Transaction: Send + Sync`
59    /// - by using the synchronous version, the compiler ensures we don't hold a guard over an await point, which would
60    ///   deadlock everything
61    /// - ensures that no two threads race on `conn.prepare` / `prepare_cached`
62    conn: Arc<parking_lot::Mutex<Option<MutexGuardArc<rusqlite::Connection>>>>,
63    /// Whether the database detected external modifications to the connection when this transaction
64    /// was created.
65    ///
66    /// If there is only a single live connection to the database, this will never be `true`.
67    /// That can only happen if multiple connections are interleaving transactions on the DB.
68    externally_modified: bool,
69    /// The current max arrival sequence of any inbox message.
70    ///
71    /// This transaction may feel like an odd place to store this, given that an inbox message is an
72    /// entity and its arrival sequence is more like business logic than like database management.
73    ///
74    /// The argument is that the transaction is the correct place to store it because it holds an exclusive
75    /// lock over the database: while a transaction is live, no other task or process can insert new
76    /// inbox messages, except via this transaction. So storing the arrival sequence here works.
77    inbox_message_max_arrival_sequence: Mutex<u64>,
78}
79
80impl Transaction {
81    /// Instantiate a new transaction.
82    ///
83    /// Requires a transaction lock guard to ensure that only one exists at a time.
84    pub(crate) async fn new(
85        lock_guard: TransactionGuard,
86        database: Arc<Database>,
87    ) -> CryptoKeystoreResult<UniqueArc<Self>> {
88        let conn = database.raw_conn().await;
89
90        {
91            // initialize the DB-level transaction before doing any construction work on the type-level
92            // transaction; failure here invalidates everything to follow. We don't need to worry about
93            // concurrency; we already hold the lock guard.
94            let mut stmt = conn.prepare_cached("BEGIN IMMEDIATE TRANSACTION")?;
95            stmt.execute([])?;
96        }
97
98        let inbox_message_max_arrival_sequence = InboxMessage::max_arrival_sequence(&conn)?.into();
99
100        let mut transaction = Self {
101            _lock_guard: lock_guard,
102            database,
103            conn: Arc::new(parking_lot::Mutex::new(Some(conn))),
104            externally_modified: false,
105            inbox_message_max_arrival_sequence,
106        };
107        // we have to set this after initialization so that a sqlite failure when querying the pragma
108        // causes a rollback.
109        transaction.externally_modified = {
110            let conn = transaction.conn.as_ref().lock();
111            let conn = conn.as_ref().expect("mutex was just initialized with Some");
112            transaction.database.update_data_version(conn)?
113        };
114        let transaction = UniqueArc::from(transaction);
115
116        let weak = UniqueArc::downgrade(&transaction);
117
118        {
119            let mut transaction_guard = transaction.database.transaction.lock().await;
120            // this transaction guard may be `None` if the database is new or the previous transaction
121            // was committed.
122            // it may be `Some(_)` if the previous transaction was rolled back by means of dropping the
123            // `UniqueArc<Transaction>`. either way, it's correct to simply replace it without checking the
124            // previous value.
125            *transaction_guard = Some(weak);
126        }
127
128        Ok(transaction)
129    }
130
131    /// `true` when the transaction is active.
132    ///
133    /// You'd think that given the presence of this wrapper, you could assume that a transaction
134    /// is active: instantiating one creates a transaction, and the consuming methods close it.
135    /// However, Sqlite can sometimes automatically roll back transactions without telling the
136    /// user:
137    ///
138    /// <https://sqlite.org/c3ref/get_autocommit.html>
139    ///
140    /// > The only way to find out whether SQLite automatically rolled back the transaction
141    /// > after an error is to use this function.
142    fn is_active(conn: &Connection) -> bool {
143        !conn.is_autocommit()
144    }
145
146    /// Whether the database detected external modifications to the connection when this transaction
147    /// was created.
148    ///
149    /// If there is only a single live connection to the database, this will never return `true`.
150    /// That can only happen if multiple connections are interleaving transactions on the DB.
151    pub fn externally_modified(&self) -> bool {
152        self.externally_modified
153    }
154
155    /// Get the next arrival sequence number for an inbox message.
156    ///
157    /// Multiple calls will return increasing integers. It's fine if any given conversation
158    /// has gaps between messages; only the relative ordering matters.
159    ///
160    /// Not idempotent, but the u64 space is big enough that it shouldn't matter.
161    pub fn inbox_message_next_arrival_sequence(&self) -> u64 {
162        let mut guard = self.inbox_message_max_arrival_sequence.lock();
163        *guard += 1;
164        *guard
165    }
166}
167
168/// [`Transaction::externally_modified`] must report commits made through another connection to the
169/// same database, and nothing else.
170#[cfg(all(test, not(target_os = "unknown")))]
171mod external_modification_tests {
172    use std::{path::Path, sync::Arc};
173
174    use crate::{Database, DatabaseKey, entities::ConsumerData, traits::EntityDatabaseMutation as _};
175
176    /// Two handles on the same database file, each with its own connection, as two processes would
177    /// have.
178    async fn two_handles(dir: &Path) -> (Arc<Database>, Arc<Database>) {
179        let path = dir.join("keystore.db");
180        let path = path.to_str().expect("temp dir path is utf-8");
181        let key = DatabaseKey::generate();
182        (
183            Database::open(path, &key).await.unwrap(),
184            Database::open(path, &key).await.unwrap(),
185        )
186    }
187
188    /// Commit a write through `database`.
189    async fn write(database: &Arc<Database>) {
190        let transaction = database.new_transaction().await.unwrap();
191        ConsumerData::from(b"some data".to_vec()).save(&*transaction).unwrap();
192        transaction.commit().await.unwrap();
193    }
194
195    /// Start and commit an empty transaction on `database`, returning what it reported.
196    async fn externally_modified(database: &Arc<Database>) -> bool {
197        let transaction = database.new_transaction().await.unwrap();
198        let externally_modified = transaction.externally_modified();
199        transaction.commit().await.unwrap();
200        externally_modified
201    }
202
203    #[macro_rules_attribute::apply(smol_macros::test)]
204    async fn own_commits_are_not_external_modifications() {
205        let dir = tempfile::tempdir().unwrap();
206        let (database, _other) = two_handles(dir.path()).await;
207
208        // initialize the data_version state
209        externally_modified(&database).await;
210        write(&database).await;
211
212        assert!(!externally_modified(&database).await);
213    }
214
215    #[macro_rules_attribute::apply(smol_macros::test)]
216    async fn another_connections_commit_is_an_external_modification() {
217        let dir = tempfile::tempdir().unwrap();
218        let (database, other) = two_handles(dir.path()).await;
219
220        externally_modified(&database).await;
221        write(&other).await;
222
223        assert!(externally_modified(&database).await);
224    }
225
226    #[macro_rules_attribute::apply(smol_macros::test)]
227    async fn external_modification_is_reported_once() {
228        let dir = tempfile::tempdir().unwrap();
229        let (database, other) = two_handles(dir.path()).await;
230
231        externally_modified(&database).await;
232        write(&other).await;
233        externally_modified(&database).await;
234
235        assert!(!externally_modified(&database).await);
236    }
237
238    #[macro_rules_attribute::apply(smol_macros::test)]
239    async fn another_connections_rollback_is_not_an_external_modification() {
240        let dir = tempfile::tempdir().unwrap();
241        let (database, other) = two_handles(dir.path()).await;
242
243        externally_modified(&database).await;
244        let transaction = other.new_transaction().await.unwrap();
245        ConsumerData::from(b"some data".to_vec()).save(&*transaction).unwrap();
246        transaction.rollback().await.unwrap();
247
248        assert!(!externally_modified(&database).await);
249    }
250
251    #[macro_rules_attribute::apply(smol_macros::test)]
252    async fn another_connections_read_only_transaction_is_not_an_external_modification() {
253        let dir = tempfile::tempdir().unwrap();
254        let (database, other) = two_handles(dir.path()).await;
255
256        externally_modified(&database).await;
257        externally_modified(&other).await;
258
259        assert!(!externally_modified(&database).await);
260    }
261}