iris-shared-sqlitedb 0.1.0

Hardened SQLite WAL connection, migration, and transaction helpers for iris-stack
Documentation
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

use tokio::sync::Semaphore;

use crate::Error;

#[cfg(test)]
mod tests;

const MIN_BUSY_TIMEOUT: Duration = Duration::from_millis(1);
const MAX_BUSY_TIMEOUT: Duration = Duration::from_millis(2_147_483_647);

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
    pub path: PathBuf,
    pub read_connections: usize,
    pub connection_max_idle: Duration,
    pub busy_timeout: Duration,
    pub journal_size_limit: i64,
    pub checkpoint_interval: Duration,
}

impl Options {
    pub(crate) fn validate(&self) -> Result<(), Error> {
        let problems: Vec<String> = [
            (!is_clean_absolute(&self.path))
                .then(|| format!("path must be a clean absolute path: {}", self.path.display())),
            (self.read_connections == 0 || self.read_connections > Semaphore::MAX_PERMITS).then(|| {
                format!(
                    "read connections must be between 1 and {}: {}",
                    Semaphore::MAX_PERMITS,
                    self.read_connections
                )
            }),
            self.connection_max_idle
                .is_zero()
                .then(|| "connection max idle time must be positive".to_owned()),
            (!(MIN_BUSY_TIMEOUT..=MAX_BUSY_TIMEOUT).contains(&self.busy_timeout)).then(|| {
                format!(
                    "busy timeout must be between {MIN_BUSY_TIMEOUT:?} and {MAX_BUSY_TIMEOUT:?}: {:?}",
                    self.busy_timeout
                )
            }),
            (self.journal_size_limit <= 0).then(|| {
                format!(
                    "journal size limit must be positive: {}",
                    self.journal_size_limit
                )
            }),
            self.checkpoint_interval
                .is_zero()
                .then(|| "checkpoint interval must be positive".to_owned()),
        ]
        .into_iter()
        .flatten()
        .collect();
        if problems.is_empty() {
            Ok(())
        } else {
            Err(Error::Options(problems))
        }
    }

    pub(crate) fn directory(&self) -> &Path {
        self.path.parent().unwrap_or(&self.path)
    }

    pub(crate) fn sibling(&self, suffix: &str) -> PathBuf {
        let mut path = OsString::from(self.path.as_os_str());
        path.push(suffix);
        PathBuf::from(path)
    }
}

fn is_clean_absolute(path: &Path) -> bool {
    path.is_absolute()
        && !path
            .components()
            .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
        && path.components().collect::<PathBuf>().as_os_str() == path.as_os_str()
}