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";
27/// The unstemmed twins' tokenizer: tantivy's default, lowercased.
28pub(super) const PLAIN: &str = "default";
29/// Code's tokenizer: split at whitespace, lowercased.
30pub(super) const CODE: &str = "code";
31/// The whole-title fields' tokenizer, which keeps a value as one term.
32pub(super) const RAW: &str = "raw";
33
34/// The fast field the index is sorted by: a section's place in what is
35/// published, in reading order — its page's place in the nav, then its own
36/// on the page.
37const PLACE: &str = "place";
38
39/// Where the code reference's pages start in reading order: after any page
40/// a nav can reach.
41const CODE_NAV: u64 = 1 << 40;
42
43/// The schema's fields, each a part of a section that is stored, searched, or
44/// both.
45#[derive(Clone, Copy)]
46pub(super) struct Fields {
47    /// The address of the section's page, indexed whole, so a page's sections are
48    /// deleted by it.
49    pub(super) page: Field,
50    /// The section's own address, its anchor included; stored only.
51    pub(super) url: Field,
52    /// The headings down to the section, its page's title first; stored only.
53    pub(super) path: Field,
54    /// The page's title, ranked.
55    pub(super) title: Field,
56    /// The section's heading, ranked.
57    pub(super) heading: Field,
58    /// The section's prose, ranked.
59    pub(super) prose: Field,
60    /// The section's code, each identifier whole and in its parts, for matching.
61    pub(super) code: Field,
62    /// The section's code, whitespace squeezed, for spelling out the words a
63    /// result matched; stored only.
64    pub(super) code_text: Field,
65    /// A slide's speaker notes, ranked.
66    pub(super) notes: Field,
67    /// The page's `description` and `keywords`, ranked.
68    pub(super) meta: Field,
69    /// The page's title unstemmed, for near and prefix matches.
70    pub(super) title_words: Field,
71    /// The section's heading unstemmed, for near and prefix matches.
72    pub(super) heading_words: Field,
73    /// The section's prose unstemmed, for near and prefix matches.
74    pub(super) prose_words: Field,
75    /// The page's kept words as one term, stemmed and as typed: what a query
76    /// naming the whole title matches.
77    pub(super) title_exact: Field,
78    /// The section's kept words as one term, stemmed and as typed: what a query
79    /// naming the whole heading matches.
80    pub(super) heading_exact: Field,
81}
82
83/// The index's one writer, and what was published when it last indexed —
84/// every page, by address, read or not — once it has.
85pub(super) struct Indexer {
86    /// The writer every change goes through.
87    writer: IndexWriter,
88    /// What was published when it last indexed; `None` before it has.
89    published: Option<Published>,
90    /// The code reference's pages indexed, by address, each with a hash of
91    /// what it reads: a page is indexed again only when that changed.
92    code: BTreeMap<String, u64>,
93}
94
95/// One section, ready to be a tantivy document.
96pub(super) struct Entry<'a> {
97    /// The page the section is on.
98    pub(super) page: &'a Page,
99    /// The section's heading; a slide's and a code page's is the page's title.
100    pub(super) heading: &'a str,
101    /// The section's address, with its anchor when it has one.
102    pub(super) url: String,
103    /// The headings down to the section, its page's title first.
104    pub(super) path: Vec<String>,
105    /// Its heading's level; 0 for the text before a page's first heading.
106    pub(super) depth: u8,
107    /// Its place on its page, from 0.
108    pub(super) order: usize,
109    /// The section's prose, whitespace squeezed: a slide's headings and text
110    /// together; a code page's doc comment and the prose that adds to it.
111    pub(super) prose: &'a str,
112    /// The section's code, whitespace squeezed; a code page's declaration.
113    pub(super) code: &'a str,
114    /// A slide's speaker notes; empty for any other page.
115    pub(super) notes: &'a str,
116    /// The page's `description` and `keywords` as one line of words.
117    pub(super) meta: &'a str,
118}
119
120impl Search {
121    /// Indexes what the document `entry` publishes, among the documents of `folder`.
122    pub fn build(folder: &Folder, entry: &Path) -> Self {
123        let mut schema = Schema::builder();
124        let text = |tokenizer: &str, record: IndexRecordOption, stored: bool| {
125            let options = TextOptions::default().set_indexing_options(
126                TextFieldIndexing::default()
127                    .set_tokenizer(tokenizer)
128                    .set_index_option(record),
129            );
130            if stored {
131                options.set_stored()
132            } else {
133                options
134            }
135        };
136        let ranked = |stored| text(STEMMED, IndexRecordOption::WithFreqsAndPositions, stored);
137        let plain = text(PLAIN, IndexRecordOption::Basic, false);
138        let raw = text(RAW, IndexRecordOption::Basic, false);
139        let fields = Fields {
140            // Indexed whole, so a page's sections are deleted by its address.
141            page: schema.add_text_field("page", STRING | STORED),
142            url: schema.add_text_field("url", STORED),
143            path: schema.add_text_field("path", STORED),
144            title: schema.add_text_field("title", ranked(true)),
145            heading: schema.add_text_field("heading", ranked(true)),
146            prose: schema.add_text_field("prose", ranked(true)),
147            code: schema.add_text_field("code", text(CODE, IndexRecordOption::WithFreqs, false)),
148            code_text: schema.add_text_field("code_text", STORED),
149            notes: schema.add_text_field("notes", ranked(true)),
150            meta: schema.add_text_field("meta", ranked(true)),
151            title_words: schema.add_text_field("title_words", plain.clone()),
152            heading_words: schema.add_text_field("heading_words", plain.clone()),
153            prose_words: schema.add_text_field("prose_words", plain),
154            title_exact: schema.add_text_field("title_exact", raw.clone()),
155            heading_exact: schema.add_text_field("heading_exact", raw),
156        };
157        for name in ["depth", "order", "nav", PLACE] {
158            schema.add_u64_field(name, FAST);
159        }
160        // Sections stay in reading order, however their pages were indexed,
161        // so sections that score alike rank as they read.
162        let tantivy = tantivy::Index::builder()
163            .schema(schema.build())
164            .settings(IndexSettings {
165                sort_by_field: Some(IndexSortByField {
166                    field: PLACE.to_string(),
167                    order: Order::Asc,
168                }),
169                ..IndexSettings::default()
170            })
171            .create_in_ram()
172            .expect("an index in memory can always be made");
173        tantivy.tokenizers().register(
174            CODE,
175            TextAnalyzer::builder(WhitespaceTokenizer::default())
176                .filter(LowerCaser)
177                .build(),
178        );
179        let analyzer = |name: &str| {
180            tantivy
181                .tokenizers()
182                .get(name)
183                .expect("tantivy registers its default and en_stem tokenizers")
184        };
185        let (stemmed, plain) = (analyzer(STEMMED), analyzer(PLAIN));
186        // One thread at the smallest budget tantivy allows, 15 MB: a docs
187        // folder is small, and the index lives in memory.
188        let writer: IndexWriter = tantivy
189            .writer_with_num_threads(1, 15_000_000)
190            .expect("an index in memory has no lock to contend for");
191        // It merges only when told, after each change (`compact`).
192        writer.set_merge_policy(Box::new(NoMergePolicy));
193        let reader = tantivy
194            .reader_builder()
195            .reload_policy(ReloadPolicy::Manual)
196            .try_into()
197            .expect("an index in memory can always be read");
198        let searcher = reader.searcher();
199        let search = Self {
200            fields,
201            reader,
202            indexer: Mutex::new(Some(Indexer {
203                writer,
204                published: None,
205                code: BTreeMap::new(),
206            })),
207            stemmed,
208            plain,
209            entry: entry.to_path_buf(),
210            snapshot: RwLock::new(Arc::new(Snapshot::new(searcher, BTreeMap::new()))),
211        };
212        search.index(folder, &[]);
213        search
214    }
215
216    /// Indexes what `entry` publishes, commits it once and lets the writer
217    /// go, threads and all, with what it kept between saves: for files that
218    /// never change, such as a published version's.
219    pub fn frozen(folder: &Folder, entry: &Path) -> Self {
220        let search = Self::build(folder, entry);
221        if let Some(indexer) = lock(&search.indexer).take() {
222            let _ = indexer.writer.wait_merging_threads();
223        }
224        search
225    }
226
227    /// Brings the index up to what is published now, a page at a time. When
228    /// `paths` can change what is published ([`Published::moved_by`]), it is
229    /// found again, whole: a page no longer published leaves; a page newly
230    /// published, or whose unit — kind, trail, document, address, place in
231    /// the nav — differs, or whose file is one of `paths` or under one, is
232    /// read again. Otherwise what is published is as it was, and only the
233    /// pages `paths` reach are read again. Every other page stays as it was
234    /// indexed. All in one commit, then compacted, so the index answers as
235    /// one built fresh would. A frozen index has no writer, and stays as it
236    /// is.
237    pub(super) fn index(&self, folder: &Folder, paths: &[PathBuf]) {
238        let mut indexer = lock(&self.indexer);
239        let Some(Indexer {
240            writer,
241            published,
242            code,
243        }) = indexer.as_mut()
244        else {
245            return;
246        };
247        let read = |unit: &Unit| paths.iter().any(|path| unit.reached(path));
248        let mut pages = self
249            .snapshot
250            .read()
251            .unwrap_or_else(|p| p.into_inner())
252            .pages
253            .clone();
254        let remove = |url: &str, pages: &mut Pages| {
255            writer.delete_term(Term::from_field_text(self.fields.page, url));
256            pages.remove(url);
257        };
258        // Each document is loaded once per pass, and its widgets read once,
259        // through the pass's own cache: what a page's tags expand to is what
260        // its page shows now.
261        let (found, mut pass, again): (Option<Published>, Pass, Vec<Unit>) = match published {
262            Some(was) if !was.moved_by(paths) => {
263                let again: Vec<Unit> = was
264                    .units
265                    .values()
266                    .filter(|unit| read(unit))
267                    .cloned()
268                    .collect();
269                for unit in &again {
270                    remove(&unit.url(), &mut pages);
271                }
272                let documents = std::mem::take(&mut was.documents);
273                (None, Pass::with(folder, documents), again)
274            }
275            _ => {
276                let mut pass = Pass::new(folder);
277                let now = Published::find(&mut pass, &self.entry);
278                let none = BTreeMap::new();
279                let was = published.as_ref().map_or(&none, |was| &was.units);
280                for (url, unit) in was {
281                    if now
282                        .units
283                        .get(url)
284                        .is_none_or(|now| now != unit || read(now))
285                    {
286                        remove(url, &mut pages);
287                    }
288                }
289                let again = now
290                    .units
291                    .iter()
292                    .filter(|(url, unit)| {
293                        was.get(*url).is_none_or(|was| was != *unit || read(unit))
294                    })
295                    .map(|(_, unit)| unit.clone())
296                    .collect();
297                (Some(now), pass, again)
298            }
299        };
300        for unit in &again {
301            let Some(shown) = &unit.shown_in else {
302                continue;
303            };
304            if let Some(set) = pass.widgets(shown) {
305                self.add(writer, unit, set, &mut pages);
306            }
307        }
308        self.add_code(writer, code, folder, paths, &mut pages);
309        let documents = pass.into_documents();
310        let committed = writer.commit().is_ok();
311        match (found, published.as_mut()) {
312            (Some(mut now), _) if committed => {
313                now.documents = documents;
314                *published = Some(now);
315            }
316            (None, Some(was)) => was.documents = documents,
317            _ => {}
318        }
319        if !committed {
320            // Back to the last commit, which `published` and `pages` describe.
321            let _ = writer.rollback();
322            return;
323        }
324        compact(writer);
325        let _ = self.reader.reload();
326        *self.snapshot.write().unwrap_or_else(|p| p.into_inner()) =
327            Arc::new(Snapshot::new(self.reader.searcher(), pages));
328    }
329
330    /// Every page published as the index last found it, by address.
331    #[cfg(test)]
332    pub(super) fn units(&self) -> BTreeMap<String, Unit> {
333        lock(&self.indexer)
334            .as_ref()
335            .and_then(|indexer| indexer.published.as_ref())
336            .map(|published| published.units.clone())
337            .unwrap_or_default()
338    }
339
340    /// Adds the sections of one page, its content rendered as its page
341    /// shows it, with the tags of `widgets` expanded, and its record.
342    pub(super) fn add(
343        &self,
344        writer: &IndexWriter,
345        unit: &Unit,
346        widgets: &Widgets,
347        pages: &mut Pages,
348    ) {
349        let Ok(source) = std::fs::read_to_string(&unit.file) else {
350            return;
351        };
352        let front = FrontMatter::read(&source);
353        if front.search == Some(false) {
354            return;
355        }
356        let read = read(&crate::page::content(widgets, &unit.file, source.clone()));
357        let title = match unit.kind {
358            PageKind::Slide => slide_title(&source, &read, unit.name.as_deref().unwrap_or("")),
359            _ => crate::markup::title(&source, &unit.file),
360        };
361        let page = Page {
362            title,
363            url: unit.url(),
364            trail: unit.trail.clone(),
365            document: unit.document.clone(),
366            kind: unit.kind,
367            lede: read.lede.clone(),
368            nav: unit.nav,
369            title_stems: BTreeSet::new(),
370            meta_stems: self.stems(&front.meta),
371        };
372        let page = Page {
373            title_stems: self.stems(&page.title),
374            ..page
375        };
376        let add = |entry: Entry| self.add_entry(writer, entry);
377        match unit.kind {
378            // A slide is one section, at its number: all its text, and its notes.
379            PageKind::Slide => {
380                let prose: Vec<&str> = read
381                    .sections
382                    .iter()
383                    .flat_map(|s| [s.heading.as_str(), s.prose.as_str()])
384                    .collect();
385                let code: Vec<&str> = read.sections.iter().map(|s| s.code.as_str()).collect();
386                let notes: Vec<String> = crate::markup::notes(&source)
387                    .into_iter()
388                    .map(|note| note.text)
389                    .collect();
390                add(Entry {
391                    page: &page,
392                    heading: &page.title,
393                    url: page.url.clone(),
394                    path: vec![page.title.clone()],
395                    depth: 1,
396                    order: 0,
397                    prose: &squeeze(&prose.join(" ")),
398                    code: &squeeze(&code.join(" ")),
399                    notes: &squeeze(&notes.join(" ")),
400                    meta: &front.meta,
401                });
402            }
403            PageKind::Page | PageKind::Chapter => {
404                let mut above: Vec<(u8, String)> = Vec::new();
405                for (order, section) in read.sections.iter().enumerate() {
406                    above.retain(|(level, _)| *level < section.level || section.level == 0);
407                    if section.level > 0 {
408                        above.push((section.level, section.heading.clone()));
409                    }
410                    let mut path: Vec<String> = above.iter().map(|(_, h)| h.clone()).collect();
411                    if path.first() != Some(&page.title) {
412                        path.insert(0, page.title.clone());
413                    }
414                    // As `page::doc` lays them out: with more than one
415                    // chapter, each one's ids carry its name, and the chapter
416                    // is an id itself.
417                    let anchor = match (&section.id, &unit.name) {
418                        (Some(id), Some(name)) => Some(format!("{name}--{id}")),
419                        (Some(id), None) => Some(id.clone()),
420                        (None, Some(name)) => Some(name.clone()),
421                        (None, None) => None,
422                    };
423                    add(Entry {
424                        page: &page,
425                        heading: &section.heading,
426                        url: match anchor {
427                            Some(anchor) => format!("{}#{anchor}", unit.address),
428                            None => unit.address.clone(),
429                        },
430                        path,
431                        depth: section.level,
432                        order,
433                        prose: &section.prose,
434                        code: &section.code,
435                        notes: "",
436                        meta: &front.meta,
437                    });
438                }
439            }
440        }
441        pages.insert(page.url.clone(), page);
442    }
443
444    /// Indexes the served site's code reference as it reads now, when
445    /// `paths` reach it — its code, its prose, its document file — or on the
446    /// first pass: each page one section, its name, its doc and its
447    /// declaration, after every page the nav reaches. Only the pages whose
448    /// text changed, came or went are written.
449    fn add_code(
450        &self,
451        writer: &IndexWriter,
452        known: &mut BTreeMap<String, u64>,
453        folder: &Folder,
454        paths: &[PathBuf],
455        pages: &mut Pages,
456    ) {
457        let roots = crate::code::input_roots(folder.served());
458        let reached = paths.is_empty()
459            || paths.iter().any(|path| {
460                roots.iter().any(|root| path.starts_with(root))
461                    || path
462                        .extension()
463                        .is_some_and(|ext| ext == "md" || ext == "yml" || ext == "yaml")
464            });
465        if !reached {
466            return;
467        }
468        let entry = folder.entry();
469        let found = crate::code::for_document(&entry.path())
470            .map(|index| index.searched())
471            .unwrap_or_default();
472        let owner = Owner {
473            title: entry.title.clone(),
474            path: entry.part_url(&entry.path()),
475        };
476        let mut now = BTreeMap::new();
477        for (at, found) in found.iter().enumerate() {
478            use std::hash::{Hash, Hasher};
479            let mut hasher = std::collections::hash_map::DefaultHasher::new();
480            (&found.title, &found.trail, &found.prose, &found.code, at).hash(&mut hasher);
481            let hash = hasher.finish();
482            now.insert(found.url.clone(), hash);
483            if known.get(&found.url) == Some(&hash) {
484                continue;
485            }
486            writer.delete_term(Term::from_field_text(self.fields.page, &found.url));
487            // Its doc as its page reads it: Markdown as text, code fences
488            // as code.
489            let prose = squeeze(&strip_tags(&crate::page::markdown::markdown(&found.prose)));
490            let page = Page {
491                title: found.title.clone(),
492                url: found.url.clone(),
493                trail: found.trail.clone(),
494                document: owner.clone(),
495                kind: PageKind::Page,
496                lede: prose.split(". ").next().unwrap_or("").to_string(),
497                // After every page the nav reaches.
498                nav: CODE_NAV + at as u64,
499                title_stems: self.stems(&found.title),
500                meta_stems: BTreeSet::new(),
501            };
502            self.add_entry(
503                writer,
504                Entry {
505                    page: &page,
506                    heading: &page.title,
507                    url: page.url.clone(),
508                    path: vec![page.title.clone()],
509                    depth: 1,
510                    order: 0,
511                    prose: &prose,
512                    code: &squeeze(&found.code),
513                    notes: "",
514                    meta: "",
515                },
516            );
517            pages.insert(page.url.clone(), page);
518        }
519        for url in known.keys() {
520            if !now.contains_key(url) {
521                writer.delete_term(Term::from_field_text(self.fields.page, url));
522                pages.remove(url);
523            }
524        }
525        *known = now;
526    }
527
528    /// Adds `entry` as one tantivy document through `writer`, its fields filled
529    /// and its place in reading order set.
530    pub(super) fn add_entry(&self, writer: &IndexWriter, entry: Entry) {
531        let fields = self.fields;
532        let schema = writer.index().schema();
533        let fast = |name: &str| schema.get_field(name).expect("a fast field of the schema");
534        let mut doc = TantivyDocument::default();
535        doc.add_text(fields.page, &entry.page.url);
536        doc.add_text(fields.url, &entry.url);
537        for label in &entry.path {
538            doc.add_text(fields.path, label);
539        }
540        for (ranked, words, text) in [
541            (
542                fields.title,
543                Some(fields.title_words),
544                entry.page.title.as_str(),
545            ),
546            (fields.heading, Some(fields.heading_words), entry.heading),
547            (fields.prose, Some(fields.prose_words), entry.prose),
548            (fields.notes, None, entry.notes),
549            (fields.meta, None, entry.meta),
550        ] {
551            doc.add_text(ranked, text);
552            if let Some(words) = words {
553                doc.add_text(words, text);
554            }
555        }
556        doc.add_text(fields.code, expand_code(entry.code));
557        doc.add_text(fields.code_text, entry.code);
558        for (field, text) in [
559            (fields.title_exact, entry.page.title.as_str()),
560            (fields.heading_exact, entry.heading),
561        ] {
562            let words = self.words(text, false);
563            let kept = kept(&words);
564            doc.add_text(field, joined(&kept, |word| &word.stem));
565            doc.add_text(field, joined(&kept, |word| &word.typed));
566        }
567        doc.add_u64(fast("depth"), u64::from(entry.depth));
568        doc.add_u64(fast("order"), entry.order as u64);
569        doc.add_u64(fast("nav"), entry.page.nav);
570        doc.add_u64(fast(PLACE), entry.page.nav << 32 | entry.order as u64);
571        let _ = writer.add_document(doc);
572    }
573}
574
575/// Merges the index into one segment, leaving out the sections deleted. A
576/// deleted section still counts in how many sections hold a word until its
577/// segment is merged — in a word's BM25 score, and in whether the index
578/// holds it at all — so without this a page saved would rank, and
579/// near-match, otherwise than in an index built fresh.
580fn compact(writer: &mut IndexWriter) {
581    let Ok(segments) = writer.index().searchable_segment_metas() else {
582        return;
583    };
584    if segments.len() > 1 || segments.iter().any(|segment| segment.has_deletes()) {
585        let ids: Vec<_> = segments.iter().map(|segment| segment.id()).collect();
586        let _ = writer.merge(&ids).wait();
587    }
588}