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<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 if !Transaction::is_active(guard.as_ref().expect(GUARD_EXPECTATION)) {
37 return Err(CryptoKeystoreError::UnexpectedRollback);
38 }
39 Ok(Self {
40 guard,
41 _keepalive: keepalive,
42 })
43 }
44}
45
46impl Deref for TransactionConnection {
47 type Target = Connection;
48
49 fn deref(&self) -> &Connection {
50 self.guard.as_ref().expect(GUARD_EXPECTATION)
51 }
52}
53
54impl Transaction {
55 /// Guard over this transaction's connection.
56 ///
57 /// Errors if SQLite has already rolled this transaction back under us.
58 pub fn conn(&self) -> CryptoKeystoreResult<TransactionConnection> {
59 TransactionConnection::new(self.conn.lock_arc(), None)
60 }
61}
62
63impl TransactionConnection {
64 /// As [`Transaction::conn`], for callers who reached the transaction
65 /// through a weak reference and must keep it alive.
66 pub(crate) fn shared(wrapper: ArcWithReadGuard<Transaction>) -> CryptoKeystoreResult<Self> {
67 let guard = wrapper.conn.lock_arc();
68 Self::new(guard, Some(wrapper))
69 }
70}