Skip to main content

devpage_core/search/
index.rs

1//! The tantivy index: its schema and tokenizers, turning each page
2//! published into the sections it is searched by, and keeping it current a
3//! page at a time.
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::path::{Path, PathBuf};
7use std::sync::{Arc, Mutex, RwLock};
8
9use tantivy::indexer::NoMergePolicy;
10use tantivy::schema::{
11    FAST, Field, IndexRecordOption, STORED, STRING, Schema, TextFieldIndexing, TextOptions,
12};
13use tantivy::tokenizer::{LowerCaser, TextAnalyzer, WhitespaceTokenizer};
14use tantivy::{
15    IndexSettings, IndexSortByField, IndexWriter, Order, ReloadPolicy, TantivyDocument, Term,
16};
17
18use crate::folder::Folder;
19use crate::widgets::Widgets;
20
21use super::*;
22
23/// The tokenizers: the ranked fields' — tantivy's default, lowercased, with
24/// English stemming — their unstemmed twins', for near and prefix matches,
25/// code's, and the whole-title fields', which keep a value as one term.
26pub(super) const STEMMED: &str = "en_stem";
27pub(super) const PLAIN: &str = "default";
28pub(super) const CODE: &str = "code";
29pub(super) const RAW: &str = "raw";
30
31/// The fast field the index is sorted by: a section's place in what is
32/// published, in reading order — its page's place in the nav, then its own
33/// on the page.
34const PLACE: &str = "place";
35
36#[derive(Clone, Copy)]
37pub(super) struct Fields {
38    pub(super) page: Field,
39    pub(super) url: Field,
40    pub(super) path: Field,
41    pub(super) title: Field,
42    pub(super) heading: Field,
43    pub(super) prose: Field,
44    pub(super) code: Field,
45    pub(super) code_text: Field,
46    pub(super) notes: Field,
47    pub(super) meta: Field,
48    pub(super) title_words: Field,
49    pub(super) heading_words: Field,
50    pub(super) prose_words: Field,
51    pub(super) title_exact: Field,
52    pub(super) heading_exact: Field,
53}
54
55/// The index's one writer, and what was published when it last indexed —
56/// every page, by address, read or not — once it has.
57pub(super) struct Indexer {
58    writer: IndexWriter,
59    published: Option<Published>,
60}
61
62/// One section, ready to be a tantivy document.
63pub(super) struct Entry<'a> {
64    pub(super) page: &'a Page,
65    pub(super) heading: &'a str,
66    pub(super) url: String,
67    pub(super) path: Vec<String>,
68    pub(super) depth: u8,
69    pub(super) order: usize,
70    pub(super) prose: &'a str,
71    pub(super) code: &'a str,
72    pub(super) notes: &'a str,
73    pub(super) meta: &'a str,
74}
75
76impl Search {
77    /// Indexes what the document `entry` publishes, among the documents of `folder`.
78    pub fn build(folder: &Folder, entry: &Path) -> Self {
79        let mut schema = Schema::builder();
80        let text = |tokenizer: &str, record: IndexRecordOption, stored: bool| {
81            let options = TextOptions::default().set_indexing_options(
82                TextFieldIndexing::default()
83                    .set_tokenizer(tokenizer)
84                    .set_index_option(record),
85            );
86            if stored {
87                options.set_stored()
88            } else {
89                options
90            }
91        };
92        let ranked = |stored| text(STEMMED, IndexRecordOption::WithFreqsAndPositions, stored);
93        let plain = text(PLAIN, IndexRecordOption::Basic, false);
94        let raw = text(RAW, IndexRecordOption::Basic, false);
95        let fields = Fields {
96            // Indexed whole, so a page's sections are deleted by its address.
97            page: schema.add_text_field("page", STRING | STORED),
98            url: schema.add_text_field("url", STORED),
99            path: schema.add_text_field("path", STORED),
100            title: schema.add_text_field("title", ranked(true)),
101            heading: schema.add_text_field("heading", ranked(true)),
102            prose: schema.add_text_field("prose", ranked(true)),
103            code: schema.add_text_field("code", text(CODE, IndexRecordOption::WithFreqs, false)),
104            code_text: schema.add_text_field("code_text", STORED),
105            notes: schema.add_text_field("notes", ranked(true)),
106            meta: schema.add_text_field("meta", ranked(true)),
107            title_words: schema.add_text_field("title_words", plain.clone()),
108            heading_words: schema.add_text_field("heading_words", plain.clone()),
109            prose_words: schema.add_text_field("prose_words", plain),
110            title_exact: schema.add_text_field("title_exact", raw.clone()),
111            heading_exact: schema.add_text_field("heading_exact", raw),
112        };
113        for name in ["depth", "order", "nav", PLACE] {
114            schema.add_u64_field(name, FAST);
115        }
116        // Sections stay in reading order, however their pages were indexed,
117        // so sections that score alike rank as they read.
118        let tantivy = tantivy::Index::builder()
119            .schema(schema.build())
120            .settings(IndexSettings {
121                sort_by_field: Some(IndexSortByField {
122                    field: PLACE.to_string(),
123                    order: Order::Asc,
124                }),
125                ..IndexSettings::default()
126            })
127            .create_in_ram()
128            .expect("an index in memory can always be made");
129        tantivy.tokenizers().register(
130            CODE,
131            TextAnalyzer::builder(WhitespaceTokenizer::default())
132                .filter(LowerCaser)
133                .build(),
134        );
135        let analyzer = |name: &str| {
136            tantivy
137                .tokenizers()
138                .get(name)
139                .expect("tantivy registers its default and en_stem tokenizers")
140        };
141        let (stemmed, plain) = (analyzer(STEMMED), analyzer(PLAIN));
142        // One thread at the smallest budget tantivy allows, 15 MB: a docs
143        // folder is small, and the index lives in memory.
144        let writer: IndexWriter = tantivy
145            .writer_with_num_threads(1, 15_000_000)
146            .expect("an index in memory has no lock to contend for");
147        // It merges only when told, after each change (`compact`).
148        writer.set_merge_policy(Box::new(NoMergePolicy));
149        let reader = tantivy
150            .reader_builder()
151            .reload_policy(ReloadPolicy::Manual)
152            .try_into()
153            .expect("an index in memory can always be read");
154        let searcher = reader.searcher();
155        let search = Self {
156            fields,
157            reader,
158            indexer: Mutex::new(Some(Indexer {
159                writer,
160                published: None,
161            })),
162            stemmed,
163            plain,
164            entry: entry.to_path_buf(),
165            snapshot: RwLock::new(Arc::new(Snapshot::new(searcher, BTreeMap::new()))),
166        };
167        search.index(folder, &[]);
168        search
169    }
170
171    /// Indexes what `entry` publishes, commits it once and lets the writer
172    /// go, threads and all, with what it kept between saves: for files that
173    /// never change, such as a published version's.
174    pub fn frozen(folder: &Folder, entry: &Path) -> Self {
175        let search = Self::build(folder, entry);
176        if let Some(indexer) = lock(&search.indexer).take() {
177            let _ = indexer.writer.wait_merging_threads();
178        }
179        search
180    }
181
182    /// Brings the index up to what is published now, a page at a time. When
183    /// `paths` can change what is published ([`Published::moved_by`]), it is
184    /// found again, whole: a page no longer published leaves; a page newly
185    /// published, or whose unit — kind, trail, document, address, place in
186    /// the nav — differs, or whose file is one of `paths` or under one, is
187    /// read again. Otherwise what is published is as it was, and only the
188    /// pages `paths` reach are read again. Every other page stays as it was
189    /// indexed. All in one commit, then compacted, so the index answers as
190    /// one built fresh would. A frozen index has no writer, and stays as it
191    /// is.
192    pub(super) fn index(&self, folder: &Folder, paths: &[PathBuf]) {
193        let mut indexer = lock(&self.indexer);
194        let Some(Indexer { writer, published }) = indexer.as_mut() else {
195            return;
196        };
197        let read = |unit: &Unit| paths.iter().any(|path| unit.reached(path));
198        let mut pages = self
199            .snapshot
200            .read()
201            .unwrap_or_else(|p| p.into_inner())
202            .pages
203            .clone();
204        let remove = |url: &str, pages: &mut Pages| {
205            writer.delete_term(Term::from_field_text(self.fields.page, url));
206            pages.remove(url);
207        };
208        // Each document is loaded once per pass, and its widgets read once,
209        // through the pass's own cache: what a page's tags expand to is what
210        // its page shows now.
211        let (found, mut pass, again): (Option<Published>, Pass, Vec<Unit>) = match published {
212            Some(was) if !was.moved_by(paths) => {
213                let again: Vec<Unit> = was
214                    .units
215                    .values()
216                    .filter(|unit| read(unit))
217                    .cloned()
218                    .collect();
219                for unit in &again {
220                    remove(&unit.url(), &mut pages);
221                }
222                let documents = std::mem::take(&mut was.documents);
223                (None, Pass::with(folder, documents), again)
224            }
225            _ => {
226                let mut pass = Pass::new(folder);
227                let now = Published::find(&mut pass, &self.entry);
228                let none = BTreeMap::new();
229                let was = published.as_ref().map_or(&none, |was| &was.units);
230                for (url, unit) in was {
231                    if now
232                        .units
233                        .get(url)
234                        .is_none_or(|now| now != unit || read(now))
235                    {
236                        remove(url, &mut pages);
237                    }
238                }
239                let again = now
240                    .units
241                    .iter()
242                    .filter(|(url, unit)| {
243                        was.get(*url).is_none_or(|was| was != *unit || read(unit))
244                    })
245                    .map(|(_, unit)| unit.clone())
246                    .collect();
247                (Some(now), pass, again)
248            }
249        };
250        for unit in &again {
251            let Some(shown) = &unit.shown_in else {
252                continue;
253            };
254            if let Some(set) = pass.widgets(shown) {
255                self.add(writer, unit, set, &mut pages);
256            }
257        }
258        let documents = pass.into_documents();
259        let committed = writer.commit().is_ok();
260        match (found, published.as_mut()) {
261            (Some(mut now), _) if committed => {
262                now.documents = documents;
263                *published = Some(now);
264            }
265            (None, Some(was)) => was.documents = documents,
266            _ => {}
267        }
268        if !committed {
269            // Back to the last commit, which `published` and `pages` describe.
270            let _ = writer.rollback();
271            return;
272        }
273        compact(writer);
274        let _ = self.reader.reload();
275        *self.snapshot.write().unwrap_or_else(|p| p.into_inner()) =
276            Arc::new(Snapshot::new(self.reader.searcher(), pages));
277    }
278
279    /// Every page published as the index last found it, by address.
280    #[cfg(test)]
281    pub(super) fn units(&self) -> BTreeMap<String, Unit> {
282        lock(&self.indexer)
283            .as_ref()
284            .and_then(|indexer| indexer.published.as_ref())
285            .map(|published| published.units.clone())
286            .unwrap_or_default()
287    }
288
289    /// Adds the sections of one page, its content rendered as its page
290    /// shows it, with the tags of `widgets` expanded, and its record.
291    pub(super) fn add(
292        &self,
293        writer: &IndexWriter,
294        unit: &Unit,
295        widgets: &Widgets,
296        pages: &mut Pages,
297    ) {
298        let Ok(source) = std::fs::read_to_string(&unit.file) else {
299            return;
300        };
301        let front = FrontMatter::read(&source);
302        if front.search == Some(false) {
303            return;
304        }
305        let read = read(&crate::page::content(widgets, &unit.file, source.clone()));
306        let title = match unit.kind {
307            PageKind::Slide => slide_title(&source, &read, unit.name.as_deref().unwrap_or("")),
308            _ => crate::markup::title(&source, &unit.file),
309        };
310        let page = Page {
311            title,
312            url: unit.url(),
313            trail: unit.trail.clone(),
314            document: unit.document.clone(),
315            kind: unit.kind,
316            lede: read.lede.clone(),
317            nav: unit.nav,
318            title_stems: BTreeSet::new(),
319            meta_stems: self.stems(&front.meta),
320        };
321        let page = Page {
322            title_stems: self.stems(&page.title),
323            ..page
324        };
325        let add = |entry: Entry| self.add_entry(writer, entry);
326        match unit.kind {
327            // A slide is one section, at its number: all its text, and its notes.
328            PageKind::Slide => {
329                let prose: Vec<&str> = read
330                    .sections
331                    .iter()
332                    .flat_map(|s| [s.heading.as_str(), s.prose.as_str()])
333                    .collect();
334                let code: Vec<&str> = read.sections.iter().map(|s| s.code.as_str()).collect();
335                let notes: Vec<String> = crate::markup::notes(&source)
336                    .into_iter()
337                    .map(|note| note.text)
338                    .collect();
339                add(Entry {
340                    page: &page,
341                    heading: &page.title,
342                    url: page.url.clone(),
343                    path: vec![page.title.clone()],
344                    depth: 1,
345                    order: 0,
346                    prose: &squeeze(&prose.join(" ")),
347                    code: &squeeze(&code.join(" ")),
348                    notes: &squeeze(&notes.join(" ")),
349                    meta: &front.meta,
350                });
351            }
352            PageKind::Page | PageKind::Chapter => {
353                let mut above: Vec<(u8, String)> = Vec::new();
354                for (order, section) in read.sections.iter().enumerate() {
355                    above.retain(|(level, _)| *level < section.level || section.level == 0);
356                    if section.level > 0 {
357                        above.push((section.level, section.heading.clone()));
358                    }
359                    let mut path: Vec<String> = above.iter().map(|(_, h)| h.clone()).collect();
360                    if path.first() != Some(&page.title) {
361                        path.insert(0, page.title.clone());
362                    }
363                    // As `page::doc` lays them out: with more than one
364                    // chapter, each one's ids carry its name, and the chapter
365                    // is an id itself.
366                    let anchor = match (&section.id, &unit.name) {
367                        (Some(id), Some(name)) => Some(format!("{name}--{id}")),
368                        (Some(id), None) => Some(id.clone()),
369                        (None, Some(name)) => Some(name.clone()),
370                        (None, None) => None,
371                    };
372                    add(Entry {
373                        page: &page,
374                        heading: &section.heading,
375                        url: match anchor {
376                            Some(anchor) => format!("{}#{anchor}", unit.address),
377                            None => unit.address.clone(),
378                        },
379                        path,
380                        depth: section.level,
381                        order,
382                        prose: &section.prose,
383                        code: &section.code,
384                        notes: "",
385                        meta: &front.meta,
386                    });
387                }
388            }
389        }
390        pages.insert(page.url.clone(), page);
391    }
392
393    pub(super) fn add_entry(&self, writer: &IndexWriter, entry: Entry) {
394        let fields = self.fields;
395        let schema = writer.index().schema();
396        let fast = |name: &str| schema.get_field(name).expect("a fast field of the schema");
397        let mut doc = TantivyDocument::default();
398        doc.add_text(fields.page, &entry.page.url);
399        doc.add_text(fields.url, &entry.url);
400        for label in &entry.path {
401            doc.add_text(fields.path, label);
402        }
403        for (ranked, words, text) in [
404            (
405                fields.title,
406                Some(fields.title_words),
407                entry.page.title.as_str(),
408            ),
409            (fields.heading, Some(fields.heading_words), entry.heading),
410            (fields.prose, Some(fields.prose_words), entry.prose),
411            (fields.notes, None, entry.notes),
412            (fields.meta, None, entry.meta),
413        ] {
414            doc.add_text(ranked, text);
415            if let Some(words) = words {
416                doc.add_text(words, text);
417            }
418        }
419        doc.add_text(fields.code, expand_code(entry.code));
420        doc.add_text(fields.code_text, entry.code);
421        for (field, text) in [
422            (fields.title_exact, entry.page.title.as_str()),
423            (fields.heading_exact, entry.heading),
424        ] {
425            let words = self.words(text, false);
426            let kept = kept(&words);
427            doc.add_text(field, joined(&kept, |word| &word.stem));
428            doc.add_text(field, joined(&kept, |word| &word.typed));
429        }
430        doc.add_u64(fast("depth"), u64::from(entry.depth));
431        doc.add_u64(fast("order"), entry.order as u64);
432        doc.add_u64(fast("nav"), entry.page.nav);
433        doc.add_u64(fast(PLACE), entry.page.nav << 32 | entry.order as u64);
434        let _ = writer.add_document(doc);
435    }
436}
437
438/// Merges the index into one segment, leaving out the sections deleted. A
439/// deleted section still counts in how many sections hold a word until its
440/// segment is merged — in a word's BM25 score, and in whether the index
441/// holds it at all — so without this a page saved would rank, and
442/// near-match, otherwise than in an index built fresh.
443fn compact(writer: &mut IndexWriter) {
444    let Ok(segments) = writer.index().searchable_segment_metas() else {
445        return;
446    };
447    if segments.len() > 1 || segments.iter().any(|segment| segment.has_deletes()) {
448        let ids: Vec<_> = segments.iter().map(|segment| segment.id()).collect();
449        let _ = writer.merge(&ids).wait();
450    }
451}