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::thread::{self, ThreadId};
use std::time::{Duration, Instant, SystemTime};
use rusqlite::Connection;
use super::capture::{Capture, Logged, Observe, logged, own_work};
use super::checkpoint::Checkpoints;
use super::connection::{self, Role, execute, sql_error};
use super::deferred;
use super::given::own;
use super::group::{BEGIN, Done, Group, ROLLBACK, Work};
use super::migrate::{self, Migration};
use super::readers::Readers;
use super::{Committed, Config, Drafts, Left, Settle, Settlers, Tx, drafts, vacuum};
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");
#[cfg(feature = "records")]
const ZEROED: &str = own!("pragma secure_delete = on");
#[cfg(feature = "records")]
const ZEROED_IN_PLACE: &str = own!("pragma secure_delete = fast");
#[cfg(feature = "records")]
const LEFT_AS_IT_LAY: &str = own!("pragma secure_delete = off");
#[cfg(feature = "records")]
struct Zeroed<'f>(&'f File);
#[cfg(feature = "records")]
impl Drop for Zeroed<'_> {
fn drop(&mut self) {
let _ = self.0.set_on_writer(if self.0.config.zero_freed { ZEROED_IN_PLACE } else { LEFT_AS_IT_LAY });
}
}
thread_local! {
static HELD: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) };
}
pub(crate) struct File {
path: PathBuf,
writer: Arc<Mutex<Connection>>,
group: Arc<Group>,
readers: Arc<Readers>,
closed: AtomicBool,
settlers: Arc<Settlers>,
capture: Logged,
checkpoints: Arc<Checkpoints>,
copy: Arc<AtomicBool>,
config: Arc<Config>,
vacuum_failed: AtomicBool,
unneeded: Mutex<vacuum::Unneeded>,
}
#[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, incremental_vacuum: false, ..config }, None)?;
file.checkpoints.stop();
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)
}
#[cfg(feature = "blobs")]
pub(crate) fn durability(&self) -> super::Durability {
self.config.durability
}
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).map(Arc::new))
.transpose()?;
let checkpoints = Arc::new(match &capture {
Some(_) => Checkpoints::none(&path, &config),
None => Checkpoints::of(&path, &config, &writer),
});
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: Arc::new(Group::new(&config, Arc::clone(&settlers), Arc::clone(&capture), Arc::clone(&checkpoints))),
readers,
writer,
path,
closed: AtomicBool::new(false),
settlers,
capture,
checkpoints,
copy: Arc::new(AtomicBool::new(false)),
config,
vacuum_failed: AtomicBool::new(false),
unneeded: Mutex::default(),
})
}
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")?;
self.refuse_while_polled("a write")?;
if self.is_copy() {
return self.as_a_copy(write);
}
let _waiting = self.wait_for_the_writer("a 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")
})
.and_then(|()| self.refuse_in_a_point_read("a write"));
if let Err(error) = refused {
return done(Err(error));
}
if self.is_copy() {
return self.submit_as_a_copy(write, done);
}
let waiting = match self.wait_for_the_writer("a write") {
Ok(waiting) => waiting,
Err(error) => return done(Err(error)),
};
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);
drop(waiting);
}
#[cfg(feature = "async")]
#[allow(dead_code, reason = "the engines' async writes submit through it, or through aio's write")]
pub(crate) fn submit_on<T, F, D>(&self, lead: &crate::polled::Lead, bytes: usize, write: F, done: D)
where
F: FnOnce(&Tx<'_>) -> Result<T> + Send + 'static,
T: Send + 'static,
D: FnOnce(Result<T>) + Send + 'static,
{
crate::polled::leading_on(lead, || self.submit(bytes, write, done));
}
#[cfg(feature = "async")]
pub(crate) fn lead_handed(&self) {
if !self.held_here() {
self.group.lead_handed(&self.writer);
}
}
fn submit_as_a_copy<T, F, D>(&self, write: F, done: D)
where
F: FnOnce(&Tx<'_>) -> Result<T> + Send + 'static,
T: Send + 'static,
D: FnOnce(Result<T>) + Send + 'static,
{
let Some(lead) = crate::polled::lead() else {
return done(self.as_a_copy(write));
};
let (readers, describe) = (Arc::clone(&self.readers), self.describe());
lead(Box::new(move || done(on_a_copy(&readers, &describe, write))));
}
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")?;
self.refuse_while_polled("a transaction")?;
if self.is_copy() {
return self.as_a_copy(work);
}
let queued = self.config.probe.as_ref().and_then(FileProbe::queued);
let waiting = self.wait_for_the_writer("a transaction")?;
let connection = self.take_writer();
drop(waiting);
let waited = queued.map(|queued| queued.elapsed());
let outcome = self.transaction_on(&connection, waited, work);
drop(connection);
self.checkpoints.run_due();
outcome
}
fn as_a_copy<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
on_a_copy(&self.readers, &self.describe(), work)
}
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 _holding = Holding::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)?;
refuse_when_rolled_back(connection).map_err(|error| error.within(self.describe()))?;
tx.settle(Left::Here)?;
tx.settle(Left::All)?;
open.finished = true;
let handed = self.commit(connection, waited);
committed.ended(&handed);
handed.map(|()| value).map_err(E::from)
}
fn commit(&self, connection: &Connection, waited: Option<Duration>) -> Result<()> {
if let Err(broken) = deferred::kept(connection, "a transaction") {
let _ = execute(connection, ROLLBACK);
return Err(broken.within(self.describe()));
}
let capture = logged(&self.capture);
if let Some(Err(refused)) = capture.as_deref().map(Capture::refuse_a_commit) {
let _ = execute(connection, ROLLBACK);
return Err(refused.within(self.describe()));
}
match &capture {
Some(capture) => capture.arm(!super::capture::is_own_work()),
None => self.checkpoints.arm(),
}
let started = Instant::now();
let committed = connection::commit(connection);
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 => {
self.checkpoints.committed(connection);
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")?;
self.refuse_while_polled("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 waiting = self.wait_for_the_writer("a transaction")?;
let connection = self.take_writer();
drop(waiting);
let holding = Holding::enter(self.address());
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, _holding: holding, 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 give_back(&self, most: usize, now: SystemTime) -> Result<u64> {
if self.is_copy() {
return Ok(0);
}
let found = self.read(vacuum::Occupancy::read)?;
if !found.incremental {
return if found.free > 0 && self.may_vacuum(&found) { self.vacuum() } else { Ok(0) };
}
let pages = lock(&self.unneeded).note(now, found.free).min(found.free_within(most));
if pages == 0 {
return Ok(0);
}
let given = self.write(most, move |tx| vacuum::give_back(tx, pages))?;
lock(&self.unneeded).given(given);
Ok(given)
}
#[cfg(feature = "records")]
pub(crate) fn zeroing<T>(&self, work: impl FnOnce() -> Result<T>) -> Result<T> {
self.refuse_inside_a_transaction("a delete", "would wait for the writer the transaction holds")?;
self.refuse_while_polled("a delete")?;
if self.is_copy() {
return work();
}
self.set_on_writer(ZEROED)?;
let zeroed = Zeroed(self);
let done = work().and_then(|done| self.give_back_every_page().map(|()| done));
drop(zeroed);
if done.is_ok() && logged(&self.capture).is_none() {
self.empty_wal()?;
}
done
}
#[cfg(feature = "records")]
fn give_back_every_page(&self) -> Result<()> {
let found = self.read(vacuum::Occupancy::read)?;
if !found.incremental || found.free == 0 {
return Ok(());
}
let free = found.free;
let given = self.write(0, move |tx| vacuum::give_back(tx, free))?;
lock(&self.unneeded).given(given);
Ok(())
}
#[cfg(feature = "records")]
fn set_on_writer(&self, pragma: &str) -> Result<()> {
self.refuse_when_closed("a delete")?;
let waiting = self.wait_for_the_writer("a delete")?;
let writer = self.take_writer();
drop(waiting);
let set = writer.prepare_cached(pragma).and_then(|mut set| set.query_row([], |_| Ok(())));
set.map_err(|error| sql_error(format!("{}: {pragma}", self.describe()), error))
}
#[cfg(feature = "records")]
fn empty_wal(&self) -> Result<()> {
self.refuse_when_closed("a checkpoint")?;
let waiting = self.wait_for_the_writer("a checkpoint")?;
let writer = self.take_writer();
drop(waiting);
let busy = writer.query_row(TRUNCATE, [], |row| row.get::<_, i64>(0));
let busy = busy.map_err(|error| sql_error(format!("{}: a checkpoint", self.describe()), error))?;
if busy != 0 {
tracing::warn!(
target: "tinystore",
file = %self.describe(),
"a reader held the WAL past a delete: its frames go at the next checkpoint that empties it",
);
}
Ok(())
}
fn may_vacuum(&self, found: &vacuum::Occupancy) -> bool {
self.config.incremental_vacuum
&& logged(&self.capture).is_none()
&& found.in_use() <= vacuum::VACUUM_UP_TO
&& !self.vacuum_failed.load(Ordering::SeqCst)
}
fn vacuum(&self) -> Result<u64> {
self.refuse_inside_a_transaction("a vacuum", "would wait for the writer the transaction holds")?;
self.refuse_while_polled("a vacuum")?;
let waiting = self.wait_for_the_writer("a vacuum")?;
let _writing = self.take_writer();
drop(waiting);
self.refuse_when_closed("a vacuum")?;
let vacuumed = vacuum::vacuum(&self.path, self.config.busy_timeout);
if vacuumed.is_err() {
self.vacuum_failed.store(true, Ordering::SeqCst);
}
vacuumed.map_err(|error| error.within(self.describe()))
}
pub(crate) fn source(&self) -> Result<super::Source> {
self.refuse_when_closed("a snapshot")?;
let writer = (!self.is_copy()).then(|| Arc::clone(&self.writer));
Ok(super::Source { path: self.path.clone(), writer })
}
fn take_writer(&self) -> MutexGuard<'_, Connection> {
if let Some(gate) = &self.config.gate {
gate.pass();
}
lock(&self.writer)
}
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, None)? {
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], redo: Option<&str>) -> Result<bool> {
match self.read(|connection| migrate::check_applied_steps(connection, history, migrations, redo)) {
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<()> {
let check = || self.read(|connection| migrate::check_applied_steps(connection, history, migrations, None));
let checked = match (check(), &self.config.catch_up) {
(Err(missing), Some(catch_up)) if missing.kind() == ErrorKind::Unavailable => match (catch_up.0)() {
Ok(()) => check(),
Err(_) => Err(missing),
},
(checked, _) => checked,
};
checked.map_err(|error| error.within(self.describe()))
}
pub(crate) fn migrate_checked(
&self,
history: &str,
migrations: &[Migration],
drafts: Option<&Drafts>,
) -> Result<()> {
self.refuse_when_closed("a migration")?;
self.refuse_inside_a_transaction("a migration", "would wait for the writer the transaction holds")?;
self.refuse_while_polled("a migration")?;
let drafted = migrations.iter().any(|migration| migrate::is_draft(&migration.name));
if drafted && (self.is_copy() || logged(&self.capture).is_some()) {
let refused = format!("{history}: a draft in a file a node keeps, whose copies would not follow it back");
return Err(Error::invalid(refused).within(self.describe()));
}
if self.is_copy() {
return self.check_its_home_migrated(history, migrations);
}
let redo = drafts.is_some_and(|drafts| drafts.redo);
if !redo && self.migrated(history, migrations, drafts.map(|drafts| drafts.command.as_str()))? {
return Ok(());
}
let waiting = self.wait_for_the_writer("a migration")?;
let connection = self.take_writer();
drop(waiting);
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.apply_on(&connection, history, migrations, drafts));
let restored = execute(&connection, FOREIGN_KEYS_ON).map_err(|error| sql_error(what(), error));
applied.map_err(|error| error.within(self.describe())).and(restored)
}
fn apply_on(
&self,
connection: &Connection,
history: &str,
migrations: &[Migration],
drafts: Option<&Drafts>,
) -> Result<()> {
let busy = self.config.busy_timeout;
migrate::check_order(history, migrations)?;
if let Some(drafts) = drafts.filter(|drafts| drafts.redo)
&& migrate::drafts_applied(connection, history)?
{
drafts::take_back(&self.path, &drafts.copy, busy)?;
}
let compared = migrate::compare(connection, history, migrations, drafts.map(|drafts| drafts.command.as_str()))?;
let first_draft =
drafts.and_then(|_| migrations.iter().position(|migration| migrate::is_draft(&migration.name)));
let drafts_from = first_draft.unwrap_or(migrations.len()).max(compared.applied);
if compared.applied < drafts_from || !compared.shipped.is_empty() {
self.transaction_on(connection, None, |tx| {
migrate::ship(tx, history, &compared.shipped)?;
migrate::apply_steps(tx, history, &migrations[compared.applied..drafts_from])?;
migrate::check_foreign_keys(tx, history)
})?;
}
match (drafts, &migrations[drafts_from..]) {
(Some(drafts), new) if !new.is_empty() => {
if !compared.drafts_applied {
drafts::keep(&self.path, &drafts.copy, busy)?;
}
self.apply_drafts(connection, history, new, drafts)
}
(Some(drafts), _) if !compared.drafts_applied => drafts::remove(&drafts.copy),
_ => Ok(()),
}
}
fn apply_drafts(&self, connection: &Connection, history: &str, new: &[Migration], drafts: &Drafts) -> Result<()> {
self.transaction_on(connection, None, |tx| {
migrate::apply_steps(tx, history, new)?;
migrate::check_foreign_keys(tx, history)
})?;
let names: Vec<&str> = new.iter().map(|migration| &*migration.name).collect();
let (file, copy) = (self.describe(), drafts.copy.display());
tracing::warn!(target: "tinystore", "{file}: applied the drafts {}; the file before them is {copy}", names.join(", "));
Ok(())
}
pub(crate) fn sweep(&self) -> usize {
let closed = self.readers.sweep();
if closed > 0 {
super::memory::give_back();
}
closed
}
#[cfg(any(feature = "records", all(test, feature = "search"), all(test, feature = "metrics", feature = "async")))]
pub(crate) fn readers_at_most(&self) -> usize {
self.config.readers
}
#[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()
}
#[cfg(test)]
pub(crate) fn writes_waiting(&self) -> usize {
self.group.waiting()
}
#[cfg(test)]
pub(crate) fn checkpoints(&self) -> &Checkpoints {
&self.checkpoints
}
#[cfg(test)]
pub(crate) fn hold_writer(&self) -> MutexGuard<'_, Connection> {
lock(&self.writer)
}
pub(crate) fn close(&self) -> Result<()> {
if self.closed.swap(true, Ordering::SeqCst) {
return Ok(());
}
self.group.close();
self.readers.close();
self.checkpoints.stop();
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 wait_for_the_writer(&self, what: &str) -> Result<Waiting> {
if !in_a_transaction() {
return Ok(Waiting(None));
}
let (thread, file) = (thread::current().id(), self.address());
let mut waits = Waits::lock();
if waits.closes_a_ring(thread, file) {
return Err(Error::new(
ErrorKind::Unavailable,
format!(
"{}: {what} from inside a transaction would wait for the writer of a transaction that waits \
for this one: roll this one back, and run it again",
self.describe()
),
));
}
waits.waiting.push((thread, file));
Ok(Waiting(Some((thread, file))))
}
fn refuse_while_polled(&self, what: &str) -> Result<()> {
crate::polled::may_wait(|| format!("{}: {what}", self.describe()))
}
fn refuse_in_a_point_read(&self, what: &str) -> Result<()> {
if crate::polled::waits_refused() {
return Err(crate::polled::refused(|| format!("{}: {what} in a point read", 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)?;
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)
}
fn on_a_copy<T, E: From<Error>>(
readers: &Readers,
describe: &str,
work: impl FnOnce(&Tx<'_>) -> Result<T, E>,
) -> Result<T, E> {
let mut outcome = None;
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(describe))?;
outcome.expect("the read ran")
}
pub(crate) struct Begun<'f> {
file: &'f File,
_holding: Holding,
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<()> {
refuse_when_rolled_back(&self.connection).map_err(|error| error.within(self.file.describe()))?;
self.tx().settle(Left::Here)?;
self.tx().settle(Left::All)?;
self.committed = true;
let handed = self.file.commit(&self.connection, self.waited);
self.hooks.ended(&handed);
let file = self.file;
drop(self);
file.checkpoints.run_due();
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 refuse_when_rolled_back(connection: &Connection) -> Result<()> {
if !connection.is_autocommit() {
return Ok(());
}
Err(Error::invalid(
"a statement in the transaction rolled it back, as `or rollback` does: nothing of it is in the file, \
and it takes no more calls",
))
}
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);
}
});
}
}
static WAITS: Mutex<Waits> = Mutex::new(Waits { holders: Vec::new(), waiting: Vec::new() });
struct Waits {
holders: Vec<(usize, ThreadId)>,
waiting: Vec<(ThreadId, usize)>,
}
impl Waits {
fn lock() -> MutexGuard<'static, Waits> {
WAITS.lock().unwrap_or_else(PoisonError::into_inner)
}
fn closes_a_ring(&self, thread: ThreadId, file: usize) -> bool {
let mut wanted = file;
for _ in 0..=self.waiting.len() {
let Some(&(_, holder)) = self.holders.iter().find(|(held, _)| *held == wanted) else {
return false;
};
if holder == thread {
return true;
}
let Some(&(_, next)) = self.waiting.iter().find(|(waiter, _)| *waiter == holder) else {
return false;
};
wanted = next;
}
false
}
}
struct Holding(usize, ThreadId);
impl Holding {
fn enter(file: usize) -> Holding {
let thread = thread::current().id();
Waits::lock().holders.push((file, thread));
Holding(file, thread)
}
}
impl Drop for Holding {
fn drop(&mut self) {
let mut waits = Waits::lock();
if let Some(at) = waits.holders.iter().position(|&held| held == (self.0, self.1)) {
waits.holders.swap_remove(at);
}
}
}
struct Waiting(Option<(ThreadId, usize)>);
impl Drop for Waiting {
fn drop(&mut self) {
let Some(waits_for) = self.0 else { return };
let mut waits = Waits::lock();
if let Some(at) = waits.waiting.iter().rposition(|&waiting| waiting == waits_for) {
waits.waiting.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;