deltachat/sql/
pool.rs

1//! # SQLite connection pool.
2//!
3//! The connection pool holds a number of SQLite connections and allows to allocate them.
4//! When allocated connection is dropped, underlying connection is returned back to the pool.
5//!
6//! The pool is organized as a stack. It always allocates the most recently used connection.
7//! Each SQLite connection has its own page cache, so allocating recently used connections
8//! improves the performance compared to, for example, organizing the pool as a queue
9//! and returning the least recently used connection each time.
10//!
11//! Pool returns at most one write connection (with `PRAGMA query_only=0`).
12//! This ensures that there never are multiple write transactions at once.
13//!
14//! Doing the locking ourselves instead of relying on SQLite has these reasons:
15//!
16//! - SQLite's locking mechanism is non-async, blocking a thread
17//! - SQLite's locking mechanism just sleeps in a loop, which is really inefficient
18//!
19//! ---
20//!
21//! More considerations on alternatives to the current approach:
22//!
23//! We use [DEFERRED](https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions) transactions.
24//!
25//! In order to never get concurrency issues, we could make all transactions IMMEDIATE,
26//! but this would mean that there can never be two simultaneous transactions.
27//!
28//! Read transactions can simply be made DEFERRED to run in parallel w/o any drawbacks.
29//!
30//! DEFERRED write transactions without doing the locking ourselves would have these drawbacks:
31//!
32//! 1. As mentioned above, SQLite's locking mechanism is non-async and sleeps in a loop.
33//! 2. If there are other write transactions, we block the db connection until
34//!    upgraded. If some reader comes then, it has to get the next, less used connection with a
35//!    worse per-connection page cache (SQLite allows one write and any number of reads in parallel).
36//! 3. If a transaction is blocked for more than `busy_timeout`, it fails with SQLITE_BUSY.
37//! 4. If upon a successful upgrade to a write transaction the db has been modified,
38//!    the transaction has to be rolled back and retried, which means extra work in terms of
39//!    CPU/battery.
40//!
41//! The only pro of making write transactions DEFERRED w/o the external locking would be some
42//! parallelism between them.
43//!
44//! Another option would be to make write transactions IMMEDIATE, also
45//! w/o the external locking. But then cons 1. - 3. above would still be valid.
46
47use std::ops::{Deref, DerefMut};
48use std::sync::{Arc, Weak};
49
50use anyhow::{Context, Result};
51use rusqlite::Connection;
52use tokio::sync::{Mutex, OwnedMutexGuard, OwnedSemaphorePermit, Semaphore};
53
54mod wal_checkpoint;
55pub(crate) use wal_checkpoint::WalCheckpointStats;
56
57/// Inner connection pool.
58#[derive(Debug)]
59struct InnerPool {
60    /// Available connections.
61    connections: parking_lot::Mutex<Vec<Connection>>,
62
63    /// Counts the number of available connections.
64    semaphore: Arc<Semaphore>,
65
66    /// Write mutex.
67    ///
68    /// This mutex ensures there is at most
69    /// one write connection with `query_only=0`.
70    ///
71    /// This mutex is locked when write connection
72    /// is outside the pool.
73    pub(crate) write_mutex: Arc<Mutex<()>>,
74}
75
76impl InnerPool {
77    /// Puts a connection into the pool.
78    ///
79    /// The connection could be new or returned back.
80    fn put(&self, connection: Connection) {
81        let mut connections = self.connections.lock();
82        connections.push(connection);
83        drop(connections);
84    }
85
86    /// Retrieves a connection from the pool.
87    ///
88    /// Sets `query_only` pragma to the provided value
89    /// to prevent accidental misuse of connection
90    /// for writing when reading is intended.
91    /// Only pass `query_only=false` if you want
92    /// to use the connection for writing.
93    pub async fn get(self: Arc<Self>, query_only: bool) -> Result<PooledConnection> {
94        if query_only {
95            let permit = self.semaphore.clone().acquire_owned().await?;
96            let conn = {
97                let mut connections = self.connections.lock();
98                connections
99                    .pop()
100                    .context("Got a permit when there are no connections in the pool")?
101            };
102            let conn = PooledConnection {
103                pool: Arc::downgrade(&self),
104                conn: Some(conn),
105                _permit: permit,
106                _write_mutex_guard: None,
107            };
108            conn.pragma_update(None, "query_only", "1")?;
109            Ok(conn)
110        } else {
111            // We get write guard first to avoid taking a permit
112            // and not using it, blocking a reader from getting a connection
113            // while being ourselves blocked by another wrtier.
114            let write_mutex_guard = Arc::clone(&self.write_mutex).lock_owned().await;
115
116            // We may still have to wait for a connection
117            // to be returned by some reader.
118            let permit = self.semaphore.clone().acquire_owned().await?;
119            let conn = {
120                let mut connections = self.connections.lock();
121                connections.pop().context(
122                    "Got a permit and write lock when there are no connections in the pool",
123                )?
124            };
125            let conn = PooledConnection {
126                pool: Arc::downgrade(&self),
127                conn: Some(conn),
128                _permit: permit,
129                _write_mutex_guard: Some(write_mutex_guard),
130            };
131            conn.pragma_update(None, "query_only", "0")?;
132            Ok(conn)
133        }
134    }
135}
136
137/// Pooled connection.
138pub struct PooledConnection {
139    /// Weak reference to the pool used to return the connection back.
140    pool: Weak<InnerPool>,
141
142    /// Only `None` right after moving the connection back to the pool.
143    conn: Option<Connection>,
144
145    /// Semaphore permit, dropped after returning the connection to the pool.
146    _permit: OwnedSemaphorePermit,
147
148    /// Write mutex guard.
149    ///
150    /// `None` for read-only connections with `PRAGMA query_only=1`.
151    _write_mutex_guard: Option<OwnedMutexGuard<()>>,
152}
153
154impl Drop for PooledConnection {
155    fn drop(&mut self) {
156        // Put the connection back unless the pool is already dropped.
157        if let Some(pool) = self.pool.upgrade()
158            && let Some(conn) = self.conn.take()
159        {
160            pool.put(conn);
161        }
162    }
163}
164
165impl Deref for PooledConnection {
166    type Target = Connection;
167
168    fn deref(&self) -> &Connection {
169        self.conn.as_ref().unwrap()
170    }
171}
172
173impl DerefMut for PooledConnection {
174    fn deref_mut(&mut self) -> &mut Connection {
175        self.conn.as_mut().unwrap()
176    }
177}
178
179/// Connection pool.
180#[derive(Clone, Debug)]
181pub struct Pool {
182    /// Reference to the actual connection pool.
183    inner: Arc<InnerPool>,
184}
185
186impl Pool {
187    /// Creates a new connection pool.
188    pub fn new(connections: Vec<Connection>) -> Self {
189        let semaphore = Arc::new(Semaphore::new(connections.len()));
190        let inner = Arc::new(InnerPool {
191            connections: parking_lot::Mutex::new(connections),
192            semaphore,
193            write_mutex: Default::default(),
194        });
195        Pool { inner }
196    }
197
198    pub async fn get(&self, query_only: bool) -> Result<PooledConnection> {
199        Arc::clone(&self.inner).get(query_only).await
200    }
201
202    /// Truncates the WAL file.
203    pub(crate) async fn wal_checkpoint(&self) -> Result<WalCheckpointStats> {
204        wal_checkpoint::wal_checkpoint(self).await
205    }
206}