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 document index and kept current by the watcher,
5//! so a search never reads a file.
6//!
7//! tantivy, because it is a real full-text engine — BM25 ranking, stemming,
8//! phrases, near and prefix matches — as a library in pure Rust, with an
9//! index in memory: nothing to run beside devpage and nothing written to disk.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::path::PathBuf;
13use std::sync::{Mutex, RwLock};
14
15use serde::Serialize;
16use tantivy::schema::{Field, Value};
17use tantivy::tokenizer::TextAnalyzer;
18use tantivy::{IndexReader, IndexWriter, Score, TantivyDocument};
19
20use crate::index::Index;
21
22mod gather;
23mod index;
24mod query;
25mod rank;
26
27use gather::*;
28use index::*;
29use query::*;
30use rank::*;
31
32/// How many pages a search answers, and how many of each page's sections
33/// it shows.
34const MAX_PAGES: usize = 10;
35const SECTIONS_PER_PAGE: usize = 3;
36
37/// A search's answer: the pages found, best first, each with its best
38/// sections.
39#[derive(Debug, Clone, Serialize, PartialEq, Default)]
40pub struct Answer {
41    pub pages: Vec<PageResult>,
42}
43
44/// One page found: where it is, what it is, and its sections that matched.
45#[derive(Debug, Clone, Serialize, PartialEq)]
46pub struct PageResult {
47    pub title: String,
48    /// Where the page opens: its top.
49    pub url: String,
50    /// The page's place in its document's nav: the labels from the top down to it.
51    pub trail: Vec<String>,
52    pub document: Owner,
53    pub kind: PageKind,
54    /// Whether the query is the page's title: it comes first, and opens at `url`.
55    pub title_match: bool,
56    /// The page's first paragraph.
57    pub lede: String,
58    /// Its best sections, at most [`SECTIONS_PER_PAGE`].
59    pub sections: Vec<SectionResult>,
60    /// How many more of its sections matched.
61    pub more: usize,
62}
63
64/// One section found: its heading, where it is, a snippet of its prose with
65/// the matched words in `<mark>`, and those words as its text spells them.
66#[derive(Debug, Clone, Serialize, PartialEq)]
67pub struct SectionResult {
68    pub heading: String,
69    /// The page's title and the headings down to this one.
70    pub path: Vec<String>,
71    /// The page's address with the heading's anchor.
72    pub url: String,
73    /// HTML: a part of the section's prose, escaped, its matched words in `<mark>`.
74    pub snippet: String,
75    pub words: Vec<String>,
76}
77
78/// What a page found is: a site's page, a doc's chapter, or a deck's slide.
79#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
80#[serde(rename_all = "lowercase")]
81pub enum PageKind {
82    Page,
83    Chapter,
84    Slide,
85}
86
87/// The document a page belongs to: its title and its document file's address.
88#[derive(Debug, Clone, Serialize, PartialEq)]
89pub struct Owner {
90    pub title: String,
91    pub path: String,
92}
93
94pub struct Search {
95    fields: Fields,
96    reader: IndexReader,
97    writer: Mutex<IndexWriter>,
98    stemmed: TextAnalyzer,
99    plain: TextAnalyzer,
100    /// The served document's file, where what is published starts.
101    entry: PathBuf,
102    /// Every page indexed, by its address.
103    pages: RwLock<Pages>,
104}
105
106/// The page record: what a page result shows besides its sections.
107#[derive(Debug, Clone)]
108struct Page {
109    title: String,
110    url: String,
111    trail: Vec<String>,
112    document: Owner,
113    kind: PageKind,
114    lede: String,
115    /// Its place in the nav, counted from the top in reading order.
116    nav: u64,
117    /// The stems of its title, and of its front matter's description and
118    /// keywords.
119    title_stems: BTreeSet<String>,
120    meta_stems: BTreeSet<String>,
121}
122
123/// Every page indexed, by its address.
124type Pages = BTreeMap<String, Page>;
125
126/// A section found, as stored: what its result is made of.
127struct Found {
128    heading: String,
129    path: Vec<String>,
130    url: String,
131    prose: String,
132    code: String,
133}
134
135fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
136    mutex
137        .lock()
138        .unwrap_or_else(|poisoned| poisoned.into_inner())
139}
140
141impl Search {
142    /// Brings the index up to date after `paths` changed, appeared or
143    /// vanished — after `index` has heard of them. Any of them can change
144    /// what is published — a page's Topics, a document file, a
145    /// `.gitignore`, a folder — so a burst that holds a Markdown file, a
146    /// YAML file, a `.gitignore`, a folder or a path that is gone reads
147    /// everything published again.
148    pub fn changed(&self, index: &Index, paths: &[PathBuf]) {
149        let matters = |path: &PathBuf| {
150            path.is_dir()
151                || !path.exists()
152                || path.file_name().is_some_and(|name| name == ".gitignore")
153                || path
154                    .extension()
155                    .is_some_and(|ext| ext == "md" || ext == "yml" || ext == "yaml")
156        };
157        if paths.iter().any(matters) {
158            self.rebuild(index);
159        }
160    }
161
162    /// The pages matching `query`, best first, at most [`MAX_PAGES`], each
163    /// with its best sections.
164    pub fn search(&self, query: &str) -> Answer {
165        let searcher = self.reader.searcher();
166        let pages = self.pages.read().unwrap_or_else(|p| p.into_inner());
167        let mut parsed = self.parse(query);
168        self.mark_near(&mut parsed, &searcher);
169        let mut found = self.ranked(&parsed, &searcher, &pages, false);
170        let fallback = found.is_empty() && parsed.required() > 1;
171        if fallback {
172            found = self.ranked(&parsed, &searcher, &pages, true);
173        }
174        let wanted = parsed.matched();
175        // Each section found, with its page, scored.
176        let mut sections: Vec<(Score, &Page, Found)> = Vec::new();
177        for (score, address) in found {
178            let Ok(doc) = searcher.doc::<TantivyDocument>(address) else {
179                continue;
180            };
181            let text = |field: Field| {
182                doc.get_first(field)
183                    .and_then(|value| value.as_str())
184                    .unwrap_or_default()
185                    .to_string()
186            };
187            let Some(page) = pages.get(&text(self.fields.page)) else {
188                continue;
189            };
190            let (heading, prose, code) = (
191                text(self.fields.heading),
192                text(self.fields.prose),
193                text(self.fields.code_text),
194            );
195            let mut score = score;
196            if fallback {
197                let all = [
198                    page.title.as_str(),
199                    &heading,
200                    &prose,
201                    &code,
202                    &text(self.fields.notes),
203                    &text(self.fields.meta),
204                ]
205                .join(" ");
206                let covered = self.covered(&all, &wanted);
207                let coverage = covered as f32 / wanted.len().max(1) as f32;
208                score *= coverage * coverage;
209            }
210            sections.push((
211                score,
212                page,
213                Found {
214                    heading,
215                    path: doc
216                        .get_all(self.fields.path)
217                        .filter_map(|value| value.as_str().map(str::to_string))
218                        .collect(),
219                    url: text(self.fields.url),
220                    prose,
221                    code,
222                },
223            ));
224        }
225        sections.sort_by(|a, b| b.0.total_cmp(&a.0));
226        // Grouped by page: a page scores as its best section.
227        let mut grouped: Vec<(Score, &Page, Vec<Found>)> = Vec::new();
228        for (score, page, section) in sections {
229            match grouped.iter_mut().find(|(_, p, _)| p.url == page.url) {
230                Some((_, _, list)) => list.push(section),
231                None => grouped.push((score, page, vec![section])),
232            }
233        }
234        // A page whose title the query is comes first: a whole title before
235        // one being typed, then in the nav's order.
236        let titled = |page: &Page| self.title_match(&parsed, &page.title);
237        grouped.sort_by(|a, b| {
238            let (ta, tb) = (titled(a.1), titled(b.1));
239            ta.cmp(&tb)
240                .then_with(|| match ta {
241                    TitleMatch::None => b.0.total_cmp(&a.0),
242                    _ => a.1.nav.cmp(&b.1.nav),
243                })
244                .then_with(|| b.0.total_cmp(&a.0))
245        });
246        Answer {
247            pages: grouped
248                .into_iter()
249                .take(MAX_PAGES)
250                .map(|(_, page, sections)| {
251                    let more = sections.len().saturating_sub(SECTIONS_PER_PAGE);
252                    // Snippets and words for the sections shown only.
253                    let sections = sections
254                        .into_iter()
255                        .take(SECTIONS_PER_PAGE)
256                        .map(|found| SectionResult {
257                            snippet: self.snippet(&found.prose, &wanted),
258                            words: self
259                                .spelled(&[&found.heading, &found.prose, &found.code], &wanted),
260                            heading: found.heading,
261                            path: found.path,
262                            url: found.url,
263                        })
264                        .collect();
265                    PageResult {
266                        title: page.title.clone(),
267                        url: page.url.clone(),
268                        trail: page.trail.clone(),
269                        document: page.document.clone(),
270                        kind: page.kind,
271                        title_match: titled(page) != TitleMatch::None,
272                        lede: page.lede.clone(),
273                        sections,
274                        more,
275                    }
276                })
277                .collect(),
278        }
279    }
280}
281
282#[cfg(test)]
283mod tests;