1use std::fs::{File, OpenOptions, TryLockError};
13use std::io::ErrorKind;
14use std::path::{Path, PathBuf};
15
16use crate::error::LinkError;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum LockMode {
21 Shared,
23 Exclusive,
25}
26
27pub fn lock_file_path<P: AsRef<Path>>(database_filename: P) -> PathBuf {
29 let path = database_filename.as_ref();
30 let mut name = path
31 .file_name()
32 .map(|n| n.to_os_string())
33 .unwrap_or_default();
34 name.push(".lock");
35 match path.parent() {
36 Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
37 _ => PathBuf::from(name),
38 }
39}
40
41pub fn unique_token() -> String {
44 use std::hash::{BuildHasher, Hasher};
45 use std::sync::atomic::{AtomicU64, Ordering};
46 static NEXT: AtomicU64 = AtomicU64::new(0);
47 #[cfg(not(target_arch = "wasm32"))]
48 let pid = std::process::id();
49 #[cfg(target_arch = "wasm32")]
50 let pid = 0u32;
51 let mut random = std::collections::hash_map::RandomState::new().build_hasher();
53 random.write_u64(NEXT.fetch_add(1, Ordering::Relaxed));
54 format!("{pid}.{:016x}", random.finish())
55}
56
57#[derive(Debug)]
63pub struct FileLock {
64 file: File,
65 path: PathBuf,
66 mode: LockMode,
67}
68
69impl FileLock {
70 pub fn acquire<P: AsRef<Path>>(lock_path: P, mode: LockMode) -> Result<Self, LinkError> {
72 let (file, path) = Self::open(lock_path, mode)?;
73 let result = match mode {
74 LockMode::Shared => file.lock_shared(),
75 LockMode::Exclusive => file.lock(),
76 };
77 result.map_err(|error| {
78 LinkError::Lock(format!("failed to lock {}: {error}", path.display()))
79 })?;
80 Ok(Self { file, path, mode })
81 }
82
83 pub fn try_acquire<P: AsRef<Path>>(
86 lock_path: P,
87 mode: LockMode,
88 ) -> Result<Option<Self>, LinkError> {
89 let (file, path) = Self::open(lock_path, mode)?;
90 let result = match mode {
91 LockMode::Shared => file.try_lock_shared(),
92 LockMode::Exclusive => file.try_lock(),
93 };
94 match result {
95 Ok(()) => Ok(Some(Self { file, path, mode })),
96 Err(TryLockError::WouldBlock) => Ok(None),
97 Err(TryLockError::Error(error)) => Err(LinkError::Lock(format!(
98 "failed to lock {}: {error}",
99 path.display()
100 ))),
101 }
102 }
103
104 pub fn path(&self) -> &Path {
106 &self.path
107 }
108
109 pub fn mode(&self) -> LockMode {
111 self.mode
112 }
113
114 fn open<P: AsRef<Path>>(lock_path: P, mode: LockMode) -> Result<(File, PathBuf), LinkError> {
115 let path = lock_path.as_ref().to_path_buf();
116 if mode == LockMode::Shared {
117 match File::open(&path) {
118 Ok(file) => {
119 if file.metadata()?.is_dir() {
120 return Err(std::io::Error::from(ErrorKind::IsADirectory).into());
121 }
122 return Ok((file, path));
123 }
124 Err(error) if error.kind() == ErrorKind::NotFound => {}
125 Err(error) => return Err(error.into()),
126 }
127 }
128 if let Some(parent) = path.parent() {
129 if !parent.as_os_str().is_empty() && !parent.exists() {
130 std::fs::create_dir_all(parent)?;
131 }
132 }
133 let file = OpenOptions::new()
134 .create(true)
135 .truncate(false)
136 .read(true)
137 .write(true)
138 .open(&path)?;
139 Ok((file, path))
140 }
141}
142
143impl Drop for FileLock {
144 fn drop(&mut self) {
145 let _ = self.file.unlock();
146 }
147}