Skip to main content

rightkit_document_workspace/
store.rs

1//! The document workspace store: recent files, pinned files and folders, per-document view
2//! state and the open-tab session, in one SQLite file the host app places.
3
4use std::path::Path;
5#[cfg(test)]
6use std::path::PathBuf;
7use std::sync::Mutex;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use rightkit_db::rusqlite::{self, Connection};
11use rightkit_db::{
12    DbError, DbOptions, Degraded, IntegrityCheck, MigrateOptions, Migration, OpenOrDegrade,
13    QuarantineStamp, RecoveryPolicy, SidecarPolicy, VersionStorage,
14};
15use serde::Serialize;
16
17#[derive(Debug, Serialize, Clone)]
18pub struct FileEntry {
19    pub path: String,
20    pub display_name: String,
21    pub format: String,
22    /// Unix epoch seconds of the last open (recent_files.opened_at). 0 for rows written by a
23    /// schema that predates the column — the renderer treats missing values as "no time shown".
24    pub opened_at: i64,
25}
26
27/// One row of `pinned_files` for `list_pins`. `kind` is "file" (openable documents) or
28/// "dir" (explorer sidebar pinned folders); `format` is the document format for files
29/// and the literal "dir" for directories, which have no document format.
30#[derive(Debug, Serialize, Clone)]
31pub struct PinEntry {
32    pub path: String,
33    pub display_name: String,
34    pub format: String,
35    pub kind: String,
36}
37
38#[derive(Debug, Serialize, Clone, Default)]
39pub struct ViewState {
40    pub last_view: Option<String>,
41    /// Per-format view metadata as a JSON string (text scroll, PDF page/zoom/fit). Opaque to the
42    /// backend — the renderer owns the shape.
43    pub view_meta: Option<String>,
44}
45
46pub struct Db(pub Mutex<Connection>);
47
48fn now() -> i64 {
49    SystemTime::now()
50        .duration_since(UNIX_EPOCH)
51        .map(|d| d.as_secs() as i64)
52        .unwrap_or(0)
53}
54
55impl Db {
56    /// Pragmas, WAL fallback, the `quick_check` and quarantine all come from `rightkit-db`; this keeps
57    /// the store-specific part: the migration list.
58    fn options(path: &Path) -> DbOptions {
59        let mut options = DbOptions::new(path);
60        // `quick_check` rather than `integrity_check`: this runs on the startup path before the window
61        // is shown, and `integrity_check` also cross-references every index (O(database size)).
62        // `quick_check` still catches the structural page corruption that makes a file unsafe to serve.
63        options.integrity = IntegrityCheck::Quick;
64        options
65    }
66
67    /// The migration list, in order. Versions are contiguous from 1; the app has no shipped data, so
68    /// version 1 is the full current schema.
69    fn migrations() -> [Migration; 1] {
70        [Migration::sql(
71            1,
72            "init",
73            include_str!("../data/migrations/0001_init.sql"),
74        )]
75    }
76
77    /// Migration settings. The shared migrator records versions in the store's
78    /// `_migrations(version, applied_at)` table. Each migration and its version row commit together or
79    /// not at all.
80    fn migrate_options() -> MigrateOptions {
81        MigrateOptions {
82            version_storage: VersionStorage::version_table("_migrations"),
83            // A copy `<db>.pre-v<target>.bak` is written beside the database before a migration
84            // changes it, so a failed or unwanted upgrade never costs the previous data.
85            backup: true,
86            optimize_after: false,
87            // A database written by a newer build keeps opening, as before.
88            forward_compatible: Some(|_| true),
89            ..Default::default()
90        }
91    }
92
93    /// An unreadable file (failed open-time `quick_check`, SQLITE_CORRUPT, SQLITE_NOTADB, including
94    /// when it surfaces during migration) is quarantined as `workspace.db.corrupt-<unix-seconds>`
95    /// and its `-wal`, `-shm` and `-journal` sidecars are renamed beside it under the same suffix,
96    /// so every original byte is kept and no stale WAL is replayed into the replacement. Transient
97    /// conditions (busy, locked, permission) are never quarantined.
98    ///
99    /// There is deliberately no in-memory fallback: a store that does not persist would let the
100    /// user keep working and lose everything at quit. When the database cannot be opened the open
101    /// fails and the app reports it and exits.
102    fn recovery_policy() -> RecoveryPolicy {
103        RecoveryPolicy {
104            quarantine_corrupt: true,
105            quarantine_stamp: QuarantineStamp::Seconds,
106            sidecars: SidecarPolicy::RenameSidecars,
107            allow_in_memory_fallback: false,
108            ..Default::default()
109        }
110    }
111
112    /// `open()` reports `rusqlite::Error`; keep the underlying SQLite failure where there is one.
113    fn to_sqlite(err: DbError) -> rusqlite::Error {
114        match err {
115            DbError::Sqlite(err) | DbError::MigrationFailed { source: err, .. } => err,
116            other => rusqlite::Error::SqliteFailure(
117                rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_ERROR),
118                Some(other.to_string()),
119            ),
120        }
121    }
122
123    /// `PRAGMA journal_mode=WAL` reports the mode it actually adopted rather than failing. `rightkit-db`
124    /// falls back to a rollback journal on a filesystem that can't do WAL (network shares, some FUSE
125    /// mounts); read the value back so that degradation stays visible in logs. Deliberately non-fatal:
126    /// the database is still correct without WAL, just less concurrent.
127    fn verify_wal(conn: &Connection) {
128        match rightkit_db::journal_mode(conn) {
129            Ok(mode) if mode.eq_ignore_ascii_case("wal") => {}
130            Ok(mode) => eprintln!(
131                "rightkit-document-workspace: database is running in {mode} journal mode, not WAL; concurrent reads during writes may block"
132            ),
133            Err(err) => eprintln!("rightkit-document-workspace: could not read back journal_mode: {err}"),
134        }
135    }
136
137    /// Open the on-disk database at `path`, recovering from corruption rather than degrading permanently.
138    ///
139    /// A single corrupt file would otherwise be terminal: opening fails on every launch. An
140    /// unreadable file is quarantined (original bytes and sidecars kept, see `recovery_policy`) and
141    /// a fresh persistent database is created at the same path; the returned `Some(Degraded)` has
142    /// `quarantined` set so the UI can tell the user where the old file went (`persistence_status`).
143    ///
144    /// `Err` when the database cannot be opened at all (locked or unwritable folder, a database
145    /// written by a newer incompatible build, an unfinished earlier quarantine). The caller reports
146    /// it and exits; the session never continues on a store that does not persist.
147    pub fn open_path(path: &Path) -> rusqlite::Result<(Self, Option<Degraded>)> {
148        let OpenOrDegrade { conn, degraded, .. } = Self::options(path)
149            .open_writer_migrated_or_degrade(
150                &Self::migrations(),
151                &Self::migrate_options(),
152                Self::recovery_policy(),
153            )
154            .map_err(Self::to_sqlite)?;
155        if let Some(degraded) = &degraded {
156            // The policy refuses an in-memory store, so this cannot happen; if it ever did, a
157            // volatile store must still never be served.
158            if degraded.in_memory {
159                return Err(rusqlite::Error::SqliteFailure(
160                    rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_CANTOPEN),
161                    Some(format!(
162                        "refusing an in-memory database: {}",
163                        degraded.reason
164                    )),
165                ));
166            }
167            if let Some(aside) = &degraded.quarantined {
168                eprintln!(
169                    "rightkit-document-workspace: database was unreadable ({}); kept the original at {} and started a fresh one",
170                    degraded.reason,
171                    aside.display()
172                );
173            }
174        }
175        Self::verify_wal(&conn);
176        Ok((Db(Mutex::new(conn)), degraded))
177    }
178
179    /// Lock the connection, recovering the guard if a prior holder panicked (mutex poisoning). Release
180    /// builds use `panic = "abort"` so poisoning can't occur there, but debug builds must not turn one
181    /// panicked query into an app-wide cascade of `.unwrap()` crashes on every later DB call.
182    fn conn(&self) -> std::sync::MutexGuard<'_, Connection> {
183        self.0
184            .lock()
185            .unwrap_or_else(|poisoned| poisoned.into_inner())
186    }
187
188    pub fn list_recent(&self, limit: i64) -> rusqlite::Result<Vec<FileEntry>> {
189        let conn = self.conn();
190        let mut stmt = conn.prepare(
191            "SELECT path, display_name, format, opened_at FROM recent_files ORDER BY opened_at DESC LIMIT ?1",
192        )?;
193        let rows = stmt
194            .query_map([limit], |r| {
195                Ok(FileEntry {
196                    path: r.get(0)?,
197                    display_name: r.get(1)?,
198                    format: r.get(2)?,
199                    opened_at: r.get(3)?,
200                })
201            })?
202            .collect::<rusqlite::Result<Vec<_>>>()?;
203        Ok(rows)
204    }
205
206    pub fn clear_recent(&self) -> rusqlite::Result<()> {
207        self.conn().execute("DELETE FROM recent_files", [])?;
208        Ok(())
209    }
210
211    pub fn is_pinned(&self, path: &str) -> rusqlite::Result<bool> {
212        let conn = self.conn();
213        let count: i64 = conn.query_row(
214            "SELECT COUNT(*) FROM pinned_files WHERE path = ?1",
215            [path],
216            |r| r.get(0),
217        )?;
218        Ok(count > 0)
219    }
220
221    pub fn toggle_pin(
222        &self,
223        path: &str,
224        display_name: &str,
225        format: &str,
226    ) -> rusqlite::Result<bool> {
227        self.toggle_pin_kind(path, display_name, format, "file")
228    }
229
230    /// Pin/unpin a directory. Directories have no document format, so `format` stores the
231    /// literal "dir" — keeping the NOT NULL column honest and mirroring what `list_pins`
232    /// reports for these rows (`kind` distinguishes them either way).
233    pub fn toggle_pin_dir(&self, path: &str, display_name: &str) -> rusqlite::Result<bool> {
234        self.toggle_pin_kind(path, display_name, "dir", "dir")
235    }
236
237    fn toggle_pin_kind(
238        &self,
239        path: &str,
240        display_name: &str,
241        format: &str,
242        kind: &str,
243    ) -> rusqlite::Result<bool> {
244        // Hold ONE lock across the check + write so two concurrent toggles can't both INSERT (a
245        // PRIMARY KEY violation) or both DELETE. Inlined (not self.is_pinned) because std::Mutex is
246        // not reentrant — calling is_pinned() here would re-lock and deadlock.
247        let conn = self.conn();
248        let pinned: i64 = conn.query_row(
249            "SELECT COUNT(*) FROM pinned_files WHERE path = ?1",
250            [path],
251            |r| r.get(0),
252        )?;
253        if pinned > 0 {
254            conn.execute("DELETE FROM pinned_files WHERE path = ?1", [path])?;
255            Ok(false)
256        } else {
257            let next: i64 = conn.query_row(
258                "SELECT COALESCE(MAX(sort_order), 0) + 1 FROM pinned_files",
259                [],
260                |r| r.get(0),
261            )?;
262            conn.execute(
263                "INSERT INTO pinned_files (path, display_name, format, sort_order, pinned_at, kind) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
264                rusqlite::params![path, display_name, format, next, now(), kind],
265            )?;
266            Ok(true)
267        }
268    }
269
270    /// All pins in stored pin order (the `sort_order` sequence `toggle_pin*` assigns).
271    /// The renderer groups rows into pinned folders then files — the DB does not
272    /// re-sort, so pins stay in the order the user created them.
273    pub fn list_pins(&self) -> rusqlite::Result<Vec<PinEntry>> {
274        let conn = self.conn();
275        let mut stmt = conn.prepare(
276            "SELECT path, display_name, format, kind FROM pinned_files ORDER BY sort_order ASC",
277        )?;
278        let rows = stmt
279            .query_map([], |r| {
280                Ok(PinEntry {
281                    path: r.get(0)?,
282                    display_name: r.get(1)?,
283                    format: r.get(2)?,
284                    kind: r.get(3)?,
285                })
286            })?
287            .collect::<rusqlite::Result<Vec<_>>>()?;
288        Ok(rows)
289    }
290
291    pub fn record_recent(
292        &self,
293        path: &str,
294        display_name: &str,
295        format: &str,
296    ) -> rusqlite::Result<()> {
297        let conn = self.conn();
298        // Record-then-prune is one unit: a reader must never observe the table above its cap, and a
299        // failed prune must not leave the new row committed on its own.
300        let tx = rightkit_db::write_txn_unchecked(&conn).map_err(Self::to_sqlite)?;
301        tx.execute(
302            "INSERT INTO recent_files (path, display_name, format, opened_at) VALUES (?1, ?2, ?3, ?4)
303             ON CONFLICT(path) DO UPDATE SET opened_at = excluded.opened_at, display_name = excluded.display_name",
304            rusqlite::params![path, display_name, format, now()],
305        )?;
306        // Prune to the 200 most-recent rows so the table never grows without bound.
307        tx.execute(
308            "DELETE FROM recent_files WHERE path NOT IN (
309                SELECT path FROM recent_files ORDER BY opened_at DESC LIMIT 200)",
310            [],
311        )?;
312        tx.commit()
313    }
314
315    pub fn save_view_state(
316        &self,
317        path: &str,
318        last_view: &str,
319        view_meta: Option<&str>,
320        display_name: &str,
321        format: &str,
322    ) -> rusqlite::Result<()> {
323        let conn = self.conn();
324        conn.execute(
325            "INSERT INTO recent_files (path, display_name, format, opened_at, last_view, view_meta)
326             VALUES (?1, ?4, ?5, ?6, ?2, ?3)
327             ON CONFLICT(path) DO UPDATE SET last_view = excluded.last_view, view_meta = excluded.view_meta",
328            rusqlite::params![path, last_view, view_meta, display_name, format, now()],
329        )?;
330        Ok(())
331    }
332
333    /// Restored view state is advisory: a document must still open when it can't be read, so this
334    /// falls back to the default rather than propagating. The caller (`read_document`) uses `?`, so
335    /// returning an error here would turn a transient database lock into a failure to open a file the
336    /// database has no say over. A missing row is the ordinary case for a first-time open and stays
337    /// silent; anything else is a real fault and is logged instead of vanishing.
338    pub fn view_state(&self, path: &str) -> rusqlite::Result<ViewState> {
339        let conn = self.conn();
340        let st = conn
341            .query_row(
342                "SELECT last_view, view_meta FROM recent_files WHERE path = ?1",
343                [path],
344                |r| {
345                    Ok(ViewState {
346                        last_view: r.get(0)?,
347                        view_meta: r.get::<_, Option<String>>(1)?,
348                    })
349                },
350            )
351            .unwrap_or_else(|err| {
352                if !matches!(err, rusqlite::Error::QueryReturnedNoRows) {
353                    eprintln!(
354                        "rightkit-document-workspace: could not read view state for {path}: {err}"
355                    );
356                }
357                ViewState::default()
358            });
359        Ok(st)
360    }
361
362    /// Replace the saved session atomically. The clear-then-insert pair must not run in autocommit:
363    /// a failure partway through the loop would otherwise leave the previous session already deleted
364    /// and the new one half-written, so the next launch would restore a truncated set of tabs (or
365    /// none) with nothing reporting that anything was lost.
366    pub fn save_session(&self, tabs: &[(&str, bool)]) -> rusqlite::Result<()> {
367        let conn = self.conn();
368        let tx = rightkit_db::write_txn_unchecked(&conn).map_err(Self::to_sqlite)?;
369        tx.execute("DELETE FROM session_tabs", [])?;
370        {
371            let mut stmt = tx.prepare(
372                "INSERT INTO session_tabs (sort_order, path, active) VALUES (?1, ?2, ?3)",
373            )?;
374            for (i, (path, active)) in tabs.iter().enumerate() {
375                stmt.execute(rusqlite::params![i as i64, path, *active as i64])?;
376            }
377        }
378        tx.commit()
379    }
380
381    pub fn load_session(&self) -> rusqlite::Result<Vec<(String, bool)>> {
382        let conn = self.conn();
383        let mut stmt =
384            conn.prepare("SELECT path, active FROM session_tabs ORDER BY sort_order ASC")?;
385        let rows = stmt
386            .query_map([], |r| {
387                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? != 0))
388            })?
389            .collect::<rusqlite::Result<Vec<_>>>()?;
390        Ok(rows)
391    }
392
393    pub fn clear_session(&self) -> rusqlite::Result<()> {
394        let conn = self.conn();
395        conn.execute("DELETE FROM session_tabs", [])?;
396        Ok(())
397    }
398
399    /// Privacy purge: delete every stored document path (recents with their view state, the saved
400    /// session tabs, and pins) in one transaction, then overwrite freed pages (`secure_delete`) and
401    /// truncate the WAL so no path string survives in the database file or its sidecar.
402    pub fn purge_user_paths(&self) -> rusqlite::Result<()> {
403        let mut conn = self.conn();
404        conn.execute_batch("PRAGMA secure_delete = ON;")?;
405        let tx = rightkit_db::write_txn(&mut conn).map_err(Self::to_sqlite)?;
406        tx.execute("DELETE FROM recent_files", [])?;
407        tx.execute("DELETE FROM session_tabs", [])?;
408        tx.execute("DELETE FROM pinned_files", [])?;
409        tx.commit()?;
410        // `secure_delete` only blanks cells deleted now; pages freed earlier (migrations, older
411        // deletes made before the pragma) still hold path bytes on the freelist. VACUUM rewrites
412        // the whole file, dropping every freed page, so nothing stale survives.
413        // `sqlite_stat4` keeps sample index keys (here: stored paths) from an earlier ANALYZE; VACUUM
414        // copies them over. Re-analysing the purged tables replaces those samples first.
415        conn.execute_batch("ANALYZE recent_files; ANALYZE session_tabs; ANALYZE pinned_files;")?;
416        conn.execute_batch("VACUUM;")?;
417        // A reader that still holds the log keeps it from being truncated, and the path strings the
418        // purge promises to remove would stay in the `-wal` file. `busy != 0` means the checkpoint
419        // did not complete, so the purge did not either.
420        let status = rightkit_db::checkpoint_truncate(&conn).map_err(Self::to_sqlite)?;
421        if status.busy != 0 {
422            return Err(rusqlite::Error::SqliteFailure(
423                rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_BUSY),
424                Some("purge incomplete: the write-ahead log could not be truncated".to_string()),
425            ));
426        }
427        Ok(())
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use std::sync::atomic::{AtomicU64, Ordering};
435
436    struct TempDir(PathBuf);
437
438    impl TempDir {
439        fn new() -> Self {
440            static N: AtomicU64 = AtomicU64::new(0);
441            let dir = std::env::temp_dir().join(format!(
442                "rightkit-document-workspace-{}-{}",
443                std::process::id(),
444                N.fetch_add(1, Ordering::SeqCst)
445            ));
446            std::fs::create_dir_all(&dir).unwrap();
447            Self(dir)
448        }
449    }
450
451    impl Drop for TempDir {
452        fn drop(&mut self) {
453            let _ = std::fs::remove_dir_all(&self.0);
454        }
455    }
456
457    /// The open and purge contracts that have no E2E surface, in one case: (1) an unreadable
458    /// database is moved aside with its sidecars and every original byte kept, and the replacement
459    /// is a persistent file store, never in-memory (the upgrade journey proves the same through
460    /// the UI but not the sidecar bytes); (2) a store that cannot be opened is an error and the
461    /// blocking entry is left untouched, never an in-memory session; (3) a reader that still holds
462    /// the log keeps the purge from truncating it, and the purge says so instead of claiming no
463    /// path bytes remain (waits out the 5 s busy timeout).
464    #[test]
465    fn open_never_falls_back_to_memory_and_purge_reports_incomplete() {
466        // (1) Quarantine.
467        let dir = TempDir::new();
468        let path = dir.0.join("workspace.db");
469        let garbage = vec![0x5a_u8; 4096];
470        let wal = b"stale wal bytes that must be kept".to_vec();
471        std::fs::write(&path, &garbage).unwrap();
472        std::fs::write(dir.0.join("workspace.db-wal"), &wal).unwrap();
473        let (db, degraded) = Db::open_path(&path).expect("a corrupt store is replaced, not fatal");
474        let degraded = degraded.expect("a quarantine is reported");
475        assert!(!degraded.in_memory);
476        let aside = degraded.quarantined.expect("the original moved aside");
477        assert!(aside
478            .file_name()
479            .and_then(|n| n.to_str())
480            .is_some_and(|n| n.starts_with("workspace.db.corrupt-")));
481        assert_eq!(std::fs::read(&aside).unwrap(), garbage);
482        let mut aside_wal = aside.clone().into_os_string();
483        aside_wal.push("-wal");
484        assert_eq!(std::fs::read(PathBuf::from(aside_wal)).unwrap(), wal);
485        db.record_recent("/doc.txt", "doc.txt", "text").unwrap();
486        assert_eq!(db.list_recent(10).unwrap().len(), 1);
487        assert!(path.is_file());
488
489        // (2) Refusal: the database path is a directory, so it is not quarantined as corrupt.
490        let blocked = TempDir::new();
491        let blocking = blocked.0.join("workspace.db");
492        std::fs::create_dir_all(&blocking).unwrap();
493        assert!(Db::open_path(&blocking).is_err());
494        assert!(blocking.is_dir(), "the blocking entry is left untouched");
495
496        // (3) Purge honesty.
497        let purge_dir = TempDir::new();
498        let purge_path = purge_dir.0.join("workspace.db");
499        let (db, degraded) = Db::open_path(&purge_path).unwrap();
500        assert!(degraded.is_none());
501        db.record_recent("/secret/doc.txt", "doc.txt", "text")
502            .unwrap();
503        let reader = rightkit_db::open_read_only(&purge_path).unwrap();
504        reader
505            .execute_batch("BEGIN; SELECT COUNT(*) FROM recent_files;")
506            .unwrap();
507        let error = db
508            .purge_user_paths()
509            .expect_err("a held reader blocks the truncate");
510        assert!(error.to_string().contains("purge incomplete"), "{error}");
511        drop(reader);
512        db.purge_user_paths()
513            .expect("the purge completes once the reader is gone");
514    }
515}