use std::cell::Cell;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Seek, SeekFrom};
use std::os::raw::c_int;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use rusqlite::Connection;
use rusqlite::hooks::Wal;
use super::connection::sql_error;
use super::given::own;
use crate::{Error, ErrorKind, Result};
const HEADER: usize = 32;
const FRAME_HEADER: usize = 24;
pub(super) const CHECKPOINT_AT: u32 = 1000;
const CHECKPOINT: &str = own!("pragma wal_checkpoint(passive)");
const HOLD_PATIENCE: std::time::Duration = std::time::Duration::from_secs(1);
thread_local! {
static WAL_END: Cell<Option<u32>> = const { Cell::new(None) };
static ANSWERING: Cell<bool> = const { Cell::new(false) };
static OWN_WORK: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn own_work<T>(work: impl FnOnce() -> T) -> T {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
OWN_WORK.set(self.0);
}
}
let _restore = Restore(OWN_WORK.replace(true));
work()
}
pub(crate) fn is_own_work() -> bool {
OWN_WORK.get()
}
pub(crate) fn answering() -> bool {
ANSWERING.get()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Position {
pub(crate) checkpoints: u32,
pub(crate) salts: [u32; 2],
pub(crate) frame: u32,
}
impl Position {
pub(crate) fn same_generation(&self, other: &Position) -> bool {
self.checkpoints == other.checkpoints && self.salts == other.salts
}
fn followed_by(&self, next: &Position) -> bool {
*self == Position::default() || next.checkpoints == self.checkpoints.wrapping_add(1)
}
}
pub(crate) struct Commit<'a> {
pub(crate) position: Position,
pub(crate) page_size: u32,
pub(crate) size: u32,
pub(crate) pages: Vec<(u32, &'a [u8])>,
}
pub(crate) trait Observe: Send + Sync {
fn last(&self) -> Option<Position>;
fn begin(&self, position: Position, size: u32) -> Result<()>;
fn committed(&self, commit: &Commit<'_>) -> Result<()>;
fn gap(&self, position: Position) -> Result<()>;
fn sync(&self) -> Result<()>;
fn writer(&self, writer: Weak<Mutex<Connection>>) {
let _ = writer;
}
fn refuse(&self) -> Result<()> {
Ok(())
}
}
pub(crate) type Logged = Arc<std::sync::RwLock<Option<Arc<Capture>>>>;
pub(crate) fn in_the_file(outcome: &Result<()>) -> bool {
outcome.as_ref().err().is_none_or(|error| error.kind() == ErrorKind::CommittedLocally)
}
pub(crate) fn logged(cell: &Logged) -> Option<Arc<Capture>> {
cell.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
}
pub(crate) struct Capture {
observer: Arc<dyn Observe>,
wal: PathBuf,
memory: Option<Arc<crate::Memory>>,
state: Mutex<State>,
broken: AtomicBool,
}
struct State {
file: Option<fs::File>,
at: Position,
checkpointed: u32,
restart_expected: bool,
}
impl Capture {
pub(crate) fn open(
path: &Path,
writer: &Connection,
observer: Arc<dyn Observe>,
memory: Option<Arc<crate::Memory>>,
) -> Result<Capture> {
writer.wal_hook(Some(remember_the_end));
let state = State { file: None, at: Position::default(), checkpointed: 0, restart_expected: true };
let (wal, broken) = (wal_of(path), AtomicBool::new(false));
let capture = Capture { observer, wal, memory, state: Mutex::new(state), broken };
capture.recover(writer).map_err(|error| error.within(format!("{}: its WAL", path.display())))?;
Ok(capture)
}
pub(crate) fn refuse_a_write(&self) -> Result<()> {
if self.broken.load(Ordering::SeqCst) {
return Err(Error::new(
ErrorKind::Unavailable,
"a commit is in the file and not in its log: it takes writes again once opened again",
));
}
self.observer.refuse()
}
pub(crate) fn arm(&self, answering: bool) {
WAL_END.set(None);
ANSWERING.set(answering);
}
pub(crate) fn committed(&self, writer: &Connection) -> Result<()> {
let Some(end) = WAL_END.take() else {
return Ok(());
};
let handed = self.hand(end);
ANSWERING.set(false);
let broken = |error: Error| {
self.broken.store(true, Ordering::SeqCst);
Error::new(ErrorKind::OutcomeUnknown, "a commit is in the file and not in its log").with_source(error)
};
if !in_the_file(&handed) {
return handed.map_err(broken);
}
self.checkpoint_when_long(writer, end, broken)?;
handed
}
pub(crate) fn close(&self) -> Result<()> {
self.observer.sync()?;
let mut state = self.lock();
state.file = None;
state.restart_expected = true;
Ok(())
}
fn hand(&self, end: u32) -> Result<()> {
let mut state = self.lock();
let State { file, at, checkpointed, restart_expected } = &mut *state;
let wal = open_once(file, &self.wal)?;
let header = read_header(wal)?;
let mut from = at.frame + 1;
if !at.same_generation(&header.at(0)) {
if !*restart_expected && !at.followed_by(&header.at(0)) {
self.observer.gap(header.at(0))?;
}
from = 1;
*checkpointed = 0;
}
if end < from {
return Ok(());
}
let _held = self.hold(&header, from, end);
let frames = read_frames(wal, &header, from, end)?;
let commit = commit_of(&header, end, &frames)?;
let kept = self.observer.committed(&commit);
if in_the_file(&kept) {
*at = commit.position;
*restart_expected = false;
}
kept
}
fn checkpoint_when_long(&self, writer: &Connection, end: u32, broken: impl FnOnce(Error) -> Error) -> Result<()> {
if end < self.lock().checkpointed + CHECKPOINT_AT {
return Ok(());
}
self.observer.sync().map_err(broken)?;
let (busy, frames, copied): (i64, i64, i64) = writer
.query_row(CHECKPOINT, [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.map_err(|error| sql_error("a checkpoint of a commit already logged", error))?;
let mut state = self.lock();
state.checkpointed = end;
if busy == 0 && frames == copied {
state.restart_expected = true;
}
Ok(())
}
fn recover(&self, writer: &Connection) -> Result<()> {
let mut file = match fs::File::open(&self.wal) {
Ok(file) => Some(file),
Err(error) if error.kind() == io::ErrorKind::NotFound => None,
Err(error) => return Err(Error::io("read", error)),
};
let wal = match &mut file {
Some(file) => WalCommits::scan(file)?,
None => None,
};
let mut state = self.lock();
match (self.observer.last(), wal) {
(None, wal) => {
let at = wal.as_ref().map_or_else(Position::default, |wal| wal.header.at(wal.end));
let size = writer
.query_row("pragma page_count", [], |row| row.get(0))
.map_err(|error| sql_error("its pages", error))?;
self.observer.begin(at, size)?;
state.at = at;
state.restart_expected = wal.is_none();
}
(Some(last), None) => {
state.at = last;
state.restart_expected = true;
}
(Some(last), Some(wal)) => {
let from = if last.same_generation(&wal.header.at(0)) && last.frame <= wal.end {
last.frame + 1
} else {
if !last.followed_by(&wal.header.at(0)) {
self.observer.gap(wal.header.at(0))?;
}
1
};
let file = file.as_mut().expect("a WAL that holds commits is open");
for (start, end) in wal.commits_from(from) {
let _held = self.hold(&wal.header, start, end);
let frames = read_frames(file, &wal.header, start, end)?;
self.observer.committed(&commit_of(&wal.header, end, &frames)?)?;
}
state.at = wal.header.at(wal.end);
state.restart_expected = false;
}
}
self.observer.sync()
}
fn hold(&self, header: &Header, from: u32, end: u32) -> Option<crate::Reservation> {
let bytes = u64::from(end.saturating_sub(from) + 1) * header.frame_size() as u64;
self.memory.as_ref().map(|memory| memory.hold(bytes, HOLD_PATIENCE))
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
}
pub(crate) fn hook_wal(writer: &Connection) {
writer.wal_hook(Some(remember_the_end));
}
pub(crate) fn take_wal_end() -> Option<u32> {
WAL_END.take()
}
pub(crate) fn wal_at(path: &Path, frame: u32) -> Result<Position> {
let wal = wal_of(path);
let mut file = fs::File::open(&wal).map_err(|error| Error::io(wal.display().to_string(), error))?;
Ok(read_header(&mut file)?.at(frame))
}
pub(crate) fn wal_end(path: &Path) -> Result<Position> {
Ok(commits_in(path)?.map_or_else(Position::default, |wal| wal.header.at(wal.end)))
}
pub(crate) fn commits_past(path: &Path, mark: Position) -> Result<Vec<Position>> {
let Some(wal) = commits_in(path)? else {
return Ok(Vec::new());
};
let after = if mark.same_generation(&wal.header.at(0)) { mark.frame } else { 0 };
Ok(wal.commit_ends.iter().filter(|&&end| end > after).map(|&end| wal.header.at(end)).collect())
}
fn commits_in(path: &Path) -> Result<Option<WalCommits>> {
let wal = wal_of(path);
match fs::File::open(&wal) {
Ok(mut file) => WalCommits::scan(&mut file).map_err(|error| error.within(wal.display())),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(Error::io(wal.display().to_string(), error)),
}
}
fn open_once<'a>(file: &'a mut Option<fs::File>, wal: &Path) -> Result<&'a mut fs::File> {
if file.is_none() {
*file = Some(fs::File::open(wal).map_err(|error| Error::io("open", error))?);
}
Ok(file.as_mut().expect("opened just above"))
}
fn remember_the_end(_: &Wal, frames: c_int) -> rusqlite::Result<()> {
WAL_END.set(u32::try_from(frames).ok());
Ok(())
}
pub(crate) fn wal_of(path: &Path) -> PathBuf {
let mut wal = OsString::from(path.as_os_str());
wal.push("-wal");
PathBuf::from(wal)
}
struct Header {
big_endian: bool,
page_size: u32,
checkpoints: u32,
salts: [u32; 2],
checksum: [u32; 2],
}
impl Header {
fn parse(bytes: &[u8]) -> Option<Header> {
let word = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().expect("four bytes"));
if bytes.len() < HEADER || (word(0) & !1) != 0x377f_0682 {
return None;
}
let header = Header {
big_endian: word(0) & 1 == 1,
page_size: word(8),
checkpoints: word(12),
salts: [word(16), word(20)],
checksum: [word(24), word(28)],
};
let valid = header.page_size.is_power_of_two()
&& (512..=65_536).contains(&header.page_size)
&& checksum(header.big_endian, [0, 0], &bytes[..24]) == header.checksum;
valid.then_some(header)
}
fn at(&self, frame: u32) -> Position {
Position { checkpoints: self.checkpoints, salts: self.salts, frame }
}
fn frame_size(&self) -> usize {
FRAME_HEADER + self.page_size as usize
}
}
struct Frame<'a> {
page: u32,
size_after: u32,
salts: [u32; 2],
checksum: [u32; 2],
data: &'a [u8],
}
impl<'a> Frame<'a> {
fn parse(bytes: &'a [u8]) -> Frame<'a> {
let word = |at: usize| u32::from_be_bytes(bytes[at..at + 4].try_into().expect("four bytes"));
Frame {
page: word(0),
size_after: word(4),
salts: [word(8), word(12)],
checksum: [word(16), word(20)],
data: &bytes[FRAME_HEADER..],
}
}
}
struct WalCommits {
header: Header,
commit_ends: Vec<u32>,
end: u32,
}
impl WalCommits {
fn scan(wal: &mut fs::File) -> Result<Option<WalCommits>> {
let failed = |error| Error::io("read the WAL", error);
wal.seek(SeekFrom::Start(0)).map_err(failed)?;
let mut reader = io::BufReader::new(wal);
let mut head = [0; HEADER];
match reader.read_exact(&mut head) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
Err(error) => return Err(failed(error)),
}
let Some(header) = Header::parse(&head) else { return Ok(None) };
let (mut sum, mut commit_ends, mut index) = (header.checksum, Vec::new(), 0u32);
let mut frame = vec![0; header.frame_size()];
loop {
match reader.read_exact(&mut frame) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
Err(error) => return Err(failed(error)),
}
index += 1;
let parsed = Frame::parse(&frame);
sum = checksum(header.big_endian, sum, &frame[..8]);
sum = checksum(header.big_endian, sum, parsed.data);
if parsed.salts != header.salts || parsed.checksum != sum {
break;
}
if parsed.size_after != 0 {
commit_ends.push(index);
}
}
let Some(&end) = commit_ends.last() else { return Ok(None) };
Ok(Some(WalCommits { header, commit_ends, end }))
}
fn commits_from(&self, from: u32) -> impl Iterator<Item = (u32, u32)> + '_ {
let starts = std::iter::once(1).chain(self.commit_ends.iter().map(|end| end + 1));
starts.zip(self.commit_ends.iter().copied()).filter(move |&(start, _)| start >= from)
}
}
fn frame_offset(header: &Header, frame: u32) -> usize {
HEADER + (frame as usize - 1) * header.frame_size()
}
fn checksum(big_endian: bool, [mut first, mut second]: [u32; 2], bytes: &[u8]) -> [u32; 2] {
let word = |bytes: [u8; 4]| if big_endian { u32::from_be_bytes(bytes) } else { u32::from_le_bytes(bytes) };
for &[a, b, c, d, e, f, g, h] in bytes.as_chunks::<8>().0 {
first = first.wrapping_add(word([a, b, c, d])).wrapping_add(second);
second = second.wrapping_add(word([e, f, g, h])).wrapping_add(first);
}
[first, second]
}
fn read_header(wal: &mut fs::File) -> Result<Header> {
let mut bytes = [0; HEADER];
wal.seek(SeekFrom::Start(0)).and_then(|_| wal.read_exact(&mut bytes)).map_err(|error| Error::io("read", error))?;
Header::parse(&bytes).ok_or_else(|| Error::new(ErrorKind::Corrupt, "a WAL header that does not read"))
}
fn read_frames(wal: &mut fs::File, header: &Header, from: u32, end: u32) -> Result<Vec<u8>> {
let mut frames = vec![0; (end - from + 1) as usize * header.frame_size()];
wal.seek(SeekFrom::Start(frame_offset(header, from) as u64))
.and_then(|_| wal.read_exact(&mut frames))
.map_err(|error| Error::io("read", error))?;
Ok(frames)
}
fn commit_of<'a>(header: &Header, end: u32, frames: &'a [u8]) -> Result<Commit<'a>> {
let mut pages = BTreeMap::new();
let mut size = 0;
for frame in frames.chunks_exact(header.frame_size()).map(Frame::parse) {
if frame.salts != header.salts {
return Err(Error::new(ErrorKind::Corrupt, "a commit's frame is of another generation of the WAL"));
}
pages.insert(frame.page, frame.data);
size = frame.size_after;
}
if size == 0 {
return Err(Error::new(ErrorKind::Corrupt, "a commit's last frame does not end a commit"));
}
Ok(Commit { position: header.at(end), page_size: header.page_size, size, pages: pages.into_iter().collect() })
}
#[cfg(test)]
#[path = "capture_tests.rs"]
mod tests;