1use std::path::Path;
11
12use waratah_storage::{
13 EncodedTerm, IndexPermutation, MAIN_REPOSITORY_ID, Registry, RocksDbTuning, SnapshotId,
14 registry_data_dir,
15};
16use waratah_text::TextPluginConfig;
17
18use crate::config_dir;
19use crate::error::DevError;
20use crate::import::open_hexastore;
21use waratah_storage::hexastore_data_dir;
22
23fn status(message: impl std::fmt::Display) {
25 println!("text: {message}");
26}
27
28fn status_predicates(config: &TextPluginConfig) {
35 let predicates = config.normalized_predicates();
36 if predicates.is_empty() {
37 status("predicates: every predicate (`predicates = []`)");
38 return;
39 }
40 status(format!("predicates: {} configured", predicates.len()));
41 for predicate in predicates {
42 status(format!(" {predicate}"));
43 }
44}
45
46fn resolve_config(config_dir: Option<&Path>) -> Result<TextPluginConfig, DevError> {
48 let file = config_dir::find(config_dir, config_dir::files::TEXT);
49 match file {
50 Some(path) => {
51 let text = std::fs::read_to_string(&path)?;
52 let config = TextPluginConfig::from_toml(&text)
53 .map_err(|error| DevError::Backend(format!("invalid text config: {error}")))?;
54 status(format!("config {}", path.display()));
55 Ok(config)
56 }
57 None => Ok(TextPluginConfig {
58 enabled: true,
62 ..TextPluginConfig::default()
63 }),
64 }
65}
66
67pub fn preflight_index(config: &TextPluginConfig, data_dir: &Path) -> Result<(), DevError> {
77 if !config.enabled {
78 return Ok(());
79 }
80 let o_dir = hexastore_data_dir(
81 data_dir,
82 MAIN_REPOSITORY_ID,
83 waratah_storage::PartitionAxis::O,
84 );
85 let Some(dir) = waratah_storage::text_index_dir_beside(&o_dir) else {
86 return Ok(());
87 };
88 waratah_text_index::TextIndex::check_adoptable(&dir, &config.fingerprint()).map_err(|reason| {
89 DevError::Backend(format!(
90 "{reason}. This build does not rebuild the index automatically: stop the cluster \
91 and run `waratah text rebuild-index --data-dir <data-dir>` (it rebuilds from the \
92 hexastore), or remove the index directory and re-import"
93 ))
94 })
95}
96
97pub fn rebuild_offline(data_dir: &Path, config_dir: Option<&Path>) -> Result<(), DevError> {
101 let config = resolve_config(config_dir)?;
102 let o = open_hexastore(
103 hexastore_data_dir(
104 data_dir,
105 MAIN_REPOSITORY_ID,
106 waratah_storage::PartitionAxis::O,
107 ),
108 waratah_storage::PartitionAxis::O,
109 RocksDbTuning::default(),
110 true,
111 )?;
112 let registry = Registry::open_rocksdb(
113 registry_data_dir(data_dir, MAIN_REPOSITORY_ID),
114 RocksDbTuning::registry_node(),
115 )?;
116 let dir = o.text_index_dir().ok_or_else(|| {
117 DevError::Backend("the text index requires a RocksDB data dir".to_owned())
118 })?;
119 let options = waratah_text_index::TextIndexOptions::new(
120 config.analyzer.clone(),
121 config.seed_chars,
122 config.fingerprint(),
123 );
124 if let Some(meta) = waratah_text_index::meta::read_meta(&dir)
131 .map_err(|error| DevError::Backend(format!("text index sidecar read: {error}")))?
132 && meta.fingerprint != options.fingerprint
133 {
134 status(format!(
135 "sidecar fingerprint {} != requested {}; deleting the index directory",
136 meta.fingerprint, options.fingerprint
137 ));
138 std::fs::remove_dir_all(&dir)
139 .map_err(|error| DevError::Backend(format!("text index remove: {error}")))?;
140 }
141 let index = waratah_text_index::TextIndex::open_or_create(&dir, &options)
142 .map_err(|error| DevError::Backend(format!("text index open: {error}")))?;
143 index
144 .wipe()
145 .map_err(|error| DevError::Backend(format!("text index wipe: {error}")))?;
146 let mut seed_sketch = waratah_stats::TextSeedSketch::collector(config.seed_chars);
151
152 let prefixes = waratah_text::text_head_prefixes();
153 let allow = config.predicate_allowlist();
154 let started = std::time::Instant::now();
155 let mut report = waratah_text::RebuildReport::default();
156 let mut cursor: Option<EncodedTerm> = None;
157 loop {
158 let terms = o.scan_axis_head(
159 IndexPermutation::Opsg,
160 SnapshotId::latest(),
161 waratah_text::HEAD_PAGE,
162 cursor.as_ref(),
163 None,
164 &[],
165 false,
166 false,
167 &prefixes,
168 )?;
169 if terms.is_empty() {
170 break;
171 }
172 let hashes: Vec<waratah_storage::StrHash> =
173 terms.iter().flat_map(waratah_text::hashes_of).collect();
174 let resolved = if hashes.is_empty() {
175 Vec::new()
176 } else {
177 registry.lookup_many(&hashes)?
178 };
179 let hits = o.scan_object_preds(
184 &terms,
185 SnapshotId::latest(),
186 0,
187 None,
188 None,
189 None,
190 &[],
191 false,
192 )?;
193 let predicates_by_object = waratah_text::group_predicates(&terms, &hits);
194 let batch =
195 waratah_text::assemble_batch(&terms, &predicates_by_object, &resolved, allow.as_ref());
196 report.terms_walked += terms.len() as u64;
197 report.docs_posted += batch.docs.len() as u64;
198 report.unresolved += batch.unresolved;
199 report.oversized += batch.oversized;
200 if !batch.docs.is_empty() {
201 for doc in &batch.docs {
204 seed_sketch.record(&doc.lexical);
205 }
206 index
207 .add_batch(&batch.docs)
208 .map_err(|error| DevError::Backend(format!("text index add_batch: {error}")))?;
209 }
210 cursor = terms.last().cloned();
211 }
212 if !report.is_complete() {
219 status(format!(
220 "rebuild INCOMPLETE: {} lexical(s) unresolved in the registry, \
221 {} above the indexed-lexical limit; epoch NOT stamped — the index \
222 stays untrusted and the next rebuild retries the walk",
223 report.unresolved, report.oversized
224 ));
225 return Ok(());
226 }
227 let epoch = o.max_commit_ts_under_prefixes(IndexPermutation::Opsg, &prefixes)?;
231 index
232 .stamp(epoch)
233 .map_err(|error| DevError::Backend(format!("text epoch stamp: {error}")))?;
234 let mut sketch = seed_sketch;
240 sketch.epoch = epoch;
241 let mut sketch_bytes = Vec::new();
242 sketch.encode_body(&mut sketch_bytes);
243 if let Err(error) = std::fs::write(dir.join(waratah_text_index::SKETCH_FILE), sketch_bytes) {
244 status(format!(
245 "seed sketch write failed ({error}); the planner keeps its unpriced estimate \
246 until the next rebuild"
247 ));
248 }
249 status(format!(
250 "rebuild done: {} term(s) walked, {} document(s) posted, \
251 {} unresolved, {} oversized, epoch {epoch}, {} doc(s), {} ms",
252 report.terms_walked,
253 report.docs_posted,
254 report.unresolved,
255 report.oversized,
256 index.doc_count(),
257 started.elapsed().as_millis()
258 ));
259 Ok(())
260}
261
262pub fn status_offline(data_dir: &Path, config_dir: Option<&Path>) -> Result<(), DevError> {
265 let config = resolve_config(config_dir)?;
266 let o = open_hexastore(
267 hexastore_data_dir(
268 data_dir,
269 MAIN_REPOSITORY_ID,
270 waratah_storage::PartitionAxis::O,
271 ),
272 waratah_storage::PartitionAxis::O,
273 RocksDbTuning::default(),
274 false,
275 )?;
276 let dir = o.text_index_dir().ok_or_else(|| {
277 DevError::Backend("the text index requires a RocksDB data dir".to_owned())
278 })?;
279 let meta = waratah_text_index::meta::read_meta(&dir)
280 .map_err(|error| DevError::Backend(format!("text index metadata: {error}")))?;
281 match meta {
282 None => {
283 status(format!(
284 "no index at {} (enable the plugin and start, or run `waratah text rebuild-index`)",
285 dir.display()
286 ));
287 status_predicates(&config);
288 }
289 Some(meta) => {
290 let trusted =
291 meta.trusted_epoch().is_some() && config.fingerprint() == meta.fingerprint;
292 status(format!(
293 "{}: analyzer {}, seed_chars {}, fingerprint {}, epoch {:?}, trusted {trusted}",
294 dir.display(),
295 meta.analyzer,
296 meta.seed_chars,
297 meta.fingerprint,
298 meta.trusted_epoch()
299 ));
300 status_predicates(&config);
301 match waratah_text_index::TextIndex::open_doc_count_read_only(&dir) {
306 Ok(count) => status(format!("live documents: {count}")),
307 Err(error) => status(format!("index unopenable: {error}")),
308 }
309 }
310 }
311 Ok(())
312}