Skip to main content

latexml_post/
sqlite_store.rs

1//! A small SQLite store for the post-processor's on-disk caches: a file, or an in-memory database when there is no
2//! file to keep or it cannot be used.
3//!
4//! WAL journal (the file's own mode where WAL cannot be set: a network filesystem, or one without shared memory, FUSE,
5//! CIFS, WSL's `/mnt`), `synchronous=NORMAL` (in WAL no sync per commit, and a crash never corrupts the file), a busy
6//! timeout, and a `user_version` gate: a file made for another schema, or another program's database, is left alone;
7//! a new file gets its schema under the write lock. Opening is retried while another process holds the file: turning
8//! a new file to WAL meets a lock the busy timeout does not wait on (SQLite returns `SQLITE_BUSY` at once to avoid a
9//! deadlock). Writers take one `IMMEDIATE` transaction per allocation ([`SqliteStore::immediate`]), so processes
10//! sharing the file serialize on it. A store is opened lazily by its owner and never kept in a static (a forked process
11//! must not inherit the connection). Failure policy, opening, reading or writing: a Warning, then the rest of the run in
12//! memory ([`SqliteStore::fell_back`]), from a copy of what the file held when it gives it at once and the copy works.
13
14use std::path::{Path, PathBuf};
15
16use rusqlite::{Connection, Transaction, TransactionBehavior};
17
18/// An open store: its connection and the file it reads, when not in memory.
19pub struct SqliteStore {
20  conn:      Connection,
21  file:      Option<PathBuf>,
22  schema:    &'static str,
23  fell_back: bool,
24  /// Declared after `conn`, so dropped once the connection is closed.
25  wal_check: WalCheck,
26}
27
28/// How long a process waits for others holding the file, opening it or writing (as `object_db`): well inside a
29/// conversion's default `--timeout=60`, after which the run goes on in memory.
30const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
31
32impl SqliteStore {
33  /// Open `file` (`None`: in memory) with `schema` (its statements idempotent) at schema `version`. A file that
34  /// cannot be opened, or holds another version, is reported (Warning) and left alone; the store is then in memory.
35  pub fn open(file: Option<&Path>, schema: &'static str, version: i32) -> Self {
36    let conn = file.and_then(|file| match Self::open_file(file, schema, version) {
37      Ok(conn) => Some(conn),
38      Err(e) => {
39        Warn!(
40          "I/O",
41          "cache",
42          "Can't use the cache {} ({}); this run's entries are kept in memory only. Delete the file when no \
43           conversion is using it, and the next run makes a new one",
44          file.display(),
45          e
46        );
47        None
48      },
49    });
50    let fell_back = file.is_some() && conn.is_none();
51    let file = conn.as_ref().and(file.map(Path::to_path_buf));
52    let conn = conn.unwrap_or_else(|| Self::in_memory(schema));
53    let wal_check = WalCheck::new(file.as_deref());
54    SqliteStore {
55      conn,
56      file,
57      schema,
58      fell_back,
59      wal_check,
60    }
61  }
62
63  /// [`Self::open_once`], again after a pause while another process holds the file, up to [`BUSY_TIMEOUT`]. A link is
64  /// never followed (SQLite would make or write the file it leads to, out of the folder), nor anything else not a
65  /// regular file opened (a FIFO, a device, a directory). The side files cannot be redirected: SQLite names them after
66  /// the file and opens them with `O_NOFOLLOW` (`unixOpen`), so a planted `-wal` or `-shm` link fails the open.
67  fn open_file(file: &Path, schema: &str, version: i32) -> Result<Connection, String> {
68    match std::fs::symlink_metadata(file).map(|meta| meta.file_type()) {
69      Ok(kind) if kind.is_symlink() => return Err("a symbolic link, never followed".to_string()),
70      Ok(kind) if !kind.is_file() => return Err("not a regular file".to_string()),
71      _ => {},
72    }
73    let start = std::time::Instant::now();
74    // A pause that grows, and differs between processes, so they do not meet again.
75    let mut pause = std::time::Duration::from_micros(500 + u64::from(std::process::id() % 1000));
76    loop {
77      match Self::open_once(file, schema, version) {
78        Err(OpenError::Sqlite(e)) if Self::busy(&e) && start.elapsed() < BUSY_TIMEOUT => {
79          std::thread::sleep(pause);
80          pause = (pause * 2).min(std::time::Duration::from_millis(100));
81        },
82        Err(OpenError::Sqlite(e)) => return Err(e.to_string()),
83        Err(OpenError::Version(found)) => {
84          return Err(format!("schema version {found}, not {version}"));
85        },
86        Err(OpenError::Foreign) => return Err("another program's database".to_string()),
87        Ok(conn) => return Ok(conn),
88      }
89    }
90  }
91
92  fn busy(e: &rusqlite::Error) -> bool {
93    matches!(
94      e.sqlite_error_code(),
95      Some(rusqlite::ErrorCode::DatabaseBusy | rusqlite::ErrorCode::DatabaseLocked)
96    )
97  }
98
99  fn open_once(file: &Path, schema: &str, version: i32) -> Result<Connection, OpenError> {
100    let mut conn = Connection::open(file)?;
101    conn.busy_timeout(BUSY_TIMEOUT)?;
102    // A file in WAL already is not asked again. Where WAL cannot be set SQLite grants another mode, or errs (no shared
103    // memory): the file keeps its own; only a busy file is tried again.
104    let mode: String = conn.query_row("PRAGMA journal_mode", [], |row| row.get(0))?;
105    if !mode.eq_ignore_ascii_case("wal")
106      && let Err(e) = conn.query_row("PRAGMA journal_mode=WAL", [], |row| row.get::<_, String>(0))
107      && Self::busy(&e)
108    {
109      return Err(e.into());
110    }
111    conn.pragma_update(None, "synchronous", "NORMAL")?;
112    let found: i32 = conn.pragma_query_value(None, "user_version", |row| row.get(0))?;
113    if found == version {
114      return Ok(conn);
115    }
116    if found != 0 {
117      return Err(OpenError::Version(found));
118    }
119    // A new file gets the schema under the write lock, read again there: another process may have made it meanwhile.
120    let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
121    match tx.pragma_query_value(None, "user_version", |row| row.get(0))? {
122      0 => {
123        let tables: i64 = tx.query_row(
124          "SELECT count(*) FROM sqlite_master WHERE type = 'table'",
125          [],
126          |row| row.get(0),
127        )?;
128        if tables > 0 {
129          return Err(OpenError::Foreign);
130        }
131        tx.execute_batch(&format!("{schema} PRAGMA user_version = {version};"))?;
132      },
133      found if found == version => {},
134      found => return Err(OpenError::Version(found)),
135    }
136    tx.commit()?;
137    Ok(conn)
138  }
139
140  fn in_memory(schema: &str) -> Connection {
141    let conn = Connection::open_in_memory().expect("an in-memory SQLite database");
142    conn
143      .execute_batch(schema)
144      .expect("the store's schema in memory");
145    conn
146  }
147
148  /// The file the store reads, `None` in memory.
149  pub fn file(&self) -> Option<&Path> { self.file.as_deref() }
150
151  /// Whether a file was asked for and could not be used, so the store may not know what earlier runs stored there.
152  pub fn fell_back(&self) -> bool { self.fell_back }
153
154  /// Whether a file was asked for: the store runs on it, or in memory in its place.
155  pub fn wants_file(&self) -> bool { self.file.is_some() || self.fell_back }
156
157  /// Run `f` in one `IMMEDIATE` transaction, committed when it succeeds. A file that fails is reported (Warning) and
158  /// replaced by memory (`attempt`, from `copy`), where `f` runs again: `f` is told whether the store runs in memory
159  /// in place of its file ([`Self::fell_back`]), and defers its own side effects (a Warning) until the call returns. A
160  /// transaction that fails in a fresh store in memory is reported (Error) and gives `None`.
161  pub fn immediate<T>(
162    &mut self,
163    mut f: impl FnMut(&Transaction, bool) -> rusqlite::Result<T>,
164  ) -> Option<T> {
165    self.attempt(|conn, fell_back| Self::run(conn, fell_back, &mut f))
166  }
167
168  fn run<T>(
169    conn: &mut Connection,
170    fell_back: bool,
171    f: &mut impl FnMut(&Transaction, bool) -> rusqlite::Result<T>,
172  ) -> rusqlite::Result<T> {
173    let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
174    let value = f(&tx, fell_back)?;
175    tx.commit()?;
176    Ok(value)
177  }
178
179  /// A read outside any transaction, under [`Self::immediate`]'s failure policy.
180  pub fn read<T>(&mut self, f: impl Fn(&Connection) -> rusqlite::Result<T>) -> Option<T> {
181    self.attempt(|conn, _| f(conn))
182  }
183
184  /// `f` on the store; when it fails on the file, the store goes to memory (one Warning) and `f` runs there: on a copy
185  /// of the file's entries (this run's among them) when the file gives them at once, else, or when `f` fails on the
186  /// copy (a broken file copies as it is), on an empty store.
187  fn attempt<T>(
188    &mut self,
189    mut f: impl FnMut(&mut Connection, bool) -> rusqlite::Result<T>,
190  ) -> Option<T> {
191    let e = match f(&mut self.conn, self.fell_back) {
192      Ok(value) => return Some(value),
193      Err(e) => e,
194    };
195    let Some(file) = self.file.take() else {
196      return Self::ok(Err(e));
197    };
198    self.wal_check.0 = None;
199    self.fell_back = true;
200    let mut result = None;
201    if let Some(copy) = self.copy() {
202      self.conn = copy;
203      result = f(&mut self.conn, true).ok();
204    }
205    let kept = result.is_some();
206    Warn!(
207      "I/O",
208      "cache",
209      "The cache {} failed ({}); this run's further entries are kept in memory only{}",
210      file.display(),
211      e,
212      if kept {
213        ""
214      } else {
215        ", and its earlier ones are lost"
216      }
217    );
218    if kept {
219      return result;
220    }
221    self.conn = Self::in_memory(self.schema);
222    Self::ok(f(&mut self.conn, true))
223  }
224
225  /// A copy in memory of the file's entries, when the file gives them at once: the connection, left right after, waits
226  /// on no lock (a busy source would be retried for ever by `Backup::run_to_completion`), and one step copies the
227  /// whole file or nothing.
228  fn copy(&self) -> Option<Connection> {
229    self.conn.busy_timeout(std::time::Duration::ZERO).ok()?;
230    let mut copy = Connection::open_in_memory().ok()?;
231    let done = matches!(
232      rusqlite::backup::Backup::new(&self.conn, &mut copy).map(|backup| backup.step(-1)),
233      Ok(Ok(rusqlite::backup::StepResult::Done))
234    );
235    done.then_some(copy)
236  }
237
238  /// A store in memory reports its failure (Error), a bug in its caller's statements.
239  fn ok<T>(result: rusqlite::Result<T>) -> Option<T> {
240    result
241      .map_err(|e| {
242        Error!(
243          "internal",
244          "cache",
245          "The cache in memory failed ({}); the entry is not kept",
246          e
247        );
248      })
249      .ok()
250  }
251}
252
253/// A store's file, looked at once its connection is closed. A close removes the `-wal` and `-shm` files only when its
254/// one try for the file's exclusive lock succeeds (`sqlite3WalClose`), so processes closing together can all leave
255/// them: while a `-wal` is there after a pause (another each time, so the processes part), the file is opened, read
256/// (which opens its WAL) and closed again, twice at most. A process still using the file keeps them, as SQLite means.
257/// A store gone to memory checks nothing.
258struct WalCheck(Option<PathBuf>);
259
260impl WalCheck {
261  /// The file's folder resolved, its name kept: `SQLITE_OPEN_NOFOLLOW` refuses a link anywhere in the path
262  /// (`unixFullPathname`, sqlite3.c 3.54.1 L47688, L63807; macOS temporary folders are under `/var` → `/private/var`).
263  /// A form still carrying a Windows verbatim prefix (`//?/` after `canonical`) stays as written: the win32 VFS checks
264  /// no links and hands the name to `GetFullPathNameW` and `CreateFileW` as it is (`winFullPathnameNoMutex`, `winOpen`).
265  fn new(file: Option<&Path>) -> Self {
266    use latexml_core::util::pathname::{resolved_directory_of, strip_windows_verbatim_prefix};
267    WalCheck(
268      file.map(|file| match file.to_str().map(resolved_directory_of) {
269        Some(resolved) if strip_windows_verbatim_prefix(&resolved) == resolved => {
270          PathBuf::from(resolved)
271        },
272        _ => file.to_path_buf(),
273      }),
274    )
275  }
276}
277
278impl Drop for WalCheck {
279  fn drop(&mut self) {
280    use std::hash::BuildHasher;
281    let Some(file) = &self.0 else { return };
282    let mut wal = file.as_os_str().to_owned();
283    wal.push("-wal");
284    if !Path::new(&wal).exists() {
285      return;
286    }
287    // Windows: every SHARED lock first takes the PENDING byte, up to 3 tries `Sleep(1)` apart (`winLock`, a scheduler
288    // tick of up to 15.6 ms), so the processes' checks overlap far longer and keep failing each other's close: there the
289    // pause's spread doubles each try, to 128 ms (2 tries in 2-5 ms left a `-wal` in a fifth of the rounds of
290    // `simultaneous_closes_leave_no_side_files`).
291    let attempts = if cfg!(windows) { 8 } else { 2 };
292    let random = std::collections::hash_map::RandomState::new();
293    for attempt in 0..attempts {
294      let spread = if cfg!(windows) {
295        4000 << attempt.min(5)
296      } else {
297        3000
298      };
299      // The process id mixed in: forked processes share `RandomState`'s keys (`lsp_server/unix.rs`).
300      std::thread::sleep(std::time::Duration::from_micros(
301        2000 + random.hash_one((std::process::id(), attempt)) % spread,
302      ));
303      // Looked at again after the pause: a read of the file with no `-wal` would make one.
304      if !Path::new(&wal).exists() {
305        return;
306      }
307      // No `SQLITE_OPEN_CREATE`: a file removed meanwhile is not made again; nor is a link followed; nor a lock awaited.
308      let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE
309        | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW
310        | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX;
311      if let Ok(conn) = Connection::open_with_flags(file, flags)
312        && conn.busy_timeout(std::time::Duration::ZERO).is_ok()
313      {
314        let _ = conn.query_row("SELECT count(*) FROM sqlite_master", [], |row| {
315          row.get::<_, i64>(0)
316        });
317      }
318    }
319  }
320}
321
322enum OpenError {
323  Sqlite(rusqlite::Error),
324  /// The file holds this schema version, another than the store's.
325  Version(i32),
326  /// The file is another program's SQLite database: tables, and no schema version.
327  Foreign,
328}
329
330impl From<rusqlite::Error> for OpenError {
331  fn from(e: rusqlite::Error) -> Self { OpenError::Sqlite(e) }
332}
333
334#[cfg(test)]
335mod tests {
336  use super::*;
337
338  const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS t(v INTEGER);";
339
340  /// A file of another schema version is left alone and the store runs in memory; a fresh file gets the schema.
341  #[test]
342  fn another_version_is_left_alone() {
343    let dir = tempfile::tempdir().unwrap();
344    let file = dir.path().join("c.db");
345    let store = SqliteStore::open(Some(&file), SCHEMA, 1);
346    assert_eq!(store.file(), Some(file.as_path()));
347    drop(store);
348    let store = SqliteStore::open(Some(&file), SCHEMA, 2);
349    assert_eq!(store.file(), None);
350    let not_sqlite = dir.path().join("perl.cache");
351    std::fs::write(
352      &not_sqlite,
353      b"a Berkeley DB file, not SQLite at all, padded past one header",
354    )
355    .unwrap();
356    let mut store = SqliteStore::open(Some(&not_sqlite), SCHEMA, 1);
357    assert_eq!(store.file(), None);
358    assert_eq!(
359      store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", [])),
360      Some(1)
361    );
362    assert!(
363      std::fs::read(&not_sqlite)
364        .unwrap()
365        .starts_with(b"a Berkeley DB file")
366    );
367    // Another program's database, its `user_version` 0, keeps its tables and its version.
368    let foreign = dir.path().join("other.db");
369    Connection::open(&foreign)
370      .unwrap()
371      .execute_batch("CREATE TABLE notes(text TEXT);")
372      .unwrap();
373    let store = SqliteStore::open(Some(&foreign), SCHEMA, 1);
374    assert_eq!((store.file(), store.fell_back()), (None, true));
375    let conn = Connection::open(&foreign).unwrap();
376    let tables: Vec<String> = conn
377      .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
378      .unwrap()
379      .query_map([], |row| row.get(0))
380      .unwrap()
381      .collect::<Result<_, _>>()
382      .unwrap();
383    let version: i32 = conn
384      .pragma_query_value(None, "user_version", |row| row.get(0))
385      .unwrap();
386    assert_eq!((tables, version), (vec!["notes".to_string()], 0));
387  }
388
389  /// A statement that fails in memory is reported and gives nothing, without a panic, and the store keeps its entries.
390  #[test]
391  fn a_failure_in_memory_gives_nothing() {
392    let mut store = SqliteStore::open(None, SCHEMA, 1);
393    assert_eq!(
394      store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", [])),
395      Some(1)
396    );
397    assert_eq!(
398      store.immediate(|tx, _| tx.execute("INSERT INTO nowhere(v) VALUES (1)", [])),
399      None
400    );
401    assert_eq!(
402      store.read(|conn| conn.query_row("SELECT nothing FROM t", [], |row| row.get::<_, i64>(0))),
403      None
404    );
405    assert_eq!(
406      store.read(|conn| conn.query_row("SELECT count(*) FROM t", [], |row| row.get::<_, i64>(0))),
407      Some(1)
408    );
409  }
410
411  /// Sixteen processes opening one new file at the same moment all end on the file: turning it to WAL and writing its
412  /// schema meet a lock the busy timeout does not wait on, and are retried (issue 995 review: 3 trials in 5 left a
413  /// process in memory, `database is locked`). The test runs itself as each process, released by one start file.
414  #[test]
415  fn simultaneous_opens_of_a_new_file_all_use_it() {
416    const NAME: &str = "sqlite_store::tests::simultaneous_opens_of_a_new_file_all_use_it";
417    if let Ok(file) = std::env::var("SQLITE_STORE_TEST_OPEN") {
418      let go = Path::new(&file).with_extension("go");
419      while !go.exists() {
420        std::thread::sleep(std::time::Duration::from_micros(200));
421      }
422      let store = SqliteStore::open(Some(Path::new(&file)), SCHEMA, 1);
423      print!(
424        "{}",
425        if store.file().is_some() {
426          "FILE"
427        } else {
428          "MEMORY"
429        }
430      );
431      return;
432    }
433    for _ in 0..3 {
434      let dir = tempfile::tempdir().unwrap();
435      let file = dir.path().join("c.db");
436      let children: Vec<_> = (0..16)
437        .map(|_| {
438          std::process::Command::new(std::env::current_exe().unwrap())
439            .args(["--exact", NAME, "--nocapture", "--test-threads=1"])
440            .env("SQLITE_STORE_TEST_OPEN", &file)
441            .stdout(std::process::Stdio::piped())
442            .stderr(std::process::Stdio::null())
443            .spawn()
444            .unwrap()
445        })
446        .collect();
447      std::thread::sleep(std::time::Duration::from_millis(300));
448      std::fs::write(file.with_extension("go"), b"").unwrap();
449      let outcomes: Vec<String> = children
450        .into_iter()
451        .map(|child| {
452          let out = String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap();
453          if out.contains("FILE") {
454            "FILE"
455          } else {
456            "MEMORY"
457          }
458          .to_string()
459        })
460        .collect();
461      assert_eq!(outcomes, vec!["FILE"; 16]);
462    }
463  }
464
465  /// Eight processes that open a new file together, write, and close it at the same moment leave no `-wal` or `-shm`,
466  /// none in memory, no Warning ([`WalCheck`]; base: 162-282 side files in 200 rounds on Linux; macOS CI run
467  /// 45645721304 left them in `batchfix995_concurrent_documents_in_one_folder_never_share_a_name`). Eight processes in
468  /// all, each running every round (`SQLITE_STORE_TEST_ROUNDS`, default 100), released by start files.
469  #[test]
470  fn simultaneous_closes_leave_no_side_files() {
471    const NAME: &str = "sqlite_store::tests::simultaneous_closes_leave_no_side_files";
472    const PROCESSES: usize = 8;
473    let wait_for = |path: &Path| {
474      let start = std::time::Instant::now();
475      while !path.exists() {
476        assert!(
477          start.elapsed() < std::time::Duration::from_secs(30),
478          "{}",
479          path.display()
480        );
481        std::thread::sleep(std::time::Duration::from_micros(100));
482      }
483    };
484    let rounds: usize =
485      std::env::var("SQLITE_STORE_TEST_ROUNDS").map_or(100, |n| n.parse().unwrap());
486    if let Ok(child) = std::env::var("SQLITE_STORE_TEST_CLOSE") {
487      use latexml_core::common::error::{LogStatus, get_status};
488      let (dir, k) = child.split_once('|').unwrap();
489      let dir = Path::new(dir);
490      for round in 0..rounds {
491        wait_for(&dir.join(format!("open{round}")));
492        let warnings = get_status(LogStatus::Warning);
493        let mut store = SqliteStore::open(Some(&dir.join(format!("c{round}.db"))), SCHEMA, 1);
494        store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
495        let on_file = store.file().is_some();
496        std::fs::write(dir.join(format!("ready{round}.{k}")), b"").unwrap();
497        wait_for(&dir.join(format!("close{round}")));
498        drop(store);
499        let warnings = get_status(LogStatus::Warning) - warnings;
500        // Written whole before it is seen: the parent reads it once it exists.
501        let part = dir.join(format!("part{round}.{k}"));
502        std::fs::write(&part, format!("{} {warnings}", u8::from(!on_file))).unwrap();
503        std::fs::rename(part, dir.join(format!("done{round}.{k}"))).unwrap();
504      }
505      return;
506    }
507    let dir = tempfile::tempdir().unwrap();
508    let children: Vec<_> = (0..PROCESSES)
509      .map(|k| {
510        std::process::Command::new(std::env::current_exe().unwrap())
511          .args(["--exact", NAME, "--nocapture", "--test-threads=1"])
512          .env(
513            "SQLITE_STORE_TEST_CLOSE",
514            format!("{}|{k}", dir.path().display()),
515          )
516          .env("SQLITE_STORE_TEST_ROUNDS", rounds.to_string())
517          .stdout(std::process::Stdio::null())
518          .spawn()
519          .unwrap()
520      })
521      .collect();
522    let (mut left, mut memory, mut warnings) = (Vec::new(), 0, 0);
523    for round in 0..rounds {
524      std::fs::write(dir.path().join(format!("open{round}")), b"").unwrap();
525      (0..PROCESSES).for_each(|k| wait_for(&dir.path().join(format!("ready{round}.{k}"))));
526      std::fs::write(dir.path().join(format!("close{round}")), b"").unwrap();
527      for k in 0..PROCESSES {
528        let done = dir.path().join(format!("done{round}.{k}"));
529        wait_for(&done);
530        let counts: Vec<usize> = std::fs::read_to_string(&done)
531          .unwrap()
532          .split(' ')
533          .map(|n| n.parse().unwrap())
534          .collect();
535        memory += counts[0];
536        warnings += counts[1];
537      }
538      for side in ["-wal", "-shm"] {
539        if dir.path().join(format!("c{round}.db{side}")).exists() {
540          left.push(format!("c{round}.db{side}"));
541        }
542      }
543    }
544    children
545      .into_iter()
546      .for_each(|mut child| assert!(child.wait().unwrap().success()));
547    eprintln!(
548      "rounds {rounds}: side files left {}, in memory {memory}, warnings {warnings}",
549      left.len()
550    );
551    assert_eq!((left, memory, warnings), (Vec::<String>::new(), 0, 0));
552  }
553
554  /// [`WalCheck`] makes nothing: a file removed while another process keeps its `-wal` is not made again (no
555  /// `SQLITE_OPEN_CREATE`), a file it cannot write is left with no Warning, and a file in another journal mode, which
556  /// has no `-wal` (WAL refused: a network filesystem, WSL's `/mnt`), is not opened. A leftover nothing holds is
557  /// removed, through a linked folder too (Unix only: Windows locks a held `-shm` against the copy's reads).
558  #[cfg(unix)]
559  #[test]
560  fn a_close_check_removes_a_leftover_and_makes_no_file() {
561    use std::os::unix::fs::PermissionsExt;
562
563    use latexml_core::common::error::{LogStatus, get_status};
564    let side = |file: &Path, name: &str| {
565      let mut side = file.as_os_str().to_owned();
566      side.push(name);
567      PathBuf::from(side)
568    };
569    let dir = tempfile::tempdir().unwrap();
570    let file = dir.path().join("c.db");
571    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
572    store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
573    std::fs::remove_file(&file).unwrap();
574    assert!(side(&file, "-wal").exists());
575    drop(WalCheck::new(Some(&file)));
576    assert!(!file.exists());
577    drop(store);
578    assert!(!file.exists());
579
580    let warnings = get_status(LogStatus::Warning);
581    let file = dir.path().join("r.db");
582    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
583    store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
584    let holder = Connection::open(&file).unwrap();
585    holder
586      .query_row("SELECT count(*) FROM t", [], |row| row.get::<_, i64>(0))
587      .unwrap();
588    drop(store);
589    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o444)).unwrap();
590    std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap();
591    drop(WalCheck::new(Some(&file)));
592    std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
593    assert_eq!(get_status(LogStatus::Warning) - warnings, 0);
594    drop(holder);
595
596    let file = dir.path().join("d.db");
597    let conn = Connection::open(&file).unwrap();
598    conn.execute_batch(SCHEMA).unwrap();
599    drop(conn);
600    drop(WalCheck::new(Some(&file)));
601    assert!(!side(&file, "-wal").exists() && !side(&file, "-shm").exists());
602
603    // A leftover nothing holds (copied while a store keeps `h.db` open) is removed and its entries kept, also when
604    // named through a linked folder, which `SQLITE_OPEN_NOFOLLOW` refuses (macOS temporary folders: `/var` is a link).
605    let real = dir.path().join("real");
606    std::fs::create_dir(&real).unwrap();
607    let link = dir.path().join("link");
608    std::os::unix::fs::symlink(&real, &link).unwrap();
609    let mut holder = SqliteStore::open(Some(&real.join("h.db")), SCHEMA, 1);
610    holder.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
611    let mut outcomes = Vec::new();
612    for (folder, name) in [(&link, "l.db"), (&real, "p.db")] {
613      for ext in ["", "-wal", "-shm"] {
614        std::fs::copy(side(&real.join("h.db"), ext), side(&real.join(name), ext)).unwrap();
615      }
616      drop(WalCheck::new(Some(&folder.join(name))));
617      let left = ["-wal", "-shm"].map(|ext| side(&real.join(name), ext).exists());
618      let entries: i64 = Connection::open(real.join(name))
619        .unwrap()
620        .query_row("SELECT count(*) FROM t", [], |row| row.get(0))
621        .unwrap();
622      outcomes.push((name, left, entries));
623    }
624    drop(holder);
625    assert_eq!(outcomes, [("l.db", [false; 2], 1), ("p.db", [false; 2], 1)]);
626  }
627
628  /// A file another process holds locked against readers (a `DELETE` journal under `BEGIN EXCLUSIVE` with a pending
629  /// write) past the 10 s lock wait: the store's transaction falls back to memory once that wait is over, with no copy
630  /// of the file's entries (round 7 copied with `run_to_completion`, which retries a busy source for ever), one
631  /// Warning, and the earlier entries lost.
632  #[test]
633  fn a_file_locked_against_readers_falls_back_without_its_entries() {
634    use latexml_core::common::error::{LogStatus, get_status};
635    let dir = tempfile::tempdir().unwrap();
636    let file = dir.path().join("c.db");
637    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
638    store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (7)", []));
639    store
640      .conn
641      .pragma_update(None, "journal_mode", "DELETE")
642      .unwrap();
643    let holder = Connection::open(&file).unwrap();
644    holder
645      .execute_batch("BEGIN EXCLUSIVE; INSERT INTO t(v) VALUES (9);")
646      .unwrap();
647    let (send, receive) = std::sync::mpsc::channel();
648    let start = std::time::Instant::now();
649    let worker = std::thread::spawn(move || {
650      let warnings = get_status(LogStatus::Warning);
651      let inserted = store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
652      let kept = store.read(|conn| {
653        conn
654          .prepare("SELECT v FROM t ORDER BY v")?
655          .query_map([], |row| row.get::<_, i64>(0))?
656          .collect::<rusqlite::Result<Vec<_>>>()
657      });
658      let counts = (
659        get_status(LogStatus::Warning) - warnings,
660        get_status(LogStatus::Error),
661      );
662      send
663        .send((inserted, kept, counts, store.file().is_none()))
664        .unwrap();
665    });
666    let outcome = receive.recv_timeout(std::time::Duration::from_secs(25));
667    let took = start.elapsed();
668    holder.execute_batch("COMMIT").unwrap();
669    worker.join().unwrap();
670    assert_eq!(
671      outcome.expect("the store fell back within 25 s"),
672      (Some(1), Some(vec![1]), (1, 0), true)
673    );
674    // One busy wait, not two: 10 s on Linux. On macOS CI the same wait measured 18.2-18.3 s twice; the suspected
675    // cause, not yet confirmed on a Mac, is that SQLite's busy handler counts its short sleeps by their nominal
676    // lengths and macOS lengthens them (timer coalescing). So the bound there only catches a wait that never ends.
677    let bound = if cfg!(target_os = "macos") { 24 } else { 16 };
678    assert!(took < std::time::Duration::from_secs(bound), "{took:?}");
679  }
680
681  /// A cache file that is a link is never followed (issue 995 review, round 7: SQLite made the database the link led
682  /// to, out of the folder, with no Warning), nor a directory opened: the store runs in memory. A planted `-wal` link
683  /// beside a new file is not followed either (SQLite opens the side files `O_NOFOLLOW`): nothing is made out of the
684  /// folder, and the store keeps its entries.
685  #[cfg(unix)]
686  #[test]
687  fn a_link_is_never_followed() {
688    let dir = tempfile::tempdir().unwrap();
689    let outside = dir.path().join("outside");
690    std::fs::create_dir(&outside).unwrap();
691    let file = dir.path().join("c.db");
692    std::os::unix::fs::symlink(outside.join("o.db"), &file).unwrap();
693    let store = SqliteStore::open(Some(&file), SCHEMA, 1);
694    assert_eq!((store.file(), store.fell_back()), (None, true));
695    let folder = dir.path().join("d.db");
696    std::fs::create_dir(&folder).unwrap();
697    let store = SqliteStore::open(Some(&folder), SCHEMA, 1);
698    assert_eq!((store.file(), store.fell_back()), (None, true));
699    let file = dir.path().join("e.db");
700    std::os::unix::fs::symlink(outside.join("w"), dir.path().join("e.db-wal")).unwrap();
701    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
702    store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (1)", []));
703    assert_eq!(
704      store.read(|conn| conn.query_row("SELECT count(*) FROM t", [], |row| row.get::<_, i64>(0))),
705      Some(1)
706    );
707    drop(store);
708    assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
709  }
710
711  /// A transaction that fails on the file (here a read-only file) runs again in memory, and is told so: a caller
712  /// deciding by the store's state before the call missed the change (issue 995 review: a read-only cache, and a
713  /// second document's image written over the first's `x1.png`). Its close then checks no file ([`WalCheck`]).
714  #[cfg(unix)]
715  #[test]
716  fn a_failed_transaction_runs_again_told_it_is_in_memory() {
717    use std::os::unix::fs::PermissionsExt;
718    let dir = tempfile::tempdir().unwrap();
719    let file = dir.path().join("c.db");
720    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
721    store.immediate(|tx, _| tx.execute("INSERT INTO t(v) VALUES (7)", []));
722    drop(store);
723    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o444)).unwrap();
724    if std::fs::OpenOptions::new().write(true).open(&file).is_ok() {
725      eprintln!("SKIP: a read-only file is writable here (root)");
726      return;
727    }
728    let mut store = SqliteStore::open(Some(&file), SCHEMA, 1);
729    // The close check holds the path with its folder resolved (macOS's `/var` is a link to `/private/var`).
730    let resolved = PathBuf::from(latexml_core::util::pathname::resolved_directory_of(
731      file.to_str().unwrap(),
732    ));
733    assert_eq!(
734      (store.file(), store.wal_check.0.as_deref()),
735      (Some(file.as_path()), Some(resolved.as_path()))
736    );
737    let mut told = Vec::new();
738    store.immediate(|tx, fell_back| {
739      told.push(fell_back);
740      tx.execute("INSERT INTO t(v) VALUES (1)", [])
741    });
742    // The entries the file held are kept in memory, the transaction's own added there once.
743    let kept = store.read(|conn| {
744      conn
745        .prepare("SELECT v FROM t ORDER BY v")?
746        .query_map([], |row| row.get::<_, i64>(0))?
747        .collect::<rusqlite::Result<Vec<_>>>()
748    });
749    assert_eq!(
750      (
751        told,
752        store.file(),
753        store.fell_back(),
754        kept,
755        store.wal_check.0.as_deref()
756      ),
757      (vec![false, true], None, true, Some(vec![1, 7]), None)
758    );
759  }
760}