1use std::collections::{BTreeMap, HashMap, HashSet};
28use std::ffi::OsStr;
29use std::path::{Path, PathBuf};
30use std::sync::{Mutex, OnceLock, RwLock};
31
32const RETAINED_HAZARDS: usize = 64;
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub struct FileIdentity {
41 device: u64,
42 inode: u64,
43}
44
45impl std::fmt::Display for FileIdentity {
46 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(formatter, "dev={}/ino={}", self.device, self.inode)
48 }
49}
50
51pub fn identity_of(path: &Path) -> Option<FileIdentity> {
56 #[cfg(any(test, feature = "test-support"))]
57 stat_probe::record(path);
58 native_identity(crate::file_identity::metadata(path).ok()?.1)
59}
60
61fn native_identity(identity: crate::file_identity::FileIdentity) -> Option<FileIdentity> {
62 match identity {
63 crate::file_identity::FileIdentity::Known { volume, index } => Some(FileIdentity {
64 device: volume,
65 inode: index,
66 }),
67 crate::file_identity::FileIdentity::Unavailable => None,
68 }
69}
70
71#[rustfmt::skip]
72test_support_visibility! {
73
74fn metadata_identity(metadata: &std::fs::Metadata) -> Option<FileIdentity> {
75 #[cfg(unix)]
76 {
77 use std::os::unix::fs::MetadataExt;
78 Some(FileIdentity {
79 device: metadata.dev(),
80 inode: metadata.ino(),
81 })
82 }
83 #[cfg(not(unix))]
84 {
85 let _ = metadata;
86 None
87 }
88}
89}
90
91#[rustfmt::skip]
92test_support_visibility! {
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
97struct LiveFileIdentity {
98 #[cfg(any(test, feature = "test-support"))]
99 pub file: FileIdentity,
100 #[cfg(not(any(test, feature = "test-support")))]
101 file: FileIdentity,
102 #[cfg(any(test, feature = "test-support"))]
103 pub created: Option<std::time::SystemTime>,
104 #[cfg(not(any(test, feature = "test-support")))]
105 created: Option<std::time::SystemTime>,
106}
107}
108
109impl LiveFileIdentity {
110 fn from_metadata(metadata: &std::fs::Metadata) -> Option<Self> {
111 Some(Self {
112 file: metadata_identity(metadata)?,
113 created: metadata.created().ok(),
115 })
116 }
117
118 fn of(path: &Path) -> Option<Self> {
119 #[cfg(any(test, feature = "test-support"))]
120 stat_probe::record_followed(path);
121 let (metadata, identity) = crate::file_identity::metadata(path).ok()?;
122 Some(Self {
123 file: native_identity(identity)?,
124 created: metadata.created().ok(),
125 })
126 }
127}
128
129pub(crate) fn candidate_metadata(path: &Path) -> std::io::Result<std::fs::Metadata> {
130 #[cfg(any(test, feature = "test-support"))]
131 stat_probe::record(path);
132 std::fs::symlink_metadata(path)
133}
134
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub enum HazardKind {
137 Replaced,
141 MutatedWhileOpen,
144}
145
146impl HazardKind {
147 const fn summary(self) -> &'static str {
148 match self {
149 Self::Replaced => "two open connections are attached to different files at one path",
150 Self::MutatedWhileOpen => "database file changed while connections were open on it",
151 }
152 }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct DatabaseHazard {
157 pub kind: HazardKind,
158 pub path: PathBuf,
159 pub detail: String,
160}
161
162impl DatabaseHazard {
163 pub fn message(&self) -> String {
164 format!(
165 "sqlite database hazard ({}): {} — {}",
166 self.kind.summary(),
167 self.path.display(),
168 self.detail
169 )
170 }
171}
172
173#[derive(Clone, Debug)]
174struct Opener {
175 store: &'static str,
176 thread: String,
177 identity: Option<FileIdentity>,
178}
179
180impl Opener {
181 fn describe(&self) -> String {
182 match self.identity {
183 Some(identity) => format!("{} on {} attached to {identity}", self.store, self.thread),
184 None => format!(
185 "{} on {} (file identity unavailable)",
186 self.store, self.thread
187 ),
188 }
189 }
190}
191
192#[rustfmt::skip]
193test_support_visibility! {
194#[derive(Debug, Default)]
195struct OpenDatabase {
196 openers: Vec<Opener>,
197 identities: HashSet<LiveFileIdentity>,
198}
199}
200
201#[rustfmt::skip]
202test_support_visibility! {
203
204fn open_databases() -> &'static Mutex<BTreeMap<PathBuf, OpenDatabase>> {
205 static DATABASES: OnceLock<Mutex<BTreeMap<PathBuf, OpenDatabase>>> = OnceLock::new();
206 DATABASES.get_or_init(|| Mutex::new(BTreeMap::new()))
207}
208}
209
210#[derive(Default)]
211struct LiveFiles {
212 names: HashMap<PathBuf, usize>,
213 identities: HashMap<LiveFileIdentity, usize>,
214}
215
216fn live_files() -> &'static RwLock<LiveFiles> {
217 static FILES: OnceLock<RwLock<LiveFiles>> = OnceLock::new();
218 FILES.get_or_init(RwLock::default)
219}
220
221#[rustfmt::skip]
222test_support_visibility! {
223
224fn database_files(key: &Path) -> [PathBuf; 4] {
225 let sidecar = |suffix| {
226 let mut path = key.as_os_str().to_os_string();
227 path.push(suffix);
228 PathBuf::from(path)
229 };
230 [
231 key.to_path_buf(),
232 sidecar("-wal"),
233 sidecar("-shm"),
234 sidecar("-journal"),
235 ]
236}
237}
238
239#[rustfmt::skip]
240test_support_visibility! {
241
242fn retain_identities(
243 database: &mut OpenDatabase,
244 identities: impl IntoIterator<Item = LiveFileIdentity>,
245) {
246 let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
247 for identity in identities {
248 if database.identities.insert(identity) {
249 *files.identities.entry(identity).or_default() += 1;
250 }
251 }
252}
253}
254
255fn reported() -> &'static Mutex<Vec<DatabaseHazard>> {
256 static REPORTED: OnceLock<Mutex<Vec<DatabaseHazard>>> = OnceLock::new();
257 REPORTED.get_or_init(|| Mutex::new(Vec::new()))
258}
259
260fn registry_key(path: &Path) -> PathBuf {
267 if let Ok(resolved) = std::fs::canonicalize(path) {
268 return resolved;
269 }
270 match (path.parent(), path.file_name()) {
271 (Some(parent), Some(name)) if !parent.as_os_str().is_empty() => {
272 std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(name))
273 }
274 _ => path.to_path_buf(),
275 }
276}
277
278fn thread_label() -> String {
279 let current = std::thread::current();
280 match current.name() {
281 Some(name) => format!("thread {name}"),
282 None => format!("thread {:?}", current.id()),
283 }
284}
285
286fn crash_diagnostics_armed() -> bool {
287 static ARMED: OnceLock<bool> = OnceLock::new();
288 *ARMED.get_or_init(|| {
289 std::env::var_os("AFT_CAPTURE_CRASH_DIAGNOSTICS").as_deref() == Some(OsStr::new("1"))
290 })
291}
292
293fn report(hazard: DatabaseHazard) {
294 let message = hazard.message();
295 crate::slog_warn!("{message}");
296 if crash_diagnostics_armed() {
297 write_stderr_line(&format!("\nAFT sqlite database hazard: {message}\n"));
301 }
302 let mut reported = reported()
303 .lock()
304 .unwrap_or_else(std::sync::PoisonError::into_inner);
305 if reported.len() >= RETAINED_HAZARDS {
306 reported.remove(0);
307 }
308 reported.push(hazard);
309}
310
311#[cfg(unix)]
319fn write_stderr_line(line: &str) {
320 let bytes = line.as_bytes();
321 unsafe {
322 libc::write(
323 libc::STDERR_FILENO,
324 bytes.as_ptr().cast::<std::ffi::c_void>(),
325 bytes.len(),
326 );
327 }
328}
329
330#[cfg(not(unix))]
331fn write_stderr_line(line: &str) {
332 eprint!("{line}");
333}
334
335fn filesystem_gate() -> &'static parking_lot::ReentrantMutex<()> {
340 static GATE: parking_lot::ReentrantMutex<()> = parking_lot::ReentrantMutex::new(());
341 &GATE
342}
343
344pub fn filesystem_guard() -> parking_lot::ReentrantMutexGuard<'static, ()> {
345 filesystem_gate().lock()
346}
347
348pub fn note_open(path: &Path, store: &'static str) -> PathBuf {
355 let key = registry_key(path);
356 let paths = database_files(&key);
357 let identities = paths.each_ref().map(|path| LiveFileIdentity::of(path));
358 let opener = Opener {
359 store,
360 thread: thread_label(),
361 identity: identities[0].map(|identity| identity.file),
362 };
363 let hazard = {
364 let mut databases = open_databases()
365 .lock()
366 .unwrap_or_else(std::sync::PoisonError::into_inner);
367 let entry = databases.entry(key.clone()).or_default();
368 if entry.openers.is_empty() {
369 let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
370 for path in paths {
371 *files.names.entry(path).or_default() += 1;
372 }
373 }
374 let hazard = replacement_hazard(&key, entry, &opener);
375 retain_identities(entry, identities.into_iter().flatten());
376 entry.openers.push(opener);
377 hazard
378 };
379 if let Some(hazard) = hazard {
380 report(hazard);
381 }
382 key
383}
384
385pub fn note_close(key: &Path, store: &'static str) {
387 let mut databases = open_databases()
388 .lock()
389 .unwrap_or_else(std::sync::PoisonError::into_inner);
390 let Some(entry) = databases.get_mut(key) else {
391 return;
392 };
393 if let Some(index) = entry
394 .openers
395 .iter()
396 .rposition(|opener| opener.store == store)
397 {
398 entry.openers.remove(index);
399 }
400 if entry.openers.is_empty() {
401 let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
402 for path in database_files(key) {
403 if let Some(count) = files.names.get_mut(&path) {
404 *count -= 1;
405 if *count == 0 {
406 files.names.remove(&path);
407 }
408 }
409 }
410 for identity in &entry.identities {
411 if let Some(count) = files.identities.get_mut(identity) {
412 *count -= 1;
413 if *count == 0 {
414 files.identities.remove(identity);
415 }
416 }
417 }
418 databases.remove(key);
419 }
420}
421
422fn replacement_hazard(key: &Path, entry: &OpenDatabase, opener: &Opener) -> Option<DatabaseHazard> {
423 let identity = opener.identity?;
424 let previous = entry
425 .openers
426 .iter()
427 .find(|held| held.identity.is_some_and(|held| held != identity))?;
428 Some(DatabaseHazard {
429 kind: HazardKind::Replaced,
430 path: key.to_path_buf(),
431 detail: format!(
432 "the already-open {} met a new {}; SQLite shares one WAL-index per path, \
433 so the newer connection truncates the WAL-index the older one has mapped",
434 previous.describe(),
435 opener.describe()
436 ),
437 })
438}
439
440pub fn registered_connections_for_key(key: &Path) -> usize {
444 open_databases()
445 .lock()
446 .unwrap_or_else(std::sync::PoisonError::into_inner)
447 .get(key)
448 .map_or(0, |entry| entry.openers.len())
449}
450
451pub fn open_connections(path: &Path) -> usize {
452 let key = registry_key(path);
453 let identity = identity_of(&key);
454 open_databases()
455 .lock()
456 .unwrap_or_else(std::sync::PoisonError::into_inner)
457 .iter()
458 .map(|(registered_path, entry)| {
459 entry
460 .openers
461 .iter()
462 .filter(|opener| {
463 registered_path == &key || identity.is_some() && opener.identity == identity
464 })
465 .count()
466 })
467 .sum()
468}
469
470#[rustfmt::skip]
471test_support_visibility! {
472
473pub(crate) fn is_registered_file_path(path: &Path) -> bool {
475 live_files()
476 .read()
477 .unwrap_or_else(|p| p.into_inner())
478 .names
479 .contains_key(path)
480}
481}
482
483pub fn is_live_sqlite_file(path: &Path) -> bool {
487 if is_registered_file_path(path) {
488 return true;
489 }
490 #[cfg(any(test, feature = "test-support"))]
491 stat_probe::record(path);
492 let Ok((metadata, identity, links)) = crate::file_identity::metadata_with_link_count(path)
493 else {
494 return false;
495 };
496 let Some(file) = native_identity(identity) else {
497 return false;
498 };
499 is_live_identity(
500 LiveFileIdentity {
501 file,
502 created: metadata.created().ok(),
503 },
504 links,
505 )
506}
507
508fn is_live_identity(identity: LiveFileIdentity, links: u64) -> bool {
509 let known = || {
510 live_files()
511 .read()
512 .unwrap_or_else(|p| p.into_inner())
513 .identities
514 .contains_key(&identity)
515 };
516 if known() {
517 return true;
518 }
519 if links < 2 {
520 return false;
521 }
522 refresh_sidecar_identities();
523 known()
524}
525
526pub fn is_live_sqlite_file_with_metadata(
527 path: &Path,
528 metadata: Option<&std::fs::Metadata>,
529) -> bool {
530 #[cfg(windows)]
531 {
532 let _ = metadata;
535 return is_live_sqlite_file(path);
536 }
537 #[cfg(not(windows))]
538 {
539 if metadata.is_some_and(|metadata| metadata.file_type().is_symlink()) {
542 let key = registry_key(path);
543 if is_registered_file_path(&key) {
544 return true;
545 }
546 let target = std::fs::metadata(path).ok();
547 return is_live_sqlite_file_with_metadata(&key, target.as_ref());
548 }
549 let Some(metadata) = metadata else {
550 return false;
551 };
552 let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
553 return false;
554 };
555 #[cfg(unix)]
556 let links = {
557 use std::os::unix::fs::MetadataExt;
558 metadata.nlink()
559 };
560 #[cfg(not(unix))]
561 let links = 1;
562 is_live_identity(identity, links)
563 }
564}
565
566fn refresh_sidecar_identities() {
567 let paths = open_databases()
568 .lock()
569 .unwrap_or_else(|p| p.into_inner())
570 .keys()
571 .cloned()
572 .collect::<Vec<_>>();
573 let refreshed = paths
575 .into_iter()
576 .map(|key| {
577 let identities = database_files(&key)[1..]
578 .iter()
579 .filter_map(|path| LiveFileIdentity::of(path))
580 .collect::<Vec<_>>();
581 (key, identities)
582 })
583 .collect::<Vec<_>>();
584 let mut databases = open_databases().lock().unwrap_or_else(|p| p.into_inner());
585 for (key, identities) in refreshed {
586 if let Some(database) = databases.get_mut(&key) {
587 retain_identities(database, identities);
588 }
589 }
590}
591
592pub fn is_live_sqlite_handle(metadata: &std::fs::Metadata) -> bool {
603 let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
604 return false;
605 };
606 let known = || {
607 live_files()
608 .read()
609 .unwrap_or_else(|p| p.into_inner())
610 .identities
611 .contains_key(&identity)
612 };
613 if known() {
614 return true;
615 }
616 #[cfg(unix)]
618 refresh_sidecar_identities();
619 known()
620}
621
622pub fn guard_replacement(path: &Path, action: &str) {
628 let key = registry_key(path);
629 let detail = {
630 let databases = open_databases()
631 .lock()
632 .unwrap_or_else(std::sync::PoisonError::into_inner);
633 let Some(entry) = databases.get(&key) else {
634 return;
635 };
636 if entry.openers.is_empty() {
637 return;
638 }
639 let openers = entry
640 .openers
641 .iter()
642 .map(Opener::describe)
643 .collect::<Vec<_>>()
644 .join("; ");
645 format!("{action} ran while these connections were still open: [{openers}]")
646 };
647 report(DatabaseHazard {
648 kind: HazardKind::MutatedWhileOpen,
649 path: key,
650 detail,
651 });
652}
653
654pub fn hazards_for_path(path: &Path) -> Vec<DatabaseHazard> {
656 let key = registry_key(path);
657 reported()
658 .lock()
659 .unwrap_or_else(std::sync::PoisonError::into_inner)
660 .iter()
661 .filter(|hazard| hazard.path == key)
662 .cloned()
663 .collect()
664}
665
666pub fn reported_hazards() -> Vec<DatabaseHazard> {
668 reported()
669 .lock()
670 .unwrap_or_else(std::sync::PoisonError::into_inner)
671 .clone()
672}
673
674#[cfg(any(test, feature = "test-support"))]
675pub mod stat_probe {
676 use super::*;
677 use std::cell::RefCell;
678
679 thread_local! {
680 static COUNTS: RefCell<Option<BTreeMap<PathBuf, usize>>> = const { RefCell::new(None) };
681 static CANDIDATES_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
682 }
683
684 pub fn record_followed(path: &Path) {
685 if !CANDIDATES_ONLY.with(|only| only.get()) {
686 record(path);
687 }
688 }
689
690 pub fn record(path: &Path) {
691 COUNTS.with(|counts| {
692 if let Some(counts) = counts.borrow_mut().as_mut() {
693 *counts.entry(path.to_path_buf()).or_default() += 1;
694 }
695 });
696 }
697
698 pub fn count(f: impl FnOnce()) -> BTreeMap<PathBuf, usize> {
699 struct Reset;
700 impl Drop for Reset {
701 fn drop(&mut self) {
702 COUNTS.with(|counts| *counts.borrow_mut() = None);
703 }
704 }
705 let _reset = Reset;
706 COUNTS.with(|counts| *counts.borrow_mut() = Some(BTreeMap::new()));
707 f();
708 COUNTS.with(|counts| counts.borrow_mut().take().unwrap())
709 }
710}
711
712#[cfg(test)]
713mod tests {
714 #[cfg(unix)]
715 use super::*;
716
717 #[cfg(unix)]
719 use rusqlite::Connection;
720
721 #[cfg(unix)]
722 fn shm_path(path: &Path) -> PathBuf {
723 PathBuf::from(format!("{}-shm", path.display()))
724 }
725
726 #[cfg(unix)]
747 #[test]
748 fn replacing_the_database_file_truncates_the_wal_index_under_a_live_mapping() {
749 const WAL_INDEX_REGION_BYTES: u64 = 32 * 1024;
751
752 let dir = tempfile::tempdir().expect("tempdir");
753 let path = dir.path().join("replaced.sqlite");
754
755 let first = Connection::open(&path).expect("open first connection");
756 first
759 .pragma_update(None, "page_size", 512)
760 .expect("small pages");
761 first
762 .pragma_update(None, "journal_mode", "WAL")
763 .expect("first connection WAL");
764 first
765 .pragma_update(None, "synchronous", "OFF")
766 .expect("unsynced fixture writes");
767 first
768 .pragma_update(None, "wal_autocheckpoint", 0)
769 .expect("no autocheckpoint");
770 first
771 .execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB);")
772 .expect("seed");
773
774 let mut mapped_bytes = 0;
777 for id in 0..20_000_i64 {
778 first
779 .execute(
780 "INSERT INTO t(id, payload) VALUES (?1, zeroblob(400))",
781 [id],
782 )
783 .expect("append a WAL frame");
784 if id % 256 == 0 {
785 mapped_bytes = std::fs::metadata(shm_path(&path))
786 .expect("WAL-index exists")
787 .len();
788 if mapped_bytes > WAL_INDEX_REGION_BYTES {
789 break;
790 }
791 }
792 }
793 assert!(
794 mapped_bytes > WAL_INDEX_REGION_BYTES,
795 "fixture never mapped a second WAL-index region (got {mapped_bytes} bytes); \
796 without one the truncation is hidden by SQLite re-extending region 0"
797 );
798 let first_identity = identity_of(&path).expect("first database identity");
799
800 std::fs::remove_file(&path).expect("remove the database file");
804 let second = Connection::open(&path).expect("open second connection");
805 second
806 .pragma_update(None, "journal_mode", "WAL")
807 .expect("second connection WAL");
808 second
809 .execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY);")
810 .expect("write through the replacement");
811 let second_identity = identity_of(&path).expect("second database identity");
812 assert_ne!(
813 first_identity, second_identity,
814 "fixture did not actually replace the database file"
815 );
816
817 let after_bytes = std::fs::metadata(shm_path(&path))
818 .expect("WAL-index still exists")
819 .len();
820 assert!(
821 after_bytes < mapped_bytes,
822 "the second connection did not truncate the WAL-index the first one has mapped \
823 (before={mapped_bytes} bytes, after={after_bytes} bytes)"
824 );
825
826 drop(second);
827 std::mem::forget(first);
830 }
831}