1use std::{
9 cell::{Cell, RefCell},
10 fs,
11 path::PathBuf,
12 rc::Rc,
13 time::UNIX_EPOCH,
14};
15
16use rusqlite::Connection;
17
18use super::{conn::Conn, sync::SyncState};
19use crate::{RepoPath, RepoRoot};
20
21pub const CACHE_DIR: &str = ".sokf/cache";
24pub const STORE_FILE: &str = "sokf.sqlite";
28
29pub const STORE_FORMAT: u32 = 24;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CacheMode {
39 On,
41 Off,
44}
45
46pub struct Cache {
48 conn: Conn,
51 file: Option<PathBuf>,
54 mode: CacheMode,
55 synced_at: Cell<Option<i64>>,
59 now: Cell<i64>,
61 pub(super) state: RefCell<SyncState>,
62 pub(super) hint: RefCell<Option<Vec<RepoPath>>>,
65 pub(super) missed: Cell<bool>,
68 comparison: crate::compare::Session,
71}
72
73impl Cache {
74 pub fn open(root: &RepoRoot, mode: CacheMode) -> Cache {
85 let now = now();
86 let comparison = crate::compare::Session::new(root, mode == CacheMode::On);
87 let version = version(root, &comparison.identity());
88 let (conn, file) = match mode {
89 CacheMode::On => match open_file(root) {
90 Some(conn) => (conn, Some(root.as_path().join(CACHE_DIR).join(STORE_FILE))),
91 None => (memory(), None),
92 },
93 CacheMode::Off => (memory(), None),
94 };
95 let (conn, synced_at, file) = if let Ok((conn, synced_at)) = ensure_schema(conn, &version) {
96 (conn, synced_at, file)
97 } else {
98 let (conn, synced_at) =
99 ensure_schema(memory(), &version).unwrap_or_else(|_| (memory(), None));
100 (conn, synced_at, None)
101 };
102 Cache {
103 conn: Conn::new(conn, Rc::new(Cell::new(0))),
104 file,
105 mode,
106 synced_at: Cell::new(synced_at),
107 now: Cell::new(now),
108 state: RefCell::new(SyncState::default()),
109 hint: RefCell::new(None),
110 missed: Cell::new(false),
111 comparison,
112 }
113 }
114
115 pub(crate) fn comparison(&self) -> &crate::compare::Session {
117 &self.comparison
118 }
119
120 pub fn is_on(&self) -> bool {
122 self.mode == CacheMode::On
123 }
124
125 pub fn is_fresh(&self) -> bool {
128 self.synced_at.get().is_none()
129 }
130
131 pub fn begin_run(&self) {
136 self.now.set(now());
137 self.conn.reset();
138 self.missed.set(false);
139 }
140}
141impl Cache {
144 pub(super) fn conn(&self) -> &Conn {
145 &self.conn
146 }
147
148 pub(super) fn file(&self) -> Option<&std::path::Path> {
151 self.file.as_deref()
152 }
153
154 pub(super) fn synced_at(&self) -> Option<i64> {
155 self.synced_at.get()
156 }
157
158 pub(super) fn set_synced_at(&self, at: i64) {
161 self.synced_at.set(Some(at));
162 }
163
164 pub(super) fn now(&self) -> i64 {
165 self.now.get()
166 }
167}
168
169impl std::fmt::Debug for Cache {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 f.debug_struct("Cache")
172 .field("mode", &self.mode)
173 .field("synced_at", &self.synced_at)
174 .finish_non_exhaustive()
175 }
176}
177
178fn version(root: &RepoRoot, formatter: &str) -> String {
198 let config = fs::read(root.as_path().join(".sokf/config.toml"))
199 .map_or(0, |bytes| crate::source::fnv1a64(&bytes));
200 let manifests = manifests(root);
201 let stores = stores_fingerprint(root, &manifests);
202 let excludes = excludes_fingerprint(root);
203 let texts = texts_fingerprint(root, &manifests);
204 format!(
205 "{}+store.{STORE_FORMAT}+build.{}+config.{config:016x}+stores.{stores:016x}+excludes.{excludes:016x}+texts.{texts:016x}+format.{formatter}",
206 env!("CARGO_PKG_VERSION"),
207 env!("SOKF_BUILD_FINGERPRINT")
208 )
209}
210
211fn excludes_fingerprint(root: &RepoRoot) -> u64 {
216 let mut bytes: Vec<u8> = Vec::new();
217 add_files(
218 root,
219 &crate::config::excludes_files_lenient(root),
220 &mut bytes,
221 );
222 crate::source::fnv1a64(&bytes)
223}
224
225fn texts_fingerprint(root: &RepoRoot, manifests: &[(RepoPath, crate::model::Manifest)]) -> u64 {
233 let mut bytes: Vec<u8> = Vec::new();
234 add_files(root, &crate::config::texts_files_lenient(root), &mut bytes);
235 for (r, m) in manifests {
236 bytes.extend(r.as_str().as_bytes());
237 bytes.push(0);
238 bytes.extend(m.primary_language.as_deref().unwrap_or_default().as_bytes());
239 bytes.push(0);
240 }
241 crate::source::fnv1a64(&bytes)
242}
243
244fn manifests(root: &RepoRoot) -> Vec<(RepoPath, crate::model::Manifest)> {
247 let roots = crate::config::read_lenient(root)
248 .map(|c| c.roots.into_iter().chain(c.registered).collect::<Vec<_>>())
249 .unwrap_or_default();
250 roots
251 .into_iter()
252 .filter_map(|r| {
253 let path = r.join("manifest.sokf.yaml")?;
254 let text = fs::read_to_string(path.to_fs(root)).ok()?;
255 Some((
256 r,
257 crate::model::manifest(crate::yaml::parse(&text, 1), &path),
258 ))
259 })
260 .collect()
261}
262
263fn add_files(root: &RepoRoot, files: &[RepoPath], bytes: &mut Vec<u8>) {
266 for file in files {
267 bytes.extend(file.as_str().as_bytes());
268 bytes.push(0);
269 bytes.extend(fs::read(file.to_fs(root)).unwrap_or_default());
270 bytes.push(0);
271 }
272}
273
274fn stores_fingerprint(root: &RepoRoot, manifests: &[(RepoPath, crate::model::Manifest)]) -> u64 {
284 let mut bytes: Vec<u8> = Vec::new();
285 add_files(
286 root,
287 &crate::config::registry_files_lenient(root),
288 &mut bytes,
289 );
290 let chains = manifests.iter().any(|(_, m)| m.extends.is_some());
295 for (r, m) in manifests {
296 let former: Vec<&str> = m.renamed_from.iter().map(|(f, _)| f.as_str()).collect();
297 let mut fields = vec![
298 r.as_str().to_string(),
299 m.unique.clone().unwrap_or_else(|| "-".into()),
300 m.extends.clone().unwrap_or_else(|| "-".into()),
301 ];
302 if chains {
303 fields.push(m.scope.clone().unwrap_or_default());
304 fields.push(m.name.clone().unwrap_or_default());
305 fields.push(former.join(","));
306 }
307 for f in fields {
308 bytes.extend(f.as_bytes());
309 bytes.push(0);
310 }
311 }
312 crate::source::fnv1a64(&bytes)
313}
314
315fn now() -> i64 {
316 std::time::SystemTime::now()
317 .duration_since(UNIX_EPOCH)
318 .ok()
319 .and_then(|d| i64::try_from(d.as_nanos()).ok())
320 .unwrap_or(0)
321}
322
323pub(crate) fn ensure_dir(root: &RepoRoot) -> std::io::Result<PathBuf> {
327 let dir: PathBuf = root.as_path().join(CACHE_DIR);
328 fs::create_dir_all(&dir)?;
329 let ignore = dir.join(".gitignore");
330 if !ignore.exists() {
331 fs::write(&ignore, "*\n")?;
332 }
333 Ok(dir)
334}
335
336fn open_file(root: &RepoRoot) -> Option<Connection> {
340 let dir = ensure_dir(root).ok()?;
341 if let Ok(entries) = fs::read_dir(&dir) {
344 for entry in entries.flatten() {
345 let path = entry.path();
346 if path.extension().is_some_and(|e| e == "json") {
347 let _ = fs::remove_file(path);
348 }
349 }
350 }
351 let conn = Connection::open(dir.join(STORE_FILE)).ok()?;
352 conn.busy_timeout(std::time::Duration::from_secs(5)).ok()?;
353 conn.pragma_update(None, "journal_mode", "WAL").ok()?;
354 conn.pragma_update(None, "synchronous", "NORMAL").ok()?;
355 Some(conn)
356}
357
358fn memory() -> Connection {
359 Connection::open_in_memory().expect("an in-memory SQLite database opens")
360}
361
362const TABLES: &[(&str, &str)] = &[
367 (
368 "meta",
369 "CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
370 ),
371 (
372 "files",
373 "CREATE TABLE files (path TEXT PRIMARY KEY, kind INTEGER NOT NULL, root INTEGER, \
374 len INTEGER NOT NULL, mtime INTEGER, hash INTEGER, row_hash INTEGER) WITHOUT ROWID",
375 ),
376 (
377 "dirs",
378 "CREATE TABLE dirs (path TEXT PRIMARY KEY, root INTEGER NOT NULL)",
379 ),
380 (
381 "documents",
382 "CREATE TABLE documents (path TEXT PRIMARY KEY, store INTEGER NOT NULL, id TEXT, \
383 type TEXT, title TEXT, description TEXT, broken INTEGER NOT NULL, \
384 visible_hash INTEGER NOT NULL, scalars TEXT NOT NULL)",
385 ),
386 (
387 "outputs",
388 "CREATE TABLE outputs (path TEXT PRIMARY KEY, findings BLOB NOT NULL, \
389 has_findings INTEGER NOT NULL)",
390 ),
391 (
392 "queries",
393 "CREATE TABLE queries (id INTEGER PRIMARY KEY, key TEXT NOT NULL UNIQUE)",
394 ),
395 (
396 "deps",
397 "CREATE TABLE deps (reader INTEGER NOT NULL, query INTEGER NOT NULL, \
398 PRIMARY KEY (reader, query))",
399 ),
400 (
401 "citations",
402 "CREATE TABLE citations (target TEXT NOT NULL, slug TEXT, source TEXT NOT NULL, \
403 source_type TEXT NOT NULL, rel TEXT, line INTEGER NOT NULL, include INTEGER NOT NULL, \
404 supersedes INTEGER NOT NULL, retired INTEGER NOT NULL, declared INTEGER NOT NULL)",
405 ),
406 (
407 "probes",
408 "CREATE TABLE probes (path TEXT PRIMARY KEY, exists_ INTEGER NOT NULL)",
409 ),
410 (
411 "assets",
412 "CREATE TABLE assets (store INTEGER NOT NULL, asset TEXT NOT NULL, sidecar TEXT)",
413 ),
414 (
415 "ids",
416 "CREATE TABLE ids (store INTEGER NOT NULL, id TEXT NOT NULL, path TEXT NOT NULL, \
417 PRIMARY KEY (store, id, path))",
418 ),
419 (
420 "schemas",
421 "CREATE TABLE schemas (path TEXT PRIMARY KEY, store INTEGER NOT NULL, \
422 key TEXT NOT NULL, hash INTEGER NOT NULL, globs TEXT NOT NULL, \
423 asset_globs TEXT NOT NULL, uses TEXT NOT NULL, line INTEGER NOT NULL, \
424 archived TEXT NOT NULL)",
425 ),
426 (
427 "formats",
428 "CREATE TABLE formats (name TEXT PRIMARY KEY, hash INTEGER NOT NULL)",
429 ),
430 (
431 "stores",
432 "CREATE TABLE stores (root INTEGER PRIMARY KEY, identity TEXT NOT NULL, \
433 former TEXT NOT NULL)",
434 ),
435 (
436 "additional",
437 "CREATE TABLE additional (path TEXT PRIMARY KEY, schema TEXT NOT NULL)",
438 ),
439 (
440 "edges",
441 "CREATE TABLE edges (source TEXT NOT NULL, kind INTEGER NOT NULL, written TEXT NOT NULL, \
442 target TEXT NOT NULL, missing INTEGER NOT NULL, rel TEXT NOT NULL, region TEXT, \
443 note TEXT)",
444 ),
445 (
446 "keys",
447 "CREATE TABLE keys (path TEXT NOT NULL, key TEXT NOT NULL, slug TEXT NOT NULL, \
448 line INTEGER NOT NULL, heading_slug TEXT, holds_anchor INTEGER NOT NULL, \
449 scope TEXT NOT NULL, knowledge INTEGER NOT NULL, rule_id TEXT)",
450 ),
451 (
452 "anchors",
453 "CREATE TABLE anchors (path TEXT NOT NULL, slug TEXT NOT NULL)",
454 ),
455 (
456 "markers",
457 "CREATE TABLE markers (path TEXT NOT NULL, line INTEGER NOT NULL, \
458 kind INTEGER NOT NULL, rel TEXT NOT NULL, target TEXT NOT NULL)",
459 ),
460 (
461 "plans",
462 "CREATE TABLE plans (path TEXT NOT NULL, target TEXT NOT NULL)",
463 ),
464];
465
466const INDEXES: &[&str] = &[
469 "CREATE INDEX ids_by_path ON ids (path)",
470 "CREATE INDEX keys_by_path ON keys (path)",
471 "CREATE INDEX keys_by_slug ON keys (slug)",
472 "CREATE INDEX anchors_by_path ON anchors (path)",
473 "CREATE INDEX anchors_by_slug ON anchors (slug)",
474 "CREATE INDEX documents_by_type ON documents (store, type)",
475 "CREATE INDEX deps_by_query ON deps (query)",
476 "CREATE INDEX citations_by_target ON citations (target)",
477 "CREATE INDEX citations_by_source ON citations (source)",
478 "CREATE INDEX edges_by_source ON edges (source)",
479 "CREATE INDEX edges_by_target ON edges (target)",
480 "CREATE INDEX outputs_with_findings ON outputs (has_findings)",
481 "CREATE INDEX markers_by_path ON markers (path)",
482 "CREATE INDEX markers_by_target ON markers (target)",
483 "CREATE INDEX plans_by_path ON plans (path)",
484];
485fn ensure_schema(conn: Connection, version: &str) -> rusqlite::Result<(Connection, Option<i64>)> {
492 let stored: Option<String> = conn
493 .query_row("SELECT value FROM meta WHERE key = 'version'", [], |r| {
494 r.get(0)
495 })
496 .ok();
497 if stored.as_deref() == Some(version) {
498 let synced_at: Option<i64> = conn
499 .query_row("SELECT value FROM meta WHERE key = 'synced_at'", [], |r| {
500 r.get::<_, String>(0)
501 })
502 .ok()
503 .and_then(|s| s.parse().ok());
504 return Ok((conn, synced_at));
505 }
506 conn.execute_batch("BEGIN IMMEDIATE")?;
507 for (name, _) in TABLES.iter().rev() {
508 conn.execute_batch(&format!("DROP TABLE IF EXISTS {name}"))?;
509 }
510 for (_, ddl) in TABLES {
511 conn.execute_batch(ddl)?;
512 }
513 for ddl in INDEXES {
514 conn.execute_batch(ddl)?;
515 }
516 conn.execute(
517 "INSERT INTO meta (key, value) VALUES ('version', ?1)",
518 [version],
519 )?;
520 conn.execute_batch("COMMIT")?;
521 Ok((conn, None))
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 fn temp(name: &str) -> PathBuf {
529 crate::test_support::fresh_dir(&format!("store-{name}"))
530 }
531
532 #[test]
536 fn on_opens_a_file_with_a_gitignore_and_off_writes_nothing() {
537 let dir = temp("open");
538 let root = RepoRoot::new(dir.clone());
539 let cache = Cache::open(&root, CacheMode::On);
540 assert!(cache.is_on());
541 assert!(dir.join(CACHE_DIR).join(STORE_FILE).exists());
542 assert_eq!(
543 fs::read_to_string(dir.join(CACHE_DIR).join(".gitignore")).unwrap(),
544 "*\n"
545 );
546 assert_eq!(cache.synced_at(), None);
547 drop(cache);
548 let off_dir = temp("off");
549 let off = Cache::open(&RepoRoot::new(off_dir.clone()), CacheMode::Off);
550 assert!(!off.is_on());
551 assert!(!off_dir.join(CACHE_DIR).exists());
552 fs::remove_dir_all(&dir).unwrap();
553 fs::remove_dir_all(&off_dir).unwrap();
554 }
555
556 #[test]
560 fn a_store_of_another_version_is_rebuilt_silently() {
561 let dir = temp("version");
562 let root = RepoRoot::new(dir.clone());
563 {
564 let cache = Cache::open(&root, CacheMode::On);
565 cache
566 .conn()
567 .execute_batch(
568 "UPDATE meta SET value = '0.0.0+store.0' WHERE key = 'version'; \
569 INSERT INTO meta (key, value) VALUES ('synced_at', '5'); \
570 INSERT INTO files (path, kind, len) VALUES ('/a.md', 3, 1)",
571 )
572 .unwrap();
573 }
574 let cache = Cache::open(&root, CacheMode::On);
575 assert_eq!(cache.synced_at(), None);
576 assert!(cache.is_fresh());
577 let rows: i64 = cache
578 .conn()
579 .query_row("SELECT count(*) FROM files", [], |r| r.get(0))
580 .unwrap();
581 assert_eq!(rows, 0);
582 let version: String = cache
583 .conn()
584 .query_row("SELECT value FROM meta WHERE key = 'version'", [], |r| {
585 r.get(0)
586 })
587 .unwrap();
588 assert_eq!(version, super::version(&root, "none"));
589 assert!(
591 version.contains(&format!("+build.{}+", env!("SOKF_BUILD_FINGERPRINT"))),
592 "{version}"
593 );
594 cache
598 .conn()
599 .execute_batch("INSERT INTO meta (key, value) VALUES ('synced_at', '5')")
600 .unwrap();
601 drop(cache);
602 assert!(!Cache::open(&root, CacheMode::On).is_fresh());
603 fs::create_dir_all(dir.join(".sokf")).unwrap();
604 fs::write(dir.join(".sokf/config.toml"), "roots = [\"/docs\"]\n").unwrap();
605 assert!(Cache::open(&root, CacheMode::On).is_fresh());
606 fs::remove_dir_all(&dir).unwrap();
607 }
608
609 #[test]
611 fn a_change_of_the_files_of_excludes_d_rebuilds_the_store() {
612 let dir = temp("excludes-d");
613 let root = RepoRoot::new(dir.clone());
614 let fresh_after = |change: &dyn Fn()| {
617 Cache::open(&root, CacheMode::On)
618 .conn()
619 .execute_batch("INSERT OR REPLACE INTO meta (key, value) VALUES ('synced_at', '5')")
620 .unwrap();
621 change();
622 Cache::open(&root, CacheMode::On).is_fresh()
623 };
624 let file = ".sokf/excludes.d/pakf/@acme/tool/excludes.toml";
625 assert!(!fresh_after(&|| ()));
626 assert!(fresh_after(&|| {
627 crate::test_support::write(&dir, file, "exclude = [\"/a/**\"]\n");
628 }));
629 assert!(fresh_after(&|| {
630 crate::test_support::write(&dir, file, "exclude = [\"/b/**\"]\n");
631 }));
632 assert!(fresh_after(&|| fs::remove_file(dir.join(file)).unwrap()));
633 fs::remove_dir_all(&dir).unwrap();
634 }
635
636 #[test]
639 fn a_store_that_does_not_open_falls_back_to_memory() {
640 let dir = temp("broken");
641 fs::write(dir.join(".sokf"), "not a directory").unwrap();
643 let root = RepoRoot::new(dir.clone());
644 let cache = Cache::open(&root, CacheMode::On);
645 assert!(cache.is_on());
646 assert_eq!(cache.synced_at(), None);
647 let rows: i64 = cache
648 .conn()
649 .query_row("SELECT count(*) FROM files", [], |r| r.get(0))
650 .unwrap();
651 assert_eq!(rows, 0);
652 fs::remove_dir_all(&dir).unwrap();
653 }
654
655 #[test]
656 fn a_store_that_is_not_a_database_is_rebuilt() {
657 let dir = temp("garbage");
658 let cache_dir = dir.join(CACHE_DIR);
659 fs::create_dir_all(&cache_dir).unwrap();
660 fs::write(
661 cache_dir.join(STORE_FILE),
662 "not sqlite at all, and long enough to matter",
663 )
664 .unwrap();
665 let root = RepoRoot::new(dir.clone());
666 let cache = Cache::open(&root, CacheMode::On);
667 assert!(cache.is_on());
668 assert_eq!(cache.synced_at(), None);
669 assert!(format!("{cache:?}").starts_with("Cache"));
670 fs::remove_dir_all(&dir).unwrap();
671 }
672}