Skip to main content

sokf_core/cache/
store.rs

1//! This module opens the store. The store is one SQLite file under
2//! `/.sokf/cache/`, and with `--no-cache` the module creates the same tables
3//! in memory instead. When the store file does not open, the module uses a
4//! store in memory. When the store is absent or has another version or
5//! format, the module builds it again. Neither case prints a message
6//! (CACHE-1_AC-7).
7
8use 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
21// sokf:begin cache-dir
22/// `CACHE_DIR` is the cache directory, relative to the repository root.
23pub const CACHE_DIR: &str = ".sokf/cache";
24// sokf:end cache-dir
25
26/// `STORE_FILE` is the name of the store file inside the cache directory.
27pub const STORE_FILE: &str = "sokf.sqlite";
28
29/// `STORE_FORMAT` is the version of the store's tables. Raise it whenever a
30/// table changes. A change to what a check finds needs no raise, because the
31/// fingerprint of the build in the version changes with the code
32/// (CACHE-1_AC-7).
33pub const STORE_FORMAT: u32 = 24;
34
35// sokf:begin cache
36/// `CacheMode` sets whether a run reads and writes the cache.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum CacheMode {
39    /// `On` reads and writes the cache.
40    On,
41    /// `Off` neither reads nor writes the cache (`--no-cache`): the run uses
42    /// the same tables, in memory.
43    Off,
44}
45
46/// `Cache` holds the store and the state of this run's sync.
47pub struct Cache {
48    /// `conn` is the store's connection. It counts the statements that the
49    /// run makes.
50    conn: Conn,
51    /// `file` is the path of the store file, or `None` when the store is in
52    /// memory.
53    file: Option<PathBuf>,
54    mode: CacheMode,
55    /// `synced_at` is the start of the last run's sync, as the store recorded
56    /// it, or `None` for a new store. A commit of this cache sets it, so that
57    /// a second run on the same cache sees the first.
58    synced_at: Cell<Option<i64>>,
59    /// `now` is the start of this run, in nanoseconds since the Unix epoch.
60    now: Cell<i64>,
61    pub(super) state: RefCell<SyncState>,
62    /// `hint` holds the paths that a caller reported as changed. The sync
63    /// checks only these paths on disk.
64    pub(super) hint: RefCell<Option<Vec<RepoPath>>>,
65    /// `missed` records that this run, with a hint, read a file that it took
66    /// from the store and found the file removed.
67    pub(super) missed: Cell<bool>,
68    /// `comparison` holds what the runs on this cache share of the
69    /// comparison: same-same's comparer and its cache.
70    comparison: crate::compare::Session,
71}
72
73impl Cache {
74    /// `open` opens the store under `root`, or opens it in memory for `Off`.
75    /// When the store file does not open, the run uses a store in memory. When
76    /// the store is of another version, format, or configuration, `open`
77    /// replaces it with an empty one. Neither case prints a message.
78    // sokf-implements: CACHE-2_AC-4
79    // sokf-implements: CACHE-1_AC-6
80    // sokf-implements: CACHE-1_AC-7
81    // sokf-implements: CACHE-1_AC-8
82    // sokf-implements: CACHE-1_AC-10
83    // sokf-implements: CLI-1_AC-13
84    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    /// `comparison` returns the comparison's session of this cache.
116    pub(crate) fn comparison(&self) -> &crate::compare::Session {
117        &self.comparison
118    }
119
120    /// `is_on` returns whether the cache is on.
121    pub fn is_on(&self) -> bool {
122        self.mode == CacheMode::On
123    }
124
125    /// `is_fresh` returns true when the store has no record of an earlier
126    /// sync, because it is new, rebuilt, or in memory.
127    pub fn is_fresh(&self) -> bool {
128        self.synced_at.get().is_none()
129    }
130
131    /// `begin_run` starts a run on this cache: it takes the time of the run's
132    /// start and sets the count of statements to zero, so that the counts
133    /// of `stats` cover this run alone (CACHE-3_AC-4).
134    // sokf-implements: CACHE-3_AC-11
135    pub fn begin_run(&self) {
136        self.now.set(now());
137        self.conn.reset();
138        self.missed.set(false);
139    }
140}
141// sokf:end cache
142
143impl Cache {
144    pub(super) fn conn(&self) -> &Conn {
145        &self.conn
146    }
147
148    /// `file` returns the path of the store file, or `None` when the store
149    /// is in memory.
150    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    /// `set_synced_at` records the start of the run that this cache just
159    /// committed as the time of the last sync.
160    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
178/// `version` returns the version that a store must record for a run to read
179/// it. The version combines the release version, the store format, the
180/// fingerprint of the build, and the hash of the configuration. The
181/// fingerprint covers the sources and the pinned dependencies, the engine
182/// among them, so a build that checks differently never reads the results of
183/// another. The configuration is part of the version because it determines
184/// the order in which sokf finds the stores when it walks the repository.
185/// That order sets the number each store gets. The files of
186/// `/.sokf/excludes.d/` are part of it, as `repository.exclude` is, because
187/// a run with changed paths takes every other file from the store, so a file
188/// that a new glob prunes would otherwise stay in the run. The files of texts
189/// and the `primary-language` of each manifest are part of it, because the
190/// words of a label in the language of a schema decide the findings of a
191/// document that carries the label. The identity of the formatter through
192/// which same-same compares the formats that it doesn't know, `formatter`,
193/// is part of it because the formatter decides which generated blocks of
194/// those formats are current. When any of them differs, the run rebuilds
195/// the store (CACHE-1_AC-7).
196// sokf-implements: CACHE-1_AC-6
197fn 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
211/// `excludes_fingerprint` returns a hash of the name and the bytes of each
212/// file of `/.sokf/excludes.d/`, so that a change of any of them rebuilds the
213/// store (CACHE-1_AC-98).
214// sokf-implements: CACHE-1_AC-98
215fn 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
225/// `texts_fingerprint` returns a hash of the name and the bytes of
226/// `/.sokf/texts.yaml` and of each file of `/.sokf/texts.d/`, and of the
227/// `primary-language` of each store's manifest, so that a change of the
228/// words of a label in any language rebuilds the store (CACHE-1_AC-99,
229/// CACHE-1_AC-100).
230// sokf-implements: CACHE-1_AC-99
231// sokf-implements: CACHE-1_AC-100
232fn 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
244/// `manifests` returns the root and the manifest of each knowledge root of
245/// the configuration whose manifest can be read, own roots first.
246fn 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
263/// `add_files` adds the path and the bytes of each file of `files` to
264/// `bytes`, each followed by a NUL. A file that can't be read adds no bytes.
265fn 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
274/// `stores_fingerprint` returns a hash of what sets the stores of a run and
275/// how they relate: the name and the bytes of each file of
276/// `/.sokf/roots.d/`, and for each root, the `unique` and the `extends` of
277/// its manifest, with its identities where a store extends another. A registered root changes the number
278/// of each store after it, and a cap or an `extends` changes the scope of
279/// every key and the schema of every document of a store, so a change of
280/// any of them rebuilds the store (CACHE-1_AC-95, CACHE-1_AC-96).
281// sokf-implements: CACHE-1_AC-95
282// sokf-implements: CACHE-1_AC-96
283fn 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    // An `extends` resolves through the identities of the stores, so where
291    // one store extends another, a rename can break or mend a store, whose
292    // files the run then checks or skips (FORMAT-5_AC-10). Elsewhere a
293    // rename dirties only the documents that name the store (CACHE-1_AC-16).
294    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
323/// `ensure_dir` creates the cache directory and its `.gitignore`, which
324/// keeps everything in the directory out of git, and returns the directory.
325// sokf-implements: CLI-4_AC-18
326pub(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
336/// `open_file` creates the cache directory and its `.gitignore`, and opens
337/// the store file in it. It returns `None` when any step fails, and in that
338/// case the run uses a store in memory.
339fn open_file(root: &RepoRoot) -> Option<Connection> {
340    let dir = ensure_dir(root).ok()?;
341    // An earlier cache kept one JSON file for each entry. This cache does not
342    // read those files, so `open_file` removes them.
343    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
362// sokf:begin tables
363/// `TABLES` lists the tables in the order that `ensure_schema` creates them.
364/// `ensure_schema` drops them in the reverse order.
365// sokf-implements: CACHE-1_AC-30
366const 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
466/// `INDEXES` lists the indexes, which `ensure_schema` creates after the
467/// tables.
468const 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];
485// sokf:end tables
486
487/// `ensure_schema` keeps the tables when the store records `version`, and
488/// otherwise drops them and creates them again. It returns the time of the
489/// last sync that the store recorded, or `None` for a rebuilt store.
490// sokf-implements: CLI-4_AC-19
491fn 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    // sokf-tests: CACHE-1_AC-8
533    // sokf-tests: CACHE-1_AC-10
534    // sokf-tests: CLI-4_AC-18
535    #[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    // sokf-tests: CACHE-1_AC-6
557    // sokf-tests: CACHE-1_AC-7
558    // sokf-tests: CLI-4_AC-19
559    #[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        // The version names the build, so another build reads another store.
590        assert!(
591            version.contains(&format!("+build.{}+", env!("SOKF_BUILD_FINGERPRINT"))),
592            "{version}"
593        );
594        // A run records the time of its sync in the store. When the
595        // configuration changes, the next run rebuilds the store, which
596        // removes that time.
597        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    // sokf-tests: CACHE-1_AC-98
610    #[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        // `fresh_after` records a sync in the store, applies `change`, and
615        // tells whether the next open rebuilt the store.
616        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    // sokf-tests: CACHE-1_AC-7
637    // sokf-tests: CACHE-1_AC-9
638    #[test]
639    fn a_store_that_does_not_open_falls_back_to_memory() {
640        let dir = temp("broken");
641        // A file stands where the cache directory should be.
642        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}