keyhog_core/
state_file.rs1use fs2::FileExt;
5use std::ffi::OsString;
6use std::fs::{File, OpenOptions};
7use std::io::Read;
8use std::path::{Path, PathBuf};
9
10pub struct StateFileWriteLock {
17 file: File,
18}
19
20impl StateFileWriteLock {
21 pub fn acquire(state_path: &Path) -> std::io::Result<Self> {
23 let lock_path = state_file_lock_path(state_path)?;
24 let parent = lock_path.parent().ok_or_else(|| {
25 std::io::Error::new(
26 std::io::ErrorKind::InvalidInput,
27 "state-file lock path has no parent directory",
28 )
29 })?;
30 std::fs::create_dir_all(parent)?;
31 let file = OpenOptions::new()
32 .create(true)
33 .read(true)
34 .write(true)
35 .open(lock_path)?;
36 file.lock_exclusive()?;
37 Ok(Self { file })
38 }
39}
40
41impl Drop for StateFileWriteLock {
42 fn drop(&mut self) {
43 if let Err(error) = FileExt::unlock(&self.file) {
44 tracing::warn!(%error, "failed to unlock KeyHog state file; closing the lock file will release the OS lock");
45 }
46 }
47}
48
49pub fn state_file_lock_path(state_path: &Path) -> std::io::Result<PathBuf> {
51 let Some(base_name) = state_path.file_name() else {
52 return Err(std::io::Error::new(
53 std::io::ErrorKind::InvalidInput,
54 format!("state path '{}' has no file name", state_path.display()),
55 ));
56 };
57 let mut file_name = OsString::from(base_name);
58 file_name.push(".lock");
59 Ok(state_path.with_file_name(file_name))
60}
61
62pub(crate) const CALIBRATION_CACHE_FILE_BYTES: u64 = 16 * 1024 * 1024;
67
68pub(crate) const RULE_CONFIG_FILE_BYTES: u64 = 16 * 1024 * 1024;
73
74pub(crate) const MERKLE_INDEX_CACHE_FILE_BYTES: u64 = 512 * 1024 * 1024;
80
81pub(crate) fn read_capped(path: &Path, cap: u64, kind: &str) -> std::io::Result<Vec<u8>> {
83 let file = std::fs::File::open(path)?;
84 let len = file.metadata()?.len();
85 if len > cap {
86 return Err(std::io::Error::new(
87 std::io::ErrorKind::InvalidData,
88 format!(
89 "{kind} {} exceeds {cap} byte cap; delete the cache file and rerun",
90 path.display()
91 ),
92 ));
93 }
94
95 let mut data = Vec::with_capacity(len as usize);
96 file.take(cap.saturating_add(1)).read_to_end(&mut data)?;
97 if data.len() as u64 > cap {
98 return Err(std::io::Error::new(
99 std::io::ErrorKind::InvalidData,
100 format!(
101 "{kind} {} grew past {cap} byte cap while reading; retry after the file is stable",
102 path.display()
103 ),
104 ));
105 }
106 Ok(data)
107}
108
109pub(crate) fn write_atomically(path: &Path, prefix: &str, bytes: &[u8]) -> std::io::Result<()> {
118 let parent = match path.parent().filter(|p| !p.as_os_str().is_empty()) {
119 Some(parent) => parent,
120 None => Path::new("."),
121 };
122 std::fs::create_dir_all(parent)?;
123 let mut tmp = tempfile::Builder::new()
124 .prefix(prefix)
125 .tempfile_in(parent)?;
126 std::io::Write::write_all(&mut tmp, bytes)?;
127 tmp.as_file().sync_all()?;
128 tmp.persist(path).map_err(|e| e.error)?;
129 Ok(())
130}
131
132pub(crate) fn sweep_stale_tmp_siblings(
141 cache_path: &Path,
142 prefixes: &[&str],
143 cutoff_secs: u64,
144) -> usize {
145 let Some(parent) = cache_path.parent() else {
146 return 0;
147 };
148 let Ok(entries) = std::fs::read_dir(parent) else {
149 return 0;
150 };
151 let now = std::time::SystemTime::now();
152 let mut swept = 0usize;
153 for entry in entries {
154 let entry = match entry {
155 Ok(entry) => entry,
156 Err(error) => {
159 tracing::warn!(dir = %parent.display(), %error, "skip unreadable tmp dir entry during stale-state sweep");
160 continue;
161 }
162 };
163 let name = entry.file_name();
164 let Some(name_str) = name.to_str() else {
165 continue;
166 };
167 if !prefixes.iter().any(|p| name_str.starts_with(p)) {
168 continue;
169 }
170 let path = entry.path();
171 if path == cache_path {
172 continue;
173 }
174 let Ok(meta) = path.metadata() else {
175 continue;
176 };
177 let Ok(modified) = meta.modified() else {
178 continue;
179 };
180 let Ok(age) = now.duration_since(modified) else {
182 continue;
183 };
184 if age.as_secs() < cutoff_secs {
185 continue;
186 }
187 if std::fs::remove_file(&path).is_ok() {
188 swept += 1;
189 }
190 }
191 swept
192}