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