devpage-core 0.3.2

devpage's core: documents, rendering, link checking, comments and designs, with no I/O runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Full-text search over what the served document publishes: the pages its
//! nav reaches, and the chapters and slides of every document those reach,
//! split at their headings into sections, in a tantivy index held in memory.
//! Built at start beside the served folder's document index and kept current
//! by the watcher a page at a time, so a search never reads a file; or, over
//! files that never change, built once and frozen, with no writer left.
//!
//! tantivy, because it is a real full-text engine — BM25 ranking, stemming,
//! phrases, near and prefix matches — as a library in pure Rust, with an
//! index in memory: nothing to run beside devpage and nothing written to disk.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};

use serde::Serialize;
use tantivy::query::Bm25StatisticsProvider;
use tantivy::schema::{Field, Value};
use tantivy::tokenizer::TextAnalyzer;
use tantivy::{IndexReader, Score, Searcher, TantivyDocument, Term};

use crate::folder::Folder;

mod gather;
mod index;
mod query;
mod rank;

use gather::*;
use index::*;
use query::*;
use rank::*;

/// The most pages a search answers.
const MAX_PAGES: usize = 10;
/// How many of a page's sections a search shows.
const SECTIONS_PER_PAGE: usize = 3;

/// A search's answer: the pages found, best first, each with its best
/// sections.
#[derive(Debug, Clone, Serialize, PartialEq, Default)]
pub struct Answer {
    /// The pages found, best first: at most [`MAX_PAGES`].
    pub pages: Vec<PageResult>,
}

/// One page found: where it is, what it is, and its sections that matched.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PageResult {
    /// The page's title, as its result heads it.
    pub title: String,
    /// Where the page opens: its top.
    pub url: String,
    /// The page's place in its document's nav: the labels from the top down to it.
    pub trail: Vec<String>,
    /// The document the page belongs to.
    pub document: Owner,
    /// What the page is: a site's page, a doc's chapter or a deck's slide.
    pub kind: PageKind,
    /// Whether the query is the page's title: it comes first, and opens at `url`.
    pub title_match: bool,
    /// The page's first paragraph.
    pub lede: String,
    /// Its best sections, at most [`SECTIONS_PER_PAGE`].
    pub sections: Vec<SectionResult>,
    /// How many more of its sections matched.
    pub more: usize,
}

/// One section found: its heading, where it is, a snippet of its prose with
/// the matched words in `<mark>`, and those words as its text spells them.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SectionResult {
    /// The section's heading; empty for what comes before the page's first
    /// heading.
    pub heading: String,
    /// The page's title and the headings down to this one.
    pub path: Vec<String>,
    /// The page's address and the section's anchor: none before a page's
    /// first heading; in a doc of several chapters, `name--id`, or the
    /// chapter's `name` before its first heading.
    pub url: String,
    /// HTML: a part of the section's prose, escaped, its matched words in `<mark>`.
    pub snippet: String,
    /// The words the query matched, as the section's text spells them, for the
    /// page to mark.
    pub words: Vec<String>,
}

/// What a page found is: a site's page, a doc's chapter, or a deck's slide.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PageKind {
    /// A site's page, a section per heading; or a code reference's page,
    /// one section.
    Page,
    /// A doc's chapter: a section per heading, anchored by the chapter's
    /// name when the doc has several.
    Chapter,
    /// A deck's slide: one section, its notes searched with it.
    Slide,
}

/// The document a page belongs to: its title and its document file's address.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Owner {
    /// The document's title, which each of its pages' results names it by.
    pub title: String,
    /// The address of its document file.
    pub path: String,
}

/// The search index of what the served document publishes: what keeps it
/// current, and the snapshot each search reads.
pub struct Search {
    /// The index's fields, each holding one kind of a section's text.
    fields: Fields,
    /// What hands out the index as of its last commit; it reloads only when
    /// told.
    reader: IndexReader,
    /// What keeps it current; `None` once [frozen](Search::frozen).
    indexer: Mutex<Option<Indexer>>,
    /// The tokenizer that lowercases and stems English, as the ranked fields
    /// are indexed.
    stemmed: TextAnalyzer,
    /// The tokenizer that lowercases without stemming, as the near and prefix
    /// fields are indexed.
    plain: TextAnalyzer,
    /// The served document's file, where what is published starts.
    entry: PathBuf,
    /// What a search reads, as of the last commit.
    snapshot: RwLock<Arc<Snapshot>>,
}

/// The index as one commit left it, read together: its sections, every
/// page's record, and the statistics BM25 scores by.
struct Snapshot {
    /// The sections indexed, as of the commit.
    searcher: Searcher,
    /// Every page indexed, by its address.
    pages: Pages,
    /// Each field's length over every section, by field id: the sum of its
    /// sections' lengths as the index keeps them.
    tokens: Vec<u64>,
}

