use std::path::Path;
use std::sync::Mutex;
use std::sync::mpsc::{self, Receiver, SyncSender};
use std::thread;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use rusqlite::{Connection, ErrorCode};
pub(super) const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
pub(super) fn open_connection(path: &Path) -> Result<Connection> {
let conn = Connection::open(path)
.with_context(|| format!("opening sqlite db at {}", path.display()))?;
conn.busy_timeout(BUSY_TIMEOUT)
.context("arming busy_timeout")?;
set_wal_mode(&conn)?;
conn.pragma_update(None, "synchronous", "NORMAL")
.context("setting synchronous=NORMAL")?;
Ok(conn)
}
fn set_wal_mode(conn: &Connection) -> Result<()> {
let deadline = Instant::now() + BUSY_TIMEOUT;
loop {
match conn.pragma_update(None, "journal_mode", "WAL") {
Ok(()) => return Ok(()),
Err(err) if is_database_busy(&err) && Instant::now() < deadline => {
thread::sleep(Duration::from_millis(20));
}
Err(err) => return Err(err).context("setting journal_mode=WAL"),
}
}
}
fn is_database_busy(err: &rusqlite::Error) -> bool {
err.sqlite_error_code() == Some(ErrorCode::DatabaseBusy)
}
pub(super) fn default_pool_size() -> usize {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4)
.clamp(2, 16)
}
pub(super) struct ReaderPool {
tx: SyncSender<Connection>,
rx: Mutex<Receiver<Connection>>,
}
impl ReaderPool {
pub(super) fn open(path: &Path, size: usize) -> Result<Self> {
let (tx, rx) = mpsc::sync_channel(size);
for _ in 0..size {
let conn = open_connection(path)?;
tx.send(conn)
.expect("channel just created with capacity == size");
}
Ok(Self {
tx,
rx: Mutex::new(rx),
})
}
pub(super) fn checkout(&self) -> PooledConn<'_> {
let conn = {
let rx = self.rx.lock().unwrap();
rx.recv()
.expect("sender is held by self and outlives every checkout")
};
PooledConn {
conn: Some(conn),
tx: &self.tx,
}
}
}
pub(crate) struct PooledConn<'a> {
conn: Option<Connection>,
tx: &'a SyncSender<Connection>,
}
impl std::ops::Deref for PooledConn<'_> {
type Target = Connection;
fn deref(&self) -> &Connection {
self.conn.as_ref().expect("taken only in Drop")
}
}
impl Drop for PooledConn<'_> {
fn drop(&mut self) {
if let Some(conn) = self.conn.take() {
let _ = self.tx.try_send(conn);
}
}
}