core_crypto_keystore/transaction/conn.rs
1use std::ops::Deref;
2
3use async_lock::MutexGuardArc;
4use parking_lot::{ArcMutexGuard, RawMutex};
5use rusqlite::Connection;
6
7use super::{GUARD_EXPECTATION, Transaction};
8use crate::{CryptoKeystoreError, CryptoKeystoreResult, unique_arc::ArcWithReadGuard};
9
10/// The type of the guard we end up holding over the connection.
11type InternalGuard = ArcMutexGuard<RawMutex, Option<MutexGuardArc<rusqlite::Connection>>>;
12/// Keeps the wrapper alive for as long as this guard exists.
13///
14/// - `None` when the caller already holds a [`&Transaction`][Transaction], where borrowck provides the same guarantee.
15/// - `Some` when the caller upgraded a weak reference; this holds the reference for the duration that this connection
16/// is held, ensuring that it stays alive.
17type Keepalive = Option<ArcWithReadGuard<Transaction>>;
18
19/// A guard over the connection belonging to an in-flight transaction.
20///
21/// Derefs to the [`Connection`] on which `BEGIN IMMEDIATE` was issued, so reads through it
22/// see the transaction's uncommitted writes and writes through it join the transaction.
23///
24/// Field order is load-bearing, for the same reason as [`ArcWithReadGuard`]: `guard` must be
25/// released before `_keepalive`. Were `_keepalive` to drop first it could drop the wrapper's
26/// last strong reference, and [`Transaction::drop`] would then block trying to lock a
27/// mutex we still hold.
28pub struct TransactionConnection {
29 guard: InternalGuard,
30 _keepalive: Keepalive,
31}
32
33impl TransactionConnection {
34 /// Construct this transaction connection, checking that the transaction is in fact still alive.
35 fn new(guard: InternalGuard, keepalive: Keepalive) -> CryptoKeystoreResult<Self> {
36 let connection = Self {
37 guard,
38 _keepalive: keepalive,
39 };
40 // Construct first so field order also releases locks before the keepalive
41 // on the error path.
42 if !Transaction::is_active(&connection) {
43 return Err(CryptoKeystoreError::UnexpectedRollback);
44 }
45 Ok(connection)
46 }
47}
48
49impl Deref for TransactionConnection {
50 type Target = Connection;
51
52 fn deref(&self) -> &Connection {
53 self.guard.as_ref().expect(GUARD_EXPECTATION)
54 }
55}
56
57impl Transaction {
58 /// Guard over this transaction's connection.
59 ///
60 /// Errors if SQLite has already rolled this transaction back under us.
61 pub fn conn(&self) -> CryptoKeystoreResult<TransactionConnection> {
62 TransactionConnection::new(self.conn.lock_arc(), None)
63 }
64}
65
66impl TransactionConnection {
67 /// As [`Transaction::conn`], for callers who reached the transaction
68 /// through a weak reference and must keep it alive.
69 pub(crate) fn shared(wrapper: ArcWithReadGuard<Transaction>) -> CryptoKeystoreResult<Self> {
70 let guard = wrapper.conn.lock_arc();
71 Self::new(guard, Some(wrapper))
72 }
73}