impl Snapshot {
    /// The snapshot of `searcher`'s commit, with its `pages` and each field's
    /// length summed over its sections.
    fn new(searcher: Searcher, pages: Pages) -> Self {
        let tokens = searcher
            .schema()
            .fields()
            .map(|(field, _)| {
                searcher
                    .segment_readers()
                    .iter()
                    .filter_map(|segment| {
                        let norms = segment.fieldnorms_readers().get_field(field).ok()??;
                        Some(
                            segment
                                .doc_ids_alive()
                                .map(|doc| u64::from(norms.fieldnorm(doc)))
                                .sum::<u64>(),
                        )
                    })
                    .sum()
            })
            .collect();
        Self {
            searcher,
            pages,
            tokens,
        }
    }
}

/// BM25's statistics are those of the sections the snapshot holds, however
/// they came to be indexed. tantivy's own statistics count a field's length
/// exactly when a segment is written, but estimate it from the sections'
/// lengths when a merge leaves deleted sections out; summing those lengths
/// always makes an index kept current a page at a time score as one built
/// fresh.
impl Bm25StatisticsProvider for Snapshot {
    fn total_num_tokens(&self, field: tantivy::schema::Field) -> tantivy::Result<u64> {
        Ok(self
            .tokens
            .get(field.field_id() as usize)
            .copied()
            .unwrap_or(0))
    }

    fn total_num_docs(&self) -> tantivy::Result<u64> {
        Ok(self.searcher.num_docs())
    }

    fn doc_freq(&self, term: &Term) -> tantivy::Result<u64> {
        self.searcher.doc_freq(term)
    }
}

/// The page record: what a page result shows besides its sections.
#[derive(Debug, Clone)]
struct Page {
    /// The title its result heads: a slide's own, a Markdown file's first
    /// heading — its file name without one — or the name a code page is
    /// about.
    title: String,
    /// Its address, where its result opens.
    url: String,
    /// Its place in its document's nav: the labels from the top down to it.
    trail: Vec<String>,
    /// The document it belongs to.
    document: Owner,
    /// What it is: a site's page, a doc's chapter or a deck's slide.
    kind: PageKind,
    /// Its first paragraph, whitespace squeezed; a code page's first sentence.
    lede: String,
    /// Its place in the nav, counted from the top in reading order.
    nav: u64,
    /// The stems of its title.
    title_stems: BTreeSet<String>,
    /// The stems of its front matter's description and keywords.
    meta_stems: BTreeSet<String>,
}

/// Every page indexed, by its address.
type Pages = BTreeMap<String, Page>;

/// A section found, as stored: what its result is made of.
struct Found {
    /// Its heading; empty for what comes before the page's first heading.
    heading: String,
    /// The page's title and the headings down to this one.
    path: Vec<String>,
    /// The page's address and the section's anchor: none before a page's
    /// first heading; in a doc of several chapters, `name--id`, or the
    /// chapter's `name` before its first heading.
    url: String,
    /// Its prose, with a diagram's labels and a widget's text.
    prose: String,
    /// Its code, whitespace squeezed: searched with its heading and prose for
    /// how the words matched are spelled.
    code: String,
}

/// `mutex`, locked — even when a thread panicked holding it.
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

impl Search {
    /// Whether it still has a writer to keep it current: a frozen index
    /// has none, nor its threads.
    pub fn is_live(&self) -> bool {
        lock(&self.indexer).is_some()
    }

    /// The bytes its segments hold in memory.
    pub fn bytes(&self) -> u64 {
        self.reader
            .searcher()
            .space_usage()
            .map(|usage| usage.total().get_bytes())
            .unwrap_or(0)
    }

    /// Brings the index up to date after `paths` changed, appeared or
    /// vanished — after `folder` has heard of them. Any of them can change
    /// what is published — a page's Topics, a document file, a
    /// `.gitignore`, a folder — and a widget can change which of a page's
    /// tags are widgets, so a burst that holds a Markdown file, a YAML
    /// file, a widget's `.tsx`, a `.gitignore`, a folder or a path that is
    /// gone is indexed. What is published is kept from the last burst, and
    /// found again only when the burst can change it — a Markdown file's
    /// footprint changed (its Topics, a chapter's title, an unlisted page's
    /// `search`), or a file came or went, or is a document file or a
    /// `.gitignore`. Then only the pages new to it, moved in it, or among
    /// `paths` — or whose document's widgets folder holds one of them — are
    /// read again. A frozen index never changes.
    pub fn changed(&self, folder: &Folder, paths: &[PathBuf]) {
        let code = crate::code::input_roots(folder.served());
        let matters = |path: &PathBuf| {
            code.iter().any(|root| path.starts_with(root))
                || path.is_dir()
                || !path.exists()
                || path.file_name().is_some_and(|name| name == ".gitignore")
                || path
                    .extension()
                    .is_some_and(|ext| ext == "md" || ext == "yml" || ext == "yaml" || ext == "tsx")
        };
        if paths.iter().any(matters) {
            self.index(folder, paths);
        }
    }

