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