1use std::ffi::OsString;
2use std::path::{Component, Path, PathBuf};
3use std::time::Duration;
4
5use tokio::sync::Semaphore;
6
7use crate::Error;
8
9#[cfg(test)]
10mod tests;
11
12const MIN_BUSY_TIMEOUT: Duration = Duration::from_millis(1);
13const MAX_BUSY_TIMEOUT: Duration = Duration::from_millis(2_147_483_647);
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct Options {
17 pub path: PathBuf,
18 pub read_connections: usize,
19 pub connection_max_idle: Duration,
20 pub busy_timeout: Duration,
21 pub journal_size_limit: i64,
22 pub checkpoint_interval: Duration,
23}
24
25impl Options {
26 pub(crate) fn validate(&self) -> Result<(), Error> {
27 let problems: Vec<String> = [
28 (!is_clean_absolute(&self.path))
29 .then(|| format!("path must be a clean absolute path: {}", self.path.display())),
30 (self.read_connections == 0 || self.read_connections > Semaphore::MAX_PERMITS).then(|| {
31 format!(
32 "read connections must be between 1 and {}: {}",
33 Semaphore::MAX_PERMITS,
34 self.read_connections
35 )
36 }),
37 self.connection_max_idle
38 .is_zero()
39 .then(|| "connection max idle time must be positive".to_owned()),
40 (!(MIN_BUSY_TIMEOUT..=MAX_BUSY_TIMEOUT).contains(&self.busy_timeout)).then(|| {
41 format!(
42 "busy timeout must be between {MIN_BUSY_TIMEOUT:?} and {MAX_BUSY_TIMEOUT:?}: {:?}",
43 self.busy_timeout
44 )
45 }),
46 (self.journal_size_limit <= 0).then(|| {
47 format!(
48 "journal size limit must be positive: {}",
49 self.journal_size_limit
50 )
51 }),
52 self.checkpoint_interval
53 .is_zero()
54 .then(|| "checkpoint interval must be positive".to_owned()),
55 ]
56 .into_iter()
57 .flatten()
58 .collect();
59 if problems.is_empty() {
60 Ok(())
61 } else {
62 Err(Error::Options(problems))
63 }
64 }
65
66 pub(crate) fn directory(&self) -> &Path {
67 self.path.parent().unwrap_or(&self.path)
68 }
69
70 pub(crate) fn sibling(&self, suffix: &str) -> PathBuf {
71 let mut path = OsString::from(self.path.as_os_str());
72 path.push(suffix);
73 PathBuf::from(path)
74 }
75}
76
77fn is_clean_absolute(path: &Path) -> bool {
78 path.is_absolute()
79 && !path
80 .components()
81 .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
82 && path.components().collect::<PathBuf>().as_os_str() == path.as_os_str()
83}