    /// The pages matching `query`, best first, at most [`MAX_PAGES`], each
    /// with its best sections.
    pub fn search(&self, query: &str) -> Answer {
        let now = Arc::clone(&self.snapshot.read().unwrap_or_else(|p| p.into_inner()));
        let (searcher, pages) = (&now.searcher, &now.pages);
        let mut parsed = self.parse(query);
        self.mark_near(&mut parsed, searcher);
        let mut found = self.ranked(&parsed, &now, false);
        let fallback = found.is_empty() && parsed.required() > 1;
        if fallback {
            found = self.ranked(&parsed, &now, true);
        }
        let wanted = parsed.matched();
        // Each section found, with its page, scored.
        let mut sections: Vec<(Score, &Page, Found)> = Vec::new();
        for (score, address) in found {
            let Ok(doc) = searcher.doc::<TantivyDocument>(address) else {
                continue;
            };
            let text = |field: Field| {
                doc.get_first(field)
                    .and_then(|value| value.as_str())
                    .unwrap_or_default()
                    .to_string()
            };
            let Some(page) = pages.get(&text(self.fields.page)) else {
                continue;
            };
            let (heading, prose, code) = (
                text(self.fields.heading),
                text(self.fields.prose),
                text(self.fields.code_text),
            );
            let mut score = score;
            if fallback {
                let all = [
                    page.title.as_str(),
                    &heading,
                    &prose,
                    &code,
                    &text(self.fields.notes),
                    &text(self.fields.meta),
                ]
                .join(" ");
                let covered = self.covered(&all, &wanted);
                let coverage = covered as f32 / wanted.len().max(1) as f32;
                score *= coverage * coverage;
            }
            sections.push((
                score,
                page,
                Found {
                    heading,
                    path: doc
                        .get_all(self.fields.path)
                        .filter_map(|value| value.as_str().map(str::to_string))
                        .collect(),
                    url: text(self.fields.url),
                    prose,
                    code,
                },
            ));
        }
        sections.sort_by(|a, b| b.0.total_cmp(&a.0));
        // Grouped by page: a page scores as its best section.
        let mut grouped: Vec<(Score, &Page, Vec<Found>)> = Vec::new();
        for (score, page, section) in sections {
            match grouped.iter_mut().find(|(_, p, _)| p.url == page.url) {
                Some((_, _, list)) => list.push(section),
                None => grouped.push((score, page, vec![section])),
            }
        }
        // A page whose title the query is comes first: a whole title before
        // one being typed, then in the nav's order.
        let titled = |page: &Page| self.title_match(&parsed, &page.title);
        grouped.sort_by(|a, b| {
            let (ta, tb) = (titled(a.1), titled(b.1));
            // A name written as it was typed, case and all, before one that
            // only matches it.
            let exact = |page: &Page| page.title != query.trim();
            ta.cmp(&tb)
                .then_with(|| exact(a.1).cmp(&exact(b.1)))
                .then_with(|| match ta {
                    TitleMatch::None => b.0.total_cmp(&a.0),
                    _ => a.1.nav.cmp(&b.1.nav),
                })
                .then_with(|| b.0.total_cmp(&a.0))
        });
        Answer {
            pages: grouped
                .into_iter()
                .take(MAX_PAGES)
                .map(|(_, page, sections)| {
                    let more = sections.len().saturating_sub(SECTIONS_PER_PAGE);
                    // Snippets and words for the sections shown only.
                    let sections = sections
                        .into_iter()
                        .take(SECTIONS_PER_PAGE)
                        .map(|found| SectionResult {
                            snippet: self.snippet(&found.prose, &wanted),
                            words: self
                                .spelled(&[&found.heading, &found.prose, &found.code], &wanted),
                            heading: found.heading,
                            path: found.path,
                            url: found.url,
                        })
                        .collect();
                    PageResult {
                        title: page.title.clone(),
                        url: page.url.clone(),
                        trail: page.trail.clone(),
                        document: page.document.clone(),
                        kind: page.kind,
                        title_match: titled(page) != TitleMatch::None,
                        lede: page.lede.clone(),
                        sections,
                        more,
                    }
                })
                .collect(),
        }
    }
}

#[cfg(test)]
mod tests;