Skip to main content

waratah_text_index/
meta.rs

1//! Index sidecar metadata: the trust state and the configuration that lives
2//! beside the Tantivy directory.
3//!
4//! `{index_dir}/waratah-text.json` carries the analyzer, the seed length, the
5//! config fingerprint and the build epoch. It is written when the index is
6//! created (with no epoch), stamped by the rebuild's finish step, and cleared
7//! to "no epoch" by a wipe — so a wiped index reads as untrusted while its
8//! configuration survives. Deleting the directory removes everything.
9
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14use crate::error::TextIndexError;
15
16/// Sidecar file name inside the index directory.
17pub const META_FILE: &str = "waratah-text.json";
18
19/// Seed-sketch sidecar file name (a sibling of [`META_FILE`]); written at
20/// rebuild finish and removed by every wipe path (see `TextIndex::wipe`).
21/// Byte-level here on purpose: the sketch type lives in `waratah_stats`,
22/// which this crate does not depend on — callers encode/decode.
23pub const SKETCH_FILE: &str = "waratah-text-sketch.bin";
24
25/// Version of the sidecar layout.
26pub const META_VERSION: u32 = 1;
27
28/// Persisted index metadata.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct TextIndexMeta {
31    /// Layout version, so a future change is rejected instead of misread.
32    pub version: u32,
33    /// Analyzer menu value the index was built with.
34    pub analyzer: String,
35    /// Seed length the documents were built with.
36    pub seed_chars: usize,
37    /// Config fingerprint, compared by compute against its own.
38    pub fingerprint: String,
39    /// Highest commit timestamp covered by the last completed build.
40    /// `None` means "not built": the index must not be trusted.
41    pub epoch: Option<u64>,
42}
43
44impl TextIndexMeta {
45    /// Metadata for a freshly created, not yet built index.
46    pub fn configured(
47        analyzer: impl Into<String>,
48        seed_chars: usize,
49        fingerprint: impl Into<String>,
50    ) -> Self {
51        Self {
52            version: META_VERSION,
53            analyzer: analyzer.into(),
54            seed_chars,
55            fingerprint: fingerprint.into(),
56            epoch: None,
57        }
58    }
59
60    /// The trusted build epoch, if the index has been built.
61    pub fn trusted_epoch(&self) -> Option<u64> {
62        self.epoch
63    }
64}
65
66/// Read the sidecar, `Ok(None)` when the index has never been configured.
67pub fn read_meta(dir: &Path) -> Result<Option<TextIndexMeta>, TextIndexError> {
68    let path = dir.join(META_FILE);
69    let bytes = match std::fs::read(&path) {
70        Ok(bytes) => bytes,
71        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
72        Err(error) => return Err(error.into()),
73    };
74    let meta: TextIndexMeta =
75        serde_json::from_slice(&bytes).map_err(|error| TextIndexError::Meta {
76            path: path.clone(),
77            detail: error.to_string(),
78        })?;
79    if meta.version != META_VERSION {
80        return Err(TextIndexError::Meta {
81            path,
82            detail: format!(
83                "unsupported metadata version {} (this build understands {META_VERSION})",
84                meta.version
85            ),
86        });
87    }
88    Ok(Some(meta))
89}
90
91/// Write the sidecar atomically: temp file, fsync, rename, fsync the directory.
92///
93/// A torn write can therefore never leave a stamped epoch over a partially
94/// written index: the old file or the new file survives, never a mixture.
95pub fn write_meta(dir: &Path, meta: &TextIndexMeta) -> Result<(), TextIndexError> {
96    let path = dir.join(META_FILE);
97    let temp: PathBuf = dir.join(format!(".{META_FILE}.tmp-{}", std::process::id()));
98    let bytes = serde_json::to_vec_pretty(meta).map_err(|error| TextIndexError::Meta {
99        path: path.clone(),
100        detail: error.to_string(),
101    })?;
102    {
103        use std::io::Write;
104        let mut file = std::fs::File::create(&temp)?;
105        file.write_all(&bytes)?;
106        file.sync_all()?;
107    }
108    std::fs::rename(&temp, &path)?;
109    sync_dir(dir)?;
110    Ok(())
111}
112
113/// Delete the sidecar. Missing is success.
114pub fn remove_meta(dir: &Path) -> Result<(), TextIndexError> {
115    match std::fs::remove_file(dir.join(META_FILE)) {
116        Ok(()) => {}
117        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
118        Err(error) => return Err(error.into()),
119    }
120    sync_dir(dir)?;
121    Ok(())
122}
123
124fn sync_dir(dir: &Path) -> std::io::Result<()> {
125    // Directory fsync makes the rename durable. Unix-only; on other platforms
126    // the file fsync above is the best available guarantee.
127    #[cfg(unix)]
128    {
129        let handle = std::fs::File::open(dir)?;
130        handle.sync_all()?;
131    }
132    #[cfg(not(unix))]
133    let _ = dir;
134    Ok(())
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn meta_round_trips_and_missing_is_none() {
143        let dir = tempfile::tempdir().unwrap();
144        assert_eq!(read_meta(dir.path()).unwrap(), None);
145        let mut meta = TextIndexMeta::configured("simple", 16, "text-index-v1;x=1");
146        assert_eq!(meta.trusted_epoch(), None, "a new index is not built");
147        write_meta(dir.path(), &meta).unwrap();
148        assert_eq!(read_meta(dir.path()).unwrap(), Some(meta.clone()));
149        meta.epoch = Some(42);
150        write_meta(dir.path(), &meta).unwrap();
151        assert_eq!(
152            read_meta(dir.path()).unwrap().unwrap().trusted_epoch(),
153            Some(42)
154        );
155    }
156
157    #[test]
158    fn malformed_meta_is_an_error_not_an_untrusted_read() {
159        let dir = tempfile::tempdir().unwrap();
160        std::fs::write(dir.path().join(META_FILE), b"{not json").unwrap();
161        assert!(matches!(
162            read_meta(dir.path()),
163            Err(TextIndexError::Meta { .. })
164        ));
165    }
166
167    #[test]
168    fn a_future_version_is_rejected() {
169        let dir = tempfile::tempdir().unwrap();
170        std::fs::write(
171            dir.path().join(META_FILE),
172            br#"{"version":999,"analyzer":"simple","seed_chars":16,"fingerprint":"x","epoch":null}"#,
173        )
174        .unwrap();
175        assert!(matches!(
176            read_meta(dir.path()),
177            Err(TextIndexError::Meta { .. })
178        ));
179    }
180
181    #[test]
182    fn remove_is_idempotent_and_leaves_no_temp_files() {
183        let dir = tempfile::tempdir().unwrap();
184        write_meta(dir.path(), &TextIndexMeta::configured("simple", 16, "f")).unwrap();
185        remove_meta(dir.path()).unwrap();
186        assert_eq!(read_meta(dir.path()).unwrap(), None);
187        remove_meta(dir.path()).unwrap();
188        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
189            .unwrap()
190            .map(|entry| entry.unwrap().file_name())
191            .filter(|name| name.to_string_lossy().contains(".tmp-"))
192            .collect();
193        assert!(leftovers.is_empty(), "temp leftovers: {leftovers:?}");
194    }
195}