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