use crate::{apply_key_first, DbError, DbOptions, Result};
use rusqlite::backup::{Backup, StepResult};
use rusqlite::Connection;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
static COUNTER: AtomicU64 = AtomicU64::new(0);
const COPY_BUDGET_FLOOR: Duration = Duration::from_secs(120);
const COPY_BYTES_PER_SECOND: u64 = 4 * 1024 * 1024;
const COPY_BUDGET_CEILING: Duration = Duration::from_secs(6 * 60 * 60);
pub(crate) fn copy_budget(source: &Connection) -> Duration {
let bytes = source
.path()
.filter(|path| !path.is_empty())
.map_or(0, |path| sized_copy_bytes(Path::new(path)));
budget_for_bytes(bytes)
}
fn sized_copy_bytes(main: &Path) -> u64 {
["", "-wal"].iter().fold(0u64, |total, suffix| {
let mut name = main.as_os_str().to_os_string();
name.push(suffix);
let len = std::fs::metadata(PathBuf::from(name)).map_or(0, |meta| meta.len());
total.saturating_add(len)
})
}
fn budget_for_bytes(bytes: u64) -> Duration {
COPY_BUDGET_FLOOR
.saturating_add(Duration::from_secs(bytes / COPY_BYTES_PER_SECOND))
.min(COPY_BUDGET_CEILING)
}
fn busy_wait_left(
busy_since: &mut Option<Instant>,
now: Instant,
limit: Duration,
) -> std::result::Result<Duration, Duration> {
let waited = now.saturating_duration_since(*busy_since.get_or_insert(now));
if waited >= limit {
Err(waited)
} else {
Ok(limit.saturating_sub(waited))
}
}
pub trait BackupProgress {
fn step(&mut self, remaining: i32) -> bool;
}
pub fn online_backup_to(
options: &DbOptions,
source: &Connection,
target: &Path,
progress: Option<&mut dyn BackupProgress>,
) -> Result<()> {
backup_within(options, source, target, options.busy_timeout, progress)
}
pub(crate) fn online_backup_sized(
options: &DbOptions,
source: &Connection,
target: &Path,
progress: Option<&mut dyn BackupProgress>,
) -> Result<()> {
let budget = copy_budget(source).max(options.busy_timeout);
backup_within(options, source, target, budget, progress)
}
fn backup_within(
options: &DbOptions,
source: &Connection,
target: &Path,
budget: Duration,
mut progress: Option<&mut dyn BackupProgress>,
) -> Result<()> {
let started = Instant::now();
let deadline = started.checked_add(budget).unwrap_or(started);
let clock = || -> Instant {
{
Instant::now()
}
};
let check_deadline = || -> Result<()> {
let now = clock();
if now >= deadline {
Err(DbError::Backup(format!(
"backup operation timeout expired after {:?} (budget {:?})",
now.saturating_duration_since(started),
budget
)))
} else {
Ok(())
}
};
let mut busy_since: Option<Instant> = None;
let key = options.key_pragma_value()?;
check_deadline()?;
let (temp, created) = create_private_staging(target)?;
let result = (|| -> Result<()> {
if let Some(want) = created {
match rightkit_fs::transient::retry_transient_fs(|| {
rightkit_fs::FileKey::of_path(&temp)
}) {
Ok(now) if now == want => {}
Ok(_) => {
return Err(DbError::Backup(
"backup staging was replaced before it was opened".into(),
))
}
Err(error) => {
return Err(DbError::Backup(format!(
"backup staging could not be identified before it was opened: {error}"
)))
}
}
}
let mut dst = Connection::open(&temp)?;
dst.busy_timeout(Duration::ZERO)?;
apply_key_first(&dst, key.as_ref().map(|k| k.as_str()))?;
{
let backup = Backup::new(source, &mut dst)?;
loop {
check_deadline()?;
let step = backup.step(512)?;
check_deadline()?;
if let Some(sink) = progress.as_deref_mut() {
if !sink.step(backup.progress().remaining) {
return Err(DbError::Backup("cancelled".into()));
}
}
check_deadline()?;
match step {
StepResult::Done => break,
StepResult::More => busy_since = None,
_ => {
let now = clock();
let left = busy_wait_left(&mut busy_since, now, options.busy_timeout)
.map_err(|waited| {
DbError::Backup(format!(
"backup busy timeout expired after {waited:?} (busy wait {:?})",
options.busy_timeout
))
})?;
let remaining = left.min(deadline.saturating_duration_since(now));
if remaining.is_zero() {
check_deadline()?;
return Err(DbError::Backup(format!(
"backup stopped waiting for a busy source at the operation \
deadline (budget {budget:?})"
)));
}
let pause = remaining.min(Duration::from_millis(25));
std::thread::sleep(pause);
}
}
}
}
check_deadline()?;
let _ = dst.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()));
dst.query_row("PRAGMA journal_mode=DELETE", [], |row| {
row.get::<_, String>(0)
})?;
let report: String = dst.query_row("PRAGMA quick_check", [], |row| row.get(0))?;
if !report.trim().eq_ignore_ascii_case("ok") {
return Err(DbError::Backup(format!(
"quick_check on the backup said: {report}"
)));
}
drop(dst);
rightkit_fs::restrict_owner_only(&temp)?;
let mut synced_before = false;
rightkit_fs::transient::retry_transient(|| {
if std::mem::replace(&mut synced_before, true) {
staging_still_ours(&temp, created)?;
}
std::fs::OpenOptions::new()
.write(true)
.open(&temp)
.and_then(|f| f.sync_all())
})
.map_err(|e| DbError::Backup(format!("fsync backup: {e}")))?;
check_deadline()?;
let mut published_before = false;
rightkit_fs::transient::retry_transient(|| {
if std::mem::replace(&mut published_before, true) {
staging_still_ours(&temp, created)?;
}
std::fs::rename(&temp, target)
})
.map_err(|e| DbError::Backup(format!("publish backup: {e}")))?;
if let Some(parent) = target.parent().filter(|p| !p.as_os_str().is_empty()) {
rightkit_fs::atomic::sync_dir(parent);
}
Ok(())
})();
if result.is_err() {
remove_owned_staging(&temp, created);
}
result
}
fn create_private_staging(target: &Path) -> Result<(PathBuf, Option<rightkit_fs::FileKey>)> {
for _ in 0..32 {
let temp = temp_path(target)?;
match rightkit_fs::create_private_new(&temp) {
Ok(file) => {
let key = rightkit_fs::FileKey::of_file(&file, &temp).ok();
drop(file);
return Ok((temp, key));
}
Err(error) if error.kind() == Some(std::io::ErrorKind::AlreadyExists) => {}
Err(error) => return Err(error.into()),
}
}
Err(DbError::Backup(
"could not create a unique backup staging file".into(),
))
}
fn staging_still_ours(temp: &Path, created: Option<rightkit_fs::FileKey>) -> std::io::Result<()> {
if let (Some(want), Ok(now)) = (created, rightkit_fs::FileKey::of_path(temp)) {
if now != want {
return Err(std::io::Error::other(
"backup staging was replaced while a publish step was retried",
));
}
}
Ok(())
}
fn remove_owned_staging(temp: &Path, created: Option<rightkit_fs::FileKey>) {
if let Some(want) = created {
match rightkit_fs::FileKey::of_path(temp) {
Ok(now) if now != want => return,
_ => {}
}
}
remove_with_sidecars(temp);
}
pub fn restore_from(
options: &DbOptions,
destination: &mut Connection,
backup_path: &Path,
) -> Result<()> {
let source = validated_backup(options, backup_path)?;
restore_validated(options, &source, destination)
}
impl DbOptions {
pub fn restore_from(&self, backup_path: impl AsRef<Path>) -> Result<()> {
let source = validated_backup(self, backup_path.as_ref())?;
let mut destination = self.open_existing_writer()?;
restore_validated(self, &source, &mut destination)
}
}
pub(crate) fn validated_backup(options: &DbOptions, path: &Path) -> Result<Connection> {
let source = options.open_existing_at(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
source.execute_batch("BEGIN;")?;
let messages = {
let mut statement = source.prepare("PRAGMA integrity_check")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.collect::<rusqlite::Result<Vec<_>>>()?
};
if messages.is_empty()
|| messages
.iter()
.any(|message| !message.trim().eq_ignore_ascii_case("ok"))
{
return Err(DbError::Integrity(messages.join("; ")));
}
Ok(source)
}
fn restore_validated(
options: &DbOptions,
source: &Connection,
destination: &mut Connection,
) -> Result<()> {
let backup = Backup::new(source, destination)?;
let mut busy_since: Option<Instant> = None;
loop {
match backup.step(512)? {
StepResult::Done => return Ok(()),
StepResult::More => busy_since = None,
StepResult::Busy | StepResult::Locked => {
let left = busy_wait_left(&mut busy_since, Instant::now(), options.busy_timeout)
.map_err(|waited| {
DbError::Backup(format!(
"restore busy timeout expired after {waited:?} (busy wait {:?})",
options.busy_timeout
))
})?;
std::thread::sleep(left.min(Duration::from_millis(25)));
}
_ => return Err(DbError::Backup("unexpected restore step result".into())),
}
}
}
fn temp_path(target: &Path) -> Result<PathBuf> {
let name = target
.file_name()
.ok_or(DbError::InvalidDatabasePath)?
.to_string_lossy();
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
Ok(target.with_file_name(format!(
".{name}{}{}-{n}",
rightkit_fs::atomic::TEMP_MARKER,
std::process::id()
)))
}
fn remove_with_sidecars(path: &Path) {
let _ = remove_database_files(path);
}
pub fn remove_database_files(path: &Path) -> std::io::Result<()> {
let mut first_error = None;
let mut remove = |p: &Path| {
if let Err(e) = std::fs::remove_file(p) {
if e.kind() != std::io::ErrorKind::NotFound && first_error.is_none() {
first_error = Some(e);
}
}
};
remove(path);
for suffix in ["-wal", "-shm", "-journal"] {
let mut name = path.as_os_str().to_os_string();
name.push(suffix);
remove(&PathBuf::from(name));
}
first_error.map_or(Ok(()), Err)
}
pub fn store_lock_path(db_path: &Path) -> PathBuf {
let mut name = db_path.as_os_str().to_os_string();
name.push(".store-lock");
PathBuf::from(name)
}
#[derive(Debug)]
pub struct StoreLock {
lock: rightkit_fs::FileLock,
}
impl StoreLock {
pub fn shared(db_path: &Path, options: &rightkit_fs::LockOptions) -> Result<Self> {
let lock = rightkit_fs::FileLock::acquire_shared(&store_lock_path(db_path), options)?;
Ok(Self { lock })
}
pub fn exclusive(db_path: &Path, options: &rightkit_fs::LockOptions) -> Result<Self> {
let lock = rightkit_fs::FileLock::acquire(&store_lock_path(db_path), options)?;
Ok(Self { lock })
}
pub fn path(&self) -> &Path {
self.lock.path()
}
}
pub fn replace_database(
options: &DbOptions,
replacement: &Path,
lock: &rightkit_fs::LockOptions,
) -> Result<()> {
let _guard = StoreLock::exclusive(&options.path, lock)?;
replace_database_locked(options, replacement)
}
pub fn replace_database_locked(options: &DbOptions, replacement: &Path) -> Result<()> {
let target = options.path.as_path();
let source = validated_backup(options, replacement)?;
let staging = temp_path(target)?;
let staged = (|| -> Result<()> {
online_backup_sized(options, &source, &staging, None)?;
drop(source);
remove_database_files_except_main(target)
.map_err(|e| DbError::Backup(format!("clear live sidecars: {e}")))?;
std::fs::rename(&staging, target)
.map_err(|e| DbError::Backup(format!("publish replacement: {e}")))?;
if let Some(parent) = target.parent().filter(|p| !p.as_os_str().is_empty()) {
rightkit_fs::atomic::sync_dir(parent);
}
Ok(())
})();
if staged.is_err() {
let _ = std::fs::remove_file(&staging);
}
staged
}
fn remove_database_files_except_main(path: &Path) -> std::io::Result<()> {
let mut first_error = None;
for suffix in ["-wal", "-shm", "-journal"] {
let mut name = path.as_os_str().to_os_string();
name.push(suffix);
if let Err(e) = std::fs::remove_file(PathBuf::from(name)) {
if e.kind() != std::io::ErrorKind::NotFound && first_error.is_none() {
first_error = Some(e);
}
}
}
first_error.map_or(Ok(()), Err)
}