use std::collections::VecDeque;
use std::fs::{self, OpenOptions};
use std::io::{self, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, PoisonError};
use sha2::{Digest, Sha256};
use super::entry::{Entry, Kind, Point};
use super::log::Log;
use crate::sqlite::{Applier, Durability, Observe, Position as WalEnd};
use crate::store::WeakStore;
use crate::{Error, ErrorKind, Result, Store};
pub(crate) const MARK: &str = "copy";
pub(crate) struct Copy {
name: String,
path: PathBuf,
store: WeakStore,
applier: Applier,
position: Mutex<Position>,
log: Log,
unnamed: Mutex<VecDeque<Unnamed>>,
}
pub(crate) struct Unnamed {
end: WalEnd,
sum: [u8; 32],
}
fn pages_sum(page_size: u32, size: u32, pages: &[(u32, &[u8])]) -> [u8; 32] {
let mut sum = Sha256::new();
sum.update(page_size.to_le_bytes());
sum.update(size.to_le_bytes());
for &(number, page) in pages {
sum.update(number.to_le_bytes());
if number == 1 && page.len() >= 96 {
let mut first = page.to_vec();
first[24..28].fill(0);
first[92..96].fill(0);
sum.update(&first);
} else {
sum.update(page);
}
}
sum.finalize().into()
}
pub(crate) struct Position {
point: Point,
wal: WalEnd,
kept: fs::File,
path: PathBuf,
}
impl Copy {
#[cfg(test)]
pub(crate) fn start(store: &Store, name: &str) -> Result<Copy> {
let what = || format!("copy {name}");
let dir = store.log_of(name).map_err(|error| error.within(what()))?;
if !dir.join(MARK).exists() {
if store.dir().join(name).exists() {
return Err(Error::invalid(
"the store holds its own file of that name: a copy takes its place only from a snapshot of its home",
)
.within(what()));
}
mark(&dir).map_err(|error| error.within(what()))?;
}
Self::open(store, name)
}
pub(crate) fn open(store: &Store, name: &str) -> Result<Copy> {
let what = || format!("copy {name}");
let dir = store.log_of(name).map_err(|error| error.within(what()))?;
let path = store.dir().join(name);
let mut position = Position::read(dir.join(Position::FILE)).map_err(|error| error.within(what()))?;
let unnamed = position.settle(&path, &dir).map_err(|error| error.within(what()))?;
let log = Log::open(dir, store.node_bounds(), store.node_notify()).map_err(|e| e.within(what()))?;
Ok(Copy {
name: name.to_owned(),
applier: Applier::new(&path, Durability::Full),
path,
store: store.downgrade(),
position: Mutex::new(position),
log,
unnamed: Mutex::new(unnamed),
})
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) fn holding<T>(&self, read: impl FnOnce(Point) -> Result<T>) -> Result<T> {
let position = self.lock();
read(position.point)
}
pub(crate) fn applied(&self) -> u64 {
self.lock().point.sequence
}
pub(crate) fn point(&self) -> Point {
self.lock().point
}
pub(crate) fn apply(&self, entry: &Entry<'_>, bytes: Option<&[u8]>) -> Result<()> {
let mut position = self.lock();
if !position.takes(entry).map_err(|error| error.within(format!("copy {}", self.name)))? {
return Ok(());
}
let wal = match entry.kind {
Kind::Commit => self.commit(entry, &position)?,
Kind::Begin if entry.sequence == 1 && entry.size <= 1 => position.wal,
Kind::Begin | Kind::Gap => {
return Err(Error::new(
ErrorKind::Conflict,
format!(
"copy {}: its home's log starts again at entry {}: the copy starts again from a snapshot",
self.name, entry.sequence
),
));
}
};
if let Some(bytes) = bytes {
self.log.keep(entry, bytes).map_err(|error| error.within(format!("copy {}", self.name)))?;
}
position.keep(entry.point(), wal).map_err(|error| error.within(format!("copy {}", self.name)))?;
if self.applier.is_long() {
self.sync(&mut position).map_err(|error| error.within(format!("copy {}", self.name)))?;
self.applier.checkpoint()?;
}
drop(position);
if let Some(store) = self.store.upgrade() {
store.applied(&self.name);
}
Ok(())
}
fn commit(&self, entry: &Entry<'_>, position: &Position) -> Result<WalEnd> {
let mut unnamed = self.unnamed.lock().unwrap_or_else(PoisonError::into_inner);
let Some(next) = unnamed.front() else {
return self.applier.apply(entry.page_size, entry.size, &entry.pages);
};
if entry.epoch != position.point.epoch {
return Err(Position::conflict(format!(
"copy {}: its file holds {} commits of epoch {} past its position, and entry {} is of epoch {}: it \
starts again from a snapshot",
self.name,
unnamed.len(),
position.point.epoch,
entry.sequence,
entry.epoch
)));
}
if next.sum != pages_sum(entry.page_size, entry.size, &entry.pages) {
return Err(Position::conflict(format!(
"copy {}: the commit its file holds past its position is not entry {}, which its home made again \
after the same entry: it starts again from a snapshot",
self.name, entry.sequence
)));
}
Ok(unnamed.pop_front().expect("one is left").end)
}
fn sync(&self, position: &mut Position) -> Result<()> {
self.log.sync()?;
position.sync()
}
fn lock(&self) -> MutexGuard<'_, Position> {
self.position.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(test)]
#[allow(dead_code, reason = "the copy tests call them, and they build only with every engine")]
impl Copy {
pub(crate) fn commit_and_die(&self, entry: &Entry<'_>) -> Result<()> {
self.applier.apply(entry.page_size, entry.size, &entry.pages).map(drop)
}
pub(crate) fn unnamed(&self) -> u64 {
self.unnamed.lock().unwrap_or_else(PoisonError::into_inner).len() as u64
}
pub(crate) fn log_unsynced(&self) -> bool {
self.log.unsynced()
}
}
impl Drop for Copy {
fn drop(&mut self) {
let _ = self.sync(&mut self.lock());
self.applier.close();
}
}
pub(crate) fn is_copy(log: &Path) -> bool {
log.join(MARK).exists()
}
pub(crate) fn is_ready(log: &Path, file: &Path) -> bool {
is_copy(log) && file.exists() && fs::metadata(log.join(Position::FILE)).is_ok_and(|kept| kept.len() > 0)
}
pub(crate) fn mark(dir: &Path) -> Result<()> {
fs::create_dir_all(dir).map_err(|error| io_error(dir, error))?;
fs::write(dir.join(MARK), b"").map_err(|error| io_error(dir, error))?;
crate::durable::sync_directory(dir).map_err(|error| io_error(dir, error))
}
impl Position {
pub(crate) const FILE: &str = "applied";
const NAMED: usize = 8 + 8 + 16 + 16;
const BYTES: usize = Self::NAMED + 4;
pub(crate) fn point(&self) -> Point {
self.point
}
pub(crate) fn read(path: PathBuf) -> Result<Position> {
let kept = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path);
let kept = kept.map_err(|error| io_error(&path, error))?;
let (point, wal) = Self::read_kept(&path)?.unwrap_or_default();
Ok(Position { point, wal, kept, path })
}
pub(crate) fn settle(&mut self, file: &Path, log: &Path) -> Result<VecDeque<Unnamed>> {
let mut past = VecDeque::new();
crate::sqlite::each_commit_past(file, self.wal, |commit| {
let sum = pages_sum(commit.page_size, commit.size, &commit.pages);
past.push_back(Unnamed { end: commit.position, sum });
})?;
if let Some(last) = Log::last_in(log)?.filter(|last| last.sequence > self.point.sequence) {
let mut commits = 0;
Log::read(log, |entry| {
commits += usize::from(entry.sequence > self.point.sequence && entry.kind == Kind::Commit);
Ok(())
})?;
if commits > past.len() {
return Err(Self::corrupt(
"its log names commits its file does not hold: it starts again from a snapshot",
));
}
let wal = past.drain(..commits).next_back().map_or(self.wal, |named| named.end);
self.keep_durably_at(last, wal)?;
}
if !past.is_empty() {
tracing::warn!(
target: "tinystore",
file = %file.display(),
commits = past.len(),
"a copy holds commits its position does not name, as a crash left it: it names them as they come again"
);
}
Ok(past)
}
pub(crate) fn read_point(path: &Path) -> Result<Option<Point>> {
Ok(Self::read_kept(path)?.map(|(point, _)| point))
}
fn read_kept(path: &Path) -> Result<Option<(Point, WalEnd)>> {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(io_error(path, error)),
};
if bytes.is_empty() {
return Ok(None);
}
let named = Self::NAMED;
let sum_holds = bytes.len() == Self::BYTES && bytes[named..] == Self::checksum(&bytes[..named]).to_le_bytes();
if !sum_holds {
return Err(Self::corrupt("its position does not read: the copy starts again from a snapshot"));
}
let word = |at: usize| u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"));
let point = Point {
sequence: u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")),
epoch: u64::from_le_bytes(bytes[8..16].try_into().expect("eight bytes")),
check: bytes[16..32].try_into().expect("sixteen bytes"),
};
let wal = WalEnd { checkpoints: word(32), salts: [word(36), word(40)], frame: word(44) };
Ok(Some((point, wal)))
}
fn takes(&self, entry: &Entry<'_>) -> Result<bool> {
let point = &self.point;
if entry.sequence <= point.sequence {
if entry.sequence == point.sequence && entry.check != point.check {
return Err(Self::conflict(format!(
"entry {} is not the one it applied: another home wrote it",
entry.sequence
)));
}
return Ok(false);
}
if entry.sequence > point.sequence + 1 {
return Err(Error::invalid(format!(
"entry {} follows {}: the entries between are missing",
entry.sequence, point.sequence
)));
}
if !entry.follows(point) {
return Err(Self::conflict(format!(
"entry {} does not follow the one it applied: another home wrote it",
entry.sequence
)));
}
Ok(true)
}
pub(crate) fn keep(&mut self, point: Point, wal: WalEnd) -> Result<()> {
let mut bytes = Vec::with_capacity(Self::BYTES);
bytes.extend_from_slice(&point.sequence.to_le_bytes());
bytes.extend_from_slice(&point.epoch.to_le_bytes());
bytes.extend_from_slice(&point.check);
for word in [wal.checkpoints, wal.salts[0], wal.salts[1], wal.frame] {
bytes.extend_from_slice(&word.to_le_bytes());
}
bytes.extend_from_slice(&Self::checksum(&bytes).to_le_bytes());
self.kept
.seek(SeekFrom::Start(0))
.and_then(|_| self.kept.write_all(&bytes))
.map_err(|e| io_error(&self.path, e))?;
(self.point, self.wal) = (point, wal);
Ok(())
}
pub(crate) fn sync(&mut self) -> Result<()> {
self.kept.sync_data().map_err(|error| io_error(&self.path, error))
}
pub(crate) fn keep_durably(&mut self, point: Point) -> Result<()> {
self.keep_durably_at(point, WalEnd::default())
}
pub(crate) fn keep_durably_at(&mut self, point: Point, wal: WalEnd) -> Result<()> {
self.keep(point, wal)?;
self.sync()
}
fn checksum(bytes: &[u8]) -> u32 {
let digest = Sha256::digest(bytes);
u32::from_le_bytes(digest[..4].try_into().expect("four bytes"))
}
fn conflict(what: String) -> Error {
Error::new(ErrorKind::Conflict, what)
}
fn corrupt(what: &str) -> Error {
Error::new(ErrorKind::Corrupt, what)
}
}
pub(crate) fn io_error(path: &Path, error: io::Error) -> Error {
Error::io(path.display().to_string(), error)
}
pub(crate) fn remove_if_there(path: &Path) -> Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(io_error(path, error)),
}
}