waratah_text_index/
meta.rs1use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14use crate::error::TextIndexError;
15
16pub const META_FILE: &str = "waratah-text.json";
18
19pub const SKETCH_FILE: &str = "waratah-text-sketch.bin";
24
25pub const META_VERSION: u32 = 1;
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct TextIndexMeta {
31 pub version: u32,
33 pub analyzer: String,
35 pub seed_chars: usize,
37 pub fingerprint: String,
39 pub epoch: Option<u64>,
42}
43
44impl TextIndexMeta {
45 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 pub fn trusted_epoch(&self) -> Option<u64> {
62 self.epoch
63 }
64}
65
66pub 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
91pub 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
113pub 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 #[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}