Skip to main content

core_crypto_keystore/connection/
transaction.rs

1//! This module manages the lifecycle of keystore transactions.
2//!
3//! The keystore holds the database connection for the life of the SQLite transaction. Writes
4//! run on that connection as they are issued. The keystore's [`Transaction`] wrapper can be
5//! shared across async tasks, which requires `Send` and `Sync`.
6
7use std::{ops::Deref, sync::Arc};
8
9use async_lock::MutexGuard;
10use rusqlite::Connection;
11
12use crate::{
13    CryptoKeystoreError, CryptoKeystoreResult, Database, Transaction, UniqueArc, transaction::TransactionConnection,
14    unique_arc::ArcWithReadGuard,
15};
16
17/// These impls control the keystore transaction lifecycle.
18impl Database {
19    /// Waits for the current transaction to be committed or rolled back, then starts a new one.
20    ///
21    /// With the `cross-process-lock` feature enabled, this also waits on transactions running
22    /// against the same database in other processes.
23    pub async fn new_transaction(self: &Arc<Self>) -> CryptoKeystoreResult<UniqueArc<Transaction>> {
24        let lock_guard = self.transaction_lock.acquire().await?;
25        Transaction::new(lock_guard, self.clone()).await
26    }
27
28    /// Start a new transaction if no other transaction is currently in progress.
29    ///
30    /// If a transaction is currently in progress, this will produce a `TransactionInProgress` error.
31    /// With the `cross-process-lock` feature enabled, a transaction in progress in another process
32    /// counts too.
33    pub async fn try_new_immediate_transaction(self: &Arc<Self>) -> CryptoKeystoreResult<UniqueArc<Transaction>> {
34        let lock_guard = self
35            .transaction_lock
36            .try_acquire()?
37            .ok_or(CryptoKeystoreError::TransactionInProgress)?;
38        Transaction::new(lock_guard, self.clone()).await
39    }
40
41    /// Do an operation on a new keystore transaction on this database.
42    ///
43    /// This is a convenience method abstracting over the transaction lifecycle;
44    /// it creates a new transaction (including waiting for any existing transaction to finish),
45    /// then performs its operation.
46    ///
47    /// If the operation succeeds, the transaction is committed.
48    /// Otherwise, it is rolled back.
49    pub async fn transactionally<R>(
50        self: &Arc<Self>,
51        operation: impl AsyncFnOnce(&Transaction) -> CryptoKeystoreResult<R>,
52    ) -> CryptoKeystoreResult<R> {
53        let lock_guard = self.transaction_lock.acquire().await?;
54        let transaction = Transaction::new(lock_guard, self.clone()).await?;
55
56        let result = operation(&transaction).await;
57        if result.is_ok() {
58            transaction.commit().await?;
59        } else {
60            transaction.rollback().await?;
61        }
62
63        result
64    }
65
66    /// The connection on which to perform a database operation.
67    ///
68    /// When a transaction is in flight this is tha transaction's connection.
69    /// Otherwise it is the database's internal connection.
70    ///
71    /// It is the caller's responsibility to ensure that mutating operations are only performed
72    /// via a transaction!
73    ///
74    /// The returned type is deliberately `!Send` because there is an inner lock
75    /// which is synchronous (for good reason, see field-level docs on `Transaction::conn`);
76    /// holding that lock across an await point would wedge the database.
77    pub(crate) async fn conn<'a>(&'a self) -> impl 'a + Deref<Target = Connection> {
78        #[derive(derive_more::From)]
79        enum ConnectionGuard<'a> {
80            Transaction(TransactionConnection),
81            Database(MutexGuard<'a, Connection>),
82        }
83
84        impl<'a> Deref for ConnectionGuard<'a> {
85            type Target = Connection;
86
87            fn deref(&self) -> &Self::Target {
88                match self {
89                    ConnectionGuard::Transaction(transaction_connection) => transaction_connection.deref(),
90                    ConnectionGuard::Database(mutex_guard) => mutex_guard.deref(),
91                }
92            }
93        }
94
95        if let Some(weak) = self.transaction.lock().await.clone()
96            && let Some(wrapper) = weak.upgrade_without_type_erasure().await
97            && let Ok(transaction_connection) = TransactionConnection::shared(wrapper)
98        {
99            ConnectionGuard::from(transaction_connection)
100        } else {
101            self.conn.lock().await.into()
102        }
103    }
104
105    /// Ensure a transaction exists, passing it to the operation.
106    ///
107    /// If a transaction is already in progress, perform the operation and pass on its result
108    /// without affecting the transaction lifecycle at all, whether or not the operation succeeded.
109    ///
110    /// NOTE: if the transaction was already in progress, its owner's `.commit()` will block until
111    /// the operation here has completed.
112    ///
113    /// If a transaction was _not_ already in progress, create one and then perform the operation.
114    /// If the operation succeeded, commit the transaction; otherwise, roll it back.
115    /// Then return the result.
116    ///
117    /// If the operation succeeded but the commit failed, the commit error masks the operation's
118    /// success.
119    ///
120    /// Because the operation and therefore this overall function can return an arbitrary error type,
121    /// and there is not necessarily a direct relation between [`CryptoKeystoreError`] and `E`,
122    /// this function requires an explicit mapping function to be provided.
123    ///
124    /// NOTE: Because of TOCTOU, there is an interval between when we check if an existing
125    /// transaction exists, and when we create our own. If a separate process creates a transaction
126    /// during that interval, then this function must wait for that external transaction to
127    /// complete before it can acquire the transaction lock. This might be surprising, but isn't
128    /// worth putting in the effort to change; it's not strictly a bug.
129    pub async fn ensure_transaction<T, E>(
130        self: &Arc<Self>,
131        operation: impl AsyncFnOnce(&Transaction) -> Result<T, E>,
132        map_err: impl Fn(CryptoKeystoreError) -> E,
133    ) -> Result<T, E> {
134        #[derive(derive_more::Deref, derive_more::From)]
135        enum TxHandle {
136            /// Someone else created this transaction and we have a guard over it
137            Borrowed(#[deref(forward)] ArcWithReadGuard<Transaction>),
138            /// We created this transaction and need to commit it ourselves
139            Owned(#[deref(forward)] UniqueArc<Transaction>),
140        }
141
142        // don't keep the lock alive, to prevent deadlocks
143        let weak = (*self.transaction.lock().await).clone();
144        // still waiting on `Option::async_map`, `Option::async_and_then`
145        let existing = match weak {
146            Some(weak) => weak.upgrade_without_type_erasure().await,
147            None => None,
148        };
149        let handle: TxHandle = match existing {
150            Some(existing) => existing.into(),
151            None => self.new_transaction().await.map_err(&map_err)?.into(),
152        };
153
154        let result = operation(&handle).await;
155
156        if let TxHandle::Owned(tx) = handle {
157            if result.is_ok() {
158                tx.commit().await.map_err(&map_err)?;
159            } else {
160                tx.rollback().await.map_err(&map_err)?;
161            }
162        }
163
164        result
165    }
166}