use std::cell::RefCell;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};
use rusqlite::Connection;
use super::capture::{Capture, Logged, Observe, in_the_file, logged, own_work};
use super::connection::{self, Role, execute, sql_error};
use super::given::own;
use super::group::{BEGIN, COMMIT, Done, Group, ROLLBACK, Work};
use super::migrate::{self, Migration};
use super::readers::Readers;
use super::{Committed, Config, Left, Settle, Settlers, Tx};
use crate::probe::FileProbe;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result};
pub(super) const TRUNCATE: &str = super::given::own!("pragma wal_checkpoint(truncate)");
const FOREIGN_KEYS_OFF: &str = own!("pragma foreign_keys = off");
const FOREIGN_KEYS_ON: &str = own!("pragma foreign_keys = on");
thread_local! {
static HELD: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };
}
pub(crate) struct File {
path: PathBuf,
writer: Arc<Mutex<Connection>>,
group: Group,
readers: Arc<Readers>,
closed: AtomicBool,
settlers: Arc<Settlers>,
capture: Logged,
copy: Arc<AtomicBool>,
config: Arc<Config>,
}
#[cfg(feature = "replication")]
pub(crate) struct Switch {
path: PathBuf,
config: Arc<Config>,
writer: Weak<Mutex<Connection>>,
capture: Weak<std::sync::RwLock<Option<Arc<Capture>>>>,
copy: Weak<AtomicBool>,
readers: Weak<Readers>,
}
impl File {
pub(crate) fn open(path: impl Into<PathBuf>, config: Config) -> Result<Self> {
Self::open_observed(path, config, None)
}
pub(crate) fn open_copy(path: impl Into<PathBuf>, config: Config) -> Result<Self> {
let file = Self::open_observed(path, Config { keep_wal: true, ..config }, None)?;
let writer = no_writer(&file.describe())?;
Ok(Self { copy: Arc::new(AtomicBool::new(true)), writer: Arc::new(Mutex::new(writer)), ..file })
}
#[cfg(feature = "replication")]
pub(crate) fn switch(&self) -> Switch {
Switch {
path: self.path.clone(),
config: Arc::clone(&self.config),
writer: Arc::downgrade(&self.writer),
capture: Arc::downgrade(&self.capture),
copy: Arc::downgrade(&self.copy),
readers: Arc::downgrade(&self.readers),
}
}
#[cfg(all(test, feature = "replication"))]
pub(crate) fn become_home(&self, observer: Arc<dyn Observe>) -> Result<()> {
self.switch().become_home(observer)
}
#[cfg(all(test, feature = "replication"))]
pub(crate) fn become_copy(&self) -> Result<()> {
self.switch().become_copy()
}
pub(crate) fn is_copy(&self) -> bool {
self.copy.load(Ordering::SeqCst)
}
pub(crate) fn open_observed(
path: impl Into<PathBuf>,
config: Config,
observer: Option<Arc<dyn Observe>>,
) -> Result<Self> {
let path = path.into();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|error| Error::io(path.display().to_string(), error))?;
}
let config = Arc::new(Config { keep_wal: config.keep_wal || observer.is_some(), ..config });
let writer = connection::open(&path, &config, Role::Writer)?;
let capture = observer
.as_ref()
.map(|observer| Capture::open(&path, &writer, Arc::clone(observer), config.memory.clone()).map(Arc::new))
.transpose()?;
let writer = Arc::new(Mutex::new(writer));
if let Some(observer) = &observer {
observer.writer(Arc::downgrade(&writer));
}
let settlers = Arc::new(Settlers::default());
let capture: Logged = Arc::new(std::sync::RwLock::new(capture));
let readers = Arc::new(Readers::new(path.clone(), Arc::clone(&config)));
if let Some(probe) = &config.probe {
probe.opened(path.clone(), Arc::downgrade(&readers));
}
Ok(Self {
group: Group::new(config.group, Arc::clone(&settlers), Arc::clone(&capture), config.probe.clone()),
readers,
writer,
path,
closed: AtomicBool::new(false),
settlers,
capture,
copy: Arc::new(AtomicBool::new(false)),
config,
})
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) fn settle_with(&self, settle: Weak<dyn Settle>) {
self.settlers.add(settle);
}
pub(crate) fn write<T, F>(&self, bytes: usize, write: F) -> Result<T>
where
F: FnOnce(&Tx<'_>) -> Result<T> + Send + 'static,
T: Send + 'static,
{
self.refuse_when_closed("a write")?;
self.refuse_inside_a_transaction("a write", "would wait for the writer the transaction holds")?;
if self.is_copy() {
return self.as_a_copy(write);
}
let (work, slot) = keeping(write);
self.group.write(&self.writer, bytes, work).map_err(|error| error.within(self.describe()))?;
taken(&slot, &self.describe())
}
pub(crate) fn submit<T, F, D>(&self, bytes: usize, write: F, done: D)
where
F: FnOnce(&Tx<'_>) -> Result<T> + Send + 'static,
T: Send + 'static,
D: FnOnce(Result<T>) + Send + 'static,
{
let refused = self.refuse_when_closed("a write").and_then(|()| {
self.refuse_inside_a_transaction("a write", "would wait for the writer the transaction holds")
});
if let Err(error) = refused {
return done(Err(error));
}
if self.is_copy() {
return done(self.as_a_copy(write));
}
let (work, slot) = keeping(write);
let describe = self.describe();
let answered: Done = Box::new(move |answer| {
done(answer.map_err(|error| error.within(&describe)).and_then(|()| taken(&slot, &describe)));
});
self.group.submit(&self.writer, bytes, work, answered);
}
pub(crate) fn transaction<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
self.refuse_when_closed("a transaction")?;
self.refuse_inside_a_transaction("a transaction", "would wait for the writer the transaction holds")?;
if self.is_copy() {
return self.as_a_copy(work);
}
let queued = self.config.probe.as_ref().and_then(FileProbe::queued);
let connection = lock(&self.writer);
let waited = queued.map(|queued| queued.elapsed());
self.transaction_on(&connection, waited, work)
}
fn as_a_copy<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
let mut outcome = None;
self.readers
.read(|connection| {
let (committed, no_settlers) = (Committed::default(), Settlers::default());
outcome = Some(work(&Tx::new(connection, &committed, &no_settlers)));
Ok(())
})
.map_err(|error| error.within(self.describe()))?;
outcome.expect("the read ran")
}
fn transaction_on<T, E: From<Error>>(
&self,
connection: &Connection,
waited: Option<Duration>,
work: impl FnOnce(&Tx<'_>) -> Result<T, E>,
) -> Result<T, E> {
self.refuse_when_unlogged()?;
execute(connection, BEGIN).map_err(|error| sql_error(format!("{}: a transaction", self.describe()), error))?;
let _held = Held::enter(self.address());
let mut open = Open { connection, finished: false };
let committed = Committed::default();
let tx = Tx::new(connection, &committed, &self.settlers);
tx.settle(Left::Before)?;
let value = work(&tx)?;
tx.settle(Left::Here)?;
open.finished = true;
let handed = self.commit(connection, waited);
if in_the_file(&handed) {
committed.run();
}
handed.map(|()| value).map_err(E::from)
}
fn commit(&self, connection: &Connection, waited: Option<Duration>) -> Result<()> {
let capture = logged(&self.capture);
if let Some(capture) = &capture {
capture.arm(!super::capture::is_own_work());
}
let started = Instant::now();
let committed = execute(connection, COMMIT);
if let (Some(probe), Some(waited), true) = (&self.config.probe, waited, committed.is_ok()) {
probe.committed(started.elapsed(), &[waited]);
}
committed.map_err(|error| {
if !connection.is_autocommit() {
let _ = execute(connection, ROLLBACK);
}
Error::new(ErrorKind::OutcomeUnknown, format!("{}: a transaction's commit", self.describe()))
.with_source(error)
})?;
match &capture {
Some(capture) => capture.committed(connection).map_err(|error| error.within(self.describe())),
None => Ok(()),
}
}
fn refuse_when_unlogged(&self) -> Result<()> {
match logged(&self.capture) {
Some(capture) => capture.refuse_a_write().map_err(|error| error.within(self.describe())),
None => Ok(()),
}
}
pub(crate) fn mark(&self) -> Result<Mark> {
self.refuse_when_closed("a transaction")?;
self.refuse_inside_a_transaction("a transaction", "would wait for the writer the transaction holds")?;
Ok(Mark(Held::enter(self.address())))
}
pub(crate) fn begin(&self, _mark: &Mark) -> Result<Begun<'_>> {
self.refuse_when_closed("a transaction")?;
if self.is_copy() {
return Err(a_copy_takes_no_transaction(&self.describe()));
}
let queued = self.config.probe.as_ref().and_then(FileProbe::queued);
let connection = lock(&self.writer);
let waited = queued.map(|queued| queued.elapsed());
self.refuse_when_unlogged()?;
execute(&connection, BEGIN).map_err(|error| sql_error(format!("{}: a transaction", self.describe()), error))?;
let begun = Begun { file: self, connection, hooks: Committed::default(), committed: false, waited };
begun.tx().settle(Left::Before)?;
Ok(begun)
}
pub(crate) fn held_here(&self) -> bool {
HELD.with(|held| held.borrow().contains(&self.address()))
}
pub(crate) fn read<T>(&self, read: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
self.refuse_when_closed("a read")?;
self.refuse_inside_a_transaction("a read", "would not see what the transaction wrote")?;
self.readers.read(read)
}
pub(crate) fn copy_into(&self, target: &Path) -> Result<()> {
self.refuse_when_closed("a copy")?;
connection::copy(&self.path, target)
}
pub(crate) fn migrate(&self, history: &str, migrations: &[Migration]) -> Result<()> {
if self.is_copy() {
return self.check_its_home_migrated(history, migrations);
}
if self.migrated(history, migrations)? {
return Ok(());
}
own_work(|| self.transaction(|tx| migrate::apply(tx, history, migrations)))
.map_err(|error| error.within(self.describe()))
}
fn migrated(&self, history: &str, migrations: &[Migration]) -> Result<bool> {
match self.read(|connection| migrate::check_applied_steps(connection, history, migrations)) {
Ok(()) => Ok(true),
Err(error) if error.kind() == ErrorKind::Unavailable => Ok(false),
Err(error) => Err(error.within(self.describe())),
}
}
fn check_its_home_migrated(&self, history: &str, migrations: &[Migration]) -> Result<()> {
self.read(|connection| migrate::check_applied_steps(connection, history, migrations))
.map_err(|error| error.within(self.describe()))
}
pub(crate) fn migrate_checked(&self, history: &str, migrations: &[Migration]) -> Result<()> {
self.refuse_when_closed("a migration")?;
self.refuse_inside_a_transaction("a migration", "would wait for the writer the transaction holds")?;
if self.is_copy() {
return self.check_its_home_migrated(history, migrations);
}
if self.migrated(history, migrations)? {
return Ok(());
}
let connection = lock(&self.writer);
let what = || format!("{}: {history}: foreign keys", self.describe());
execute(&connection, FOREIGN_KEYS_OFF).map_err(|error| sql_error(what(), error))?;
let applied = own_work(|| {
self.transaction_on(&connection, None, |tx| {
migrate::apply(tx, history, migrations)?;
migrate::check_foreign_keys(tx, history)
})
});
let restored = execute(&connection, FOREIGN_KEYS_ON).map_err(|error| sql_error(what(), error));
applied.map_err(|error| error.within(self.describe())).and(restored)
}
pub(crate) fn sweep(&self) -> usize {
let closed = self.readers.sweep();
if closed > 0 {
super::memory::give_back();
}
closed
}
#[cfg(test)]
pub(crate) fn readers_open(&self) -> usize {
self.readers.open()
}
#[cfg(test)]
pub(crate) fn readers_waiting(&self) -> usize {
self.readers.waiting()
}
#[cfg(test)]
pub(crate) fn commits(&self) -> u64 {
self.group.commits()
}
pub(crate) fn close(&self) -> Result<()> {
if self.closed.swap(true, Ordering::SeqCst) {
return Ok(());
}
self.group.close();
self.readers.close();
let connection = lock(&self.writer);
if let Some(capture) = logged(&self.capture) {
capture.close().map_err(|error| error.within(format!("{}: its log", self.describe())))?;
}
connection
.query_row(TRUNCATE, [], |_| Ok(()))
.map_err(|error| sql_error(format!("{}: its last checkpoint", self.describe()), error))
}
fn refuse_when_closed(&self, what: &str) -> Result<()> {
if self.closed.load(Ordering::SeqCst) {
return Err(Error::closed(format!("{}: {what}", self.describe())));
}
Ok(())
}
fn refuse_inside_a_transaction(&self, what: &str, why: &str) -> Result<()> {
if !self.held_here() {
return Ok(());
}
Err(Error::invalid(format!(
"{}: {what} from inside a transaction of the file {why}: make it through the transaction",
self.describe()
)))
}
fn address(&self) -> usize {
self as *const File as usize
}
fn describe(&self) -> String {
self.path.display().to_string()
}
}
pub(crate) struct Mark(
#[cfg_attr(
any(feature = "kv", feature = "jobs"),
expect(dead_code, reason = "held for its drop, which lets the thread go")
)]
Held,
);
#[cfg(feature = "replication")]
impl Switch {
pub(crate) fn is_open(&self) -> bool {
self.copy.strong_count() > 0
}
pub(crate) fn readers(&self) -> Option<Arc<Readers>> {
self.readers.upgrade()
}
pub(crate) fn become_home(&self, observer: Arc<dyn Observe>) -> Result<()> {
let (Some(held), Some(capture_cell), Some(copy)) =
(self.writer.upgrade(), self.capture.upgrade(), self.copy.upgrade())
else {
return Err(Error::closed(format!("{}: its change of home", self.path.display())));
};
let describe = self.path.display().to_string();
let config = Config { keep_wal: true, ..(*self.config).clone() };
let writer = connection::open(&self.path, &config, Role::Writer)?;
writer
.query_row(TRUNCATE, [], |_| Ok(()))
.map_err(|error| sql_error(format!("{describe}: the copy's last checkpoint"), error))?;
let capture = Capture::open(&self.path, &writer, Arc::clone(&observer), self.config.memory.clone())?;
let mut writing = lock(&held);
*writing = writer;
observer.writer(Arc::downgrade(&held));
*capture_cell.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(capture));
copy.store(false, Ordering::SeqCst);
Ok(())
}
pub(crate) fn become_copy(&self) -> Result<()> {
let (Some(held), Some(capture_cell), Some(copy)) =
(self.writer.upgrade(), self.capture.upgrade(), self.copy.upgrade())
else {
return Err(Error::closed(format!("{}: its change of home", self.path.display())));
};
let describe = self.path.display().to_string();
let mut writing = lock(&held);
if let Some(capture) = logged(&capture_cell) {
capture.close().map_err(|error| error.within(format!("{describe}: its log")))?;
}
capture_cell.write().unwrap_or_else(PoisonError::into_inner).take();
writing
.query_row(TRUNCATE, [], |_| Ok(()))
.map_err(|error| sql_error(format!("{describe}: its last checkpoint as a home"), error))?;
copy.store(true, Ordering::SeqCst);
*writing = no_writer(&describe)?;
Ok(())
}
}
fn no_writer(describe: &str) -> Result<Connection> {
let writer = Connection::open_in_memory().map_err(|error| sql_error(describe, error))?;
writer.pragma_update(None, "query_only", true).map_err(|error| sql_error(describe, error))?;
Ok(writer)
}
pub(crate) struct Begun<'f> {
file: &'f File,
connection: MutexGuard<'f, Connection>,
hooks: Committed,
committed: bool,
waited: Option<Duration>,
}
impl Begun<'_> {
pub(crate) fn file(&self) -> &File {
self.file
}
pub(crate) fn tx(&self) -> Tx<'_> {
Tx::new(&self.connection, &self.hooks, &self.file.settlers)
}
pub(crate) fn commit(mut self) -> Result<()> {
self.tx().settle(Left::Here)?;
self.committed = true;
let handed = self.file.commit(&self.connection, self.waited);
if in_the_file(&handed) {
self.hooks.run();
}
handed
}
}
fn keeping<T: Send + 'static>(
write: impl FnOnce(&Tx<'_>) -> Result<T> + Send + 'static,
) -> (Work, Arc<Mutex<Option<T>>>) {
let slot = Arc::new(Mutex::new(None));
let filled = Arc::clone(&slot);
let work: Work = Box::new(move |tx| {
let value = write(tx)?;
*lock(&filled) = Some(value);
Ok(())
});
(work, slot)
}
fn taken<T>(slot: &Mutex<Option<T>>, file: &str) -> Result<T> {
lock(slot).take().ok_or_else(|| Error::internal(format!("{file}: a write committed without its value")))
}
impl Drop for Begun<'_> {
fn drop(&mut self) {
if !self.committed && !self.connection.is_autocommit() {
let _ = execute(&self.connection, ROLLBACK);
}
}
}
pub(crate) fn a_copy_takes_no_transaction(owner: &str) -> Error {
Error::new(
ErrorKind::Unavailable,
format!("{owner}: a transaction holds its file's writer, which a copy has not: run it at the file's home"),
)
}
pub(crate) fn in_a_transaction() -> bool {
HELD.with(|held| !held.borrow().is_empty())
}
struct Held(usize);
impl Held {
fn enter(file: usize) -> Held {
HELD.with(|held| held.borrow_mut().push(file));
Held(file)
}
}
impl Drop for Held {
fn drop(&mut self) {
HELD.with(|held| {
let mut held = held.borrow_mut();
if let Some(at) = held.iter().rposition(|&file| file == self.0) {
held.remove(at);
}
});
}
}
struct Open<'a> {
connection: &'a Connection,
finished: bool,
}
impl Drop for Open<'_> {
fn drop(&mut self) {
if !self.finished && !self.connection.is_autocommit() {
let _ = execute(self.connection, ROLLBACK);
}
}
}
#[cfg(test)]
#[path = "file_tests.rs"]
mod tests;