Skip to main content

devpage_core/search/
mod.rs

1//! Full-text search over what the served document publishes: the pages its
2//! nav reaches, and the chapters and slides of every document those reach,
3//! split at their headings into sections, in a tantivy index held in memory.
4//! Built at start beside the served folder's document index and kept current
5//! by the watcher a page at a time, so a search never reads a file; or, over
6//! files that never change, built once and frozen, with no writer left.
7//!
8//! tantivy, because it is a real full-text engine — BM25 ranking, stemming,
9//! phrases, near and prefix matches — as a library in pure Rust, with an
10//! index in memory: nothing to run beside devpage and nothing written to disk.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::path::PathBuf;
14use std::sync::{Arc, Mutex, RwLock};
15
16use serde::Serialize;
17use tantivy::query::Bm25StatisticsProvider;
18use tantivy::schema::{Field, Value};
19use tantivy::tokenizer::TextAnalyzer;
20use tantivy::{IndexReader, Score, Searcher, TantivyDocument, Term};
21
22use crate::folder::Folder;
23
24mod gather;
25mod index;
26mod query;
27mod rank;
28
29use gather::*;
30use index::*;
31use query::*;
32use rank::*;
33
34/// The most pages a search answers.
35const MAX_PAGES: usize = 10;
36/// How many of a page's sections a search shows.
37const SECTIONS_PER_PAGE: usize = 3;
38
39/// A search's answer: the pages found, best first, each with its best
40/// sections.
41#[derive(Debug, Clone, Serialize, PartialEq, Default)]
42pub struct Answer {
43    /// The pages found, best first: at most [`MAX_PAGES`].
44    pub pages: Vec<PageResult>,
45}
46
47/// One page found: where it is, what it is, and its sections that matched.
48#[derive(Debug, Clone, Serialize, PartialEq)]
49pub struct PageResult {
50    /// The page's title, as its result heads it.
51    pub title: String,
52    /// Where the page opens: its top.
53    pub url: String,
54    /// The page's place in its document's nav: the labels from the top down to it.
55    pub trail: Vec<String>,
56    /// The document the page belongs to.
57    pub document: Owner,
58    /// What the page is: a site's page, a doc's chapter or a deck's slide.
59    pub kind: PageKind,
60    /// Whether the query is the page's title: it comes first, and opens at `url`.
61    pub title_match: bool,
62    /// The page's first paragraph.
63    pub lede: String,
64    /// Its best sections, at most [`SECTIONS_PER_PAGE`].
65    pub sections: Vec<SectionResult>,
66    /// How many more of its sections matched.
67    pub more: usize,
68}
69
70/// One section found: its heading, where it is, a snippet of its prose with
71/// the matched words in `<mark>`, and those words as its text spells them.
72#[derive(Debug, Clone, Serialize, PartialEq)]
73pub struct SectionResult {
74    /// The section's heading; empty for what comes before the page's first
75    /// heading.
76    pub heading: String,
77    /// The page's title and the headings down to this one.
78    pub path: Vec<String>,
79    /// The page's address and the section's anchor: none before a page's
80    /// first heading; in a doc of several chapters, `name--id`, or the
81    /// chapter's `name` before its first heading.
82    pub url: String,
83    /// HTML: a part of the section's prose, escaped, its matched words in `<mark>`.
84    pub snippet: String,
85    /// The words the query matched, as the section's text spells them, for the
86    /// page to mark.
87    pub words: Vec<String>,
88}
89
90/// What a page found is: a site's page, a doc's chapter, or a deck's slide.
91#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
92#[serde(rename_all = "lowercase")]
93pub enum PageKind {
94    /// A site's page, a section per heading; or a code reference's page,
95    /// one section.
96    Page,
97    /// A doc's chapter: a section per heading, anchored by the chapter's
98    /// name when the doc has several.
99    Chapter,
100    /// A deck's slide: one section, its notes searched with it.
101    Slide,
102}
103
104/// The document a page belongs to: its title and its document file's address.
105#[derive(Debug, Clone, Serialize, PartialEq)]
106pub struct Owner {
107    /// The document's title, which each of its pages' results names it by.
108    pub title: String,
109    /// The address of its document file.
110    pub path: String,
111}
112
113/// The search index of what the served document publishes: what keeps it
114/// current, and the snapshot each search reads.
115pub struct Search {
116    /// The index's fields, each holding one kind of a section's text.
117    fields: Fields,
118    /// What hands out the index as of its last commit; it reloads only when
119    /// told.
120    reader: IndexReader,
121    /// What keeps it current; `None` once [frozen](Search::frozen).
122    indexer: Mutex<Option<Indexer>>,
123    /// The tokenizer that lowercases and stems English, as the ranked fields
124    /// are indexed.
125    stemmed: TextAnalyzer,
126    /// The tokenizer that lowercases without stemming, as the near and prefix
127    /// fields are indexed.
128    plain: TextAnalyzer,
129    /// The served document's file, where what is published starts.
130    entry: PathBuf,
131    /// What a search reads, as of the last commit.
132    snapshot: RwLock<Arc<Snapshot>>,
133}
134
135/// The index as one commit left it, read together: its sections, every
136/// page's record, and the statistics BM25 scores by.
137struct Snapshot {
138    /// The sections indexed, as of the commit.
139    searcher: Searcher,
140    /// Every page indexed, by its address.
141    pages: Pages,
142    /// Each field's length over every section, by field id: the sum of its
143    /// sections' lengths as the index keeps them.
144    tokens: Vec<u64>,
145}
146
147impl Snapshot {
148    /// The snapshot of `searcher`'s commit, with its `pages` and each field's
149    /// length summed over its sections.
150    fn new(searcher: Searcher, pages: Pages) -> Self {
151        let tokens = searcher
152            .schema()
153            .fields()
154            .map(|(field, _)| {
155                searcher
156                    .segment_readers()
157                    .iter()
158                    .filter_map(|segment| {
159                        let norms = segment.fieldnorms_readers().get_field(field).ok()??;
160                        Some(
161                            segment
162                                .doc_ids_alive()
163                                .map(|doc| u64::from(norms.fieldnorm(doc)))
164                                .sum::<u64>(),
165                        )
166                    })
167                    .sum()
168            })
169            .collect();
170        Self {
171            searcher,
172            pages,
173            tokens,
174        }
175    }
176}
177
178/// BM25's statistics are those of the sections the snapshot holds, however
179/// they came to be indexed. tantivy's own statistics count a field's length
180/// exactly when a segment is written, but estimate it from the sections'
181/// lengths when a merge leaves deleted sections out; summing those lengths
182/// always makes an index kept current a page at a time score as one built
183/// fresh.
184impl Bm25StatisticsProvider for Snapshot {
185    fn total_num_tokens(&self, field: tantivy::schema::Field) -> tantivy::Result<u64> {
186        Ok(self
187            .tokens
188            .get(field.field_id() as usize)
189            .copied()
190            .unwrap_or(0))
191    }
192
193    fn total_num_docs(&self) -> tantivy::Result<u64> {
194        Ok(self.searcher.num_docs())
195    }
196
197    fn doc_freq(&self, term: &Term) -> tantivy::Result<u64> {
198        self.searcher.doc_freq(term)
199    }
200}
201
202/// The page record: what a page result shows besides its sections.
203#[derive(Debug, Clone)]
204struct Page {
205    /// The title its result heads: a slide's own, a Markdown file's first
206    /// heading — its file name without one — or the name a code page is
207    /// about.
208    title: String,
209    /// Its address, where its result opens.
210    url: String,
211    /// Its place in its document's nav: the labels from the top down to it.
212    trail: Vec<String>,
213    /// The document it belongs to.
214    document: Owner,
215    /// What it is: a site's page, a doc's chapter or a deck's slide.
216    kind: PageKind,
217    /// Its first paragraph, whitespace squeezed; a code page's first sentence.
218    lede: String,
219    /// Its place in the nav, counted from the top in reading order.
220    nav: u64,
221    /// The stems of its title.
222    title_stems: BTreeSet<String>,
223    /// The stems of its front matter's description and keywords.
224    meta_stems: BTreeSet<String>,
225}
226
227/// Every page indexed, by its address.
228type Pages = BTreeMap<String, Page>;
229
230/// A section found, as stored: what its result is made of.
231struct Found {
232    /// Its heading; empty for what comes before the page's first heading.
233    heading: String,
234    /// The page's title and the headings down to this one.
235    path: Vec<String>,
236    /// The page's address and the section's anchor: none before a page's
237    /// first heading; in a doc of several chapters, `name--id`, or the
238    /// chapter's `name` before its first heading.
239    url: String,
240    /// Its prose, with a diagram's labels and a widget's text.
241    prose: String,
242    /// Its code, whitespace squeezed: searched with its heading and prose for
243    /// how the words matched are spelled.
244    code: String,
245}
246
247/// `mutex`, locked — even when a thread panicked holding it.
248fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
249    mutex
250        .lock()
251        .unwrap_or_else(|poisoned| poisoned.into_inner())
252}
253
254impl Search {
255    /// Whether it still has a writer to keep it current: a frozen index
256    /// has none, nor its threads.
257    pub fn is_live(&self) -> bool {
258        lock(&self.indexer).is_some()
259    }
260
261    /// The bytes its segments hold in memory.
262    pub fn bytes(&self) -> u64 {
263        self.reader
264            .searcher()
265            .space_usage()
266            .map(|usage| usage.total().get_bytes())
267            .unwrap_or(0)
268    }
269
270    /// Brings the index up to date after `paths` changed, appeared or
271    /// vanished — after `folder` has heard of them. Any of them can change
272    /// what is published — a page's Topics, a document file, a
273    /// `.gitignore`, a folder — and a widget can change which of a page's
274    /// tags are widgets, so a burst that holds a Markdown file, a YAML
275    /// file, a widget's `.tsx`, a `.gitignore`, a folder or a path that is
276    /// gone is indexed. What is published is kept from the last burst, and
277    /// found again only when the burst can change it — a Markdown file's
278    /// footprint changed (its Topics, a chapter's title, an unlisted page's
279    /// `search`), or a file came or went, or is a document file or a
280    /// `.gitignore`. Then only the pages new to it, moved in it, or among
281    /// `paths` — or whose document's widgets folder holds one of them — are
282    /// read again. A frozen index never changes.
283    pub fn changed(&self, folder: &Folder, paths: &[PathBuf]) {
284        let code = crate::code::input_roots(folder.served());
285        let matters = |path: &PathBuf| {
286            code.iter().any(|root| path.starts_with(root))
287                || path.is_dir()
288                || !path.exists()
289                || path.file_name().is_some_and(|name| name == ".gitignore")
290                || path
291                    .extension()
292                    .is_some_and(|ext| ext == "md" || ext == "yml" || ext == "yaml" || ext == "tsx")
293        };
294        if paths.iter().any(matters) {
295            self.index(folder, paths);
296        }
297    }
298
299    /// The pages matching `query`, best first, at most [`MAX_PAGES`], each
300    /// with its best sections.
301    pub fn search(&self, query: &str) -> Answer {
302        let now = Arc::clone(&self.snapshot.read().unwrap_or_else(|p| p.into_inner()));
303        let (searcher, pages) = (&now.searcher, &now.pages);
304        let mut parsed = self.parse(query);
305        self.mark_near(&mut parsed, searcher);
306        let mut found = self.ranked(&parsed, &now, false);
307        let fallback = found.is_empty() && parsed.required() > 1;
308        if fallback {
309            found = self.ranked(&parsed, &now, true);
310        }
311        let wanted = parsed.matched();
312        // Each section found, with its page, scored.
313        let mut sections: Vec<(Score, &Page, Found)> = Vec::new();
314        for (score, address) in found {
315            let Ok(doc) = searcher.doc::<TantivyDocument>(address) else {
316                continue;
317            };
318            let text = |field: Field| {
319                doc.get_first(field)
320                    .and_then(|value| value.as_str())
321                    .unwrap_or_default()
322                    .to_string()
323            };
324            let Some(page) = pages.get(&text(self.fields.page)) else {
325                continue;
326            };
327            let (heading, prose, code) = (
328                text(self.fields.heading),
329                text(self.fields.prose),
330                text(self.fields.code_text),
331            );
332            let mut score = score;
333            if fallback {
334                let all = [
335                    page.title.as_str(),
336                    &heading,
337                    &prose,
338                    &code,
339                    &text(self.fields.notes),
340                    &text(self.fields.meta),
341                ]
342                .join(" ");
343                let covered = self.covered(&all, &wanted);
344                let coverage = covered as f32 / wanted.len().max(1) as f32;
345                score *= coverage * coverage;
346            }
347            sections.push((
348                score,
349                page,
350                Found {
351                    heading,
352                    path: doc
353                        .get_all(self.fields.path)
354                        .filter_map(|value| value.as_str().map(str::to_string))
355                        .collect(),
356                    url: text(self.fields.url),
357                    prose,
358                    code,
359                },
360            ));
361        }
362        sections.sort_by(|a, b| b.0.total_cmp(&a.0));
363        // Grouped by page: a page scores as its best section.
364        let mut grouped: Vec<(Score, &Page, Vec<Found>)> = Vec::new();
365        for (score, page, section) in sections {
366            match grouped.iter_mut().find(|(_, p, _)| p.url == page.url) {
367                Some((_, _, list)) => list.push(section),
368                None => grouped.push((score, page, vec![section])),
369            }
370        }
371        // A page whose title the query is comes first: a whole title before
372        // one being typed, then in the nav's order.
373        let titled = |page: &Page| self.title_match(&parsed, &page.title);
374        grouped.sort_by(|a, b| {
375            let (ta, tb) = (titled(a.1), titled(b.1));
376            // A name written as it was typed, case and all, before one that
377            // only matches it.
378            let exact = |page: &Page| page.title != query.trim();
379            ta.cmp(&tb)
380                .then_with(|| exact(a.1).cmp(&exact(b.1)))
381                .then_with(|| match ta {
382                    TitleMatch::None => b.0.total_cmp(&a.0),
383                    _ => a.1.nav.cmp(&b.1.nav),
384                })
385                .then_with(|| b.0.total_cmp(&a.0))
386        });
387        Answer {
388            pages: grouped
389                .into_iter()
390                .take(MAX_PAGES)
391                .map(|(_, page, sections)| {
392                    let more = sections.len().saturating_sub(SECTIONS_PER_PAGE);
393                    // Snippets and words for the sections shown only.
394                    let sections = sections
395                        .into_iter()
396                        .take(SECTIONS_PER_PAGE)
397                        .map(|found| SectionResult {
398                            snippet: self.snippet(&found.prose, &wanted),
399                            words: self
400                                .spelled(&[&found.heading, &found.prose, &found.code], &wanted),
401                            heading: found.heading,
402                            path: found.path,
403                            url: found.url,
404                        })
405                        .collect();
406                    PageResult {
407                        title: page.title.clone(),
408                        url: page.url.clone(),
409                        trail: page.trail.clone(),
410                        document: page.document.clone(),
411                        kind: page.kind,
412                        title_match: titled(page) != TitleMatch::None,
413                        lede: page.lede.clone(),
414                        sections,
415                        more,
416                    }
417                })
418                .collect(),
419        }
420    }
421}
422
423#[cfg(test)]
424mod tests;