devpage-core 0.3.3

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! The tantivy index: its schema and tokenizers, turning each page
//! published into the sections it is searched by, and keeping it current a
//! page at a time.

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

use tantivy::indexer::NoMergePolicy;
use tantivy::schema::{
    FAST, Field, IndexRecordOption, STORED, STRING, Schema, TextFieldIndexing, TextOptions,
};
use tantivy::tokenizer::{LowerCaser, TextAnalyzer, WhitespaceTokenizer};
use tantivy::{
    IndexSettings, IndexSortByField, IndexWriter, Order, ReloadPolicy, TantivyDocument, Term,
};

use crate::folder::Folder;
use crate::widgets::Widgets;

use super::*;

/// The tokenizers: the ranked fields' — tantivy's default, lowercased, with
/// English stemming — their unstemmed twins', for near and prefix matches,
/// code's, and the whole-title fields', which keep a value as one term.
pub(super) const STEMMED: &str = "en_stem";
/// The unstemmed twins' tokenizer: tantivy's default, lowercased.
pub(super) const PLAIN: &str = "default";
/// Code's tokenizer: split at whitespace, lowercased.
pub(super) const CODE: &str = "code";
/// The whole-title fields' tokenizer, which keeps a value as one term.
pub(super) const RAW: &str = "raw";

/// The fast field the index is sorted by: a section's place in what is
/// published, in reading order — its page's place in the nav, then its own
/// on the page.
const PLACE: &str = "place";

/// Where the code reference's pages start in reading order: after any page
/// a nav can reach.
const CODE_NAV: u64 = 1 << 40;

/// The schema's fields, each a part of a section that is stored, searched, or
/// both.
#[derive(Clone, Copy)]
pub(super) struct Fields {
    /// The address of the section's page, indexed whole, so a page's sections are
    /// deleted by it.
    pub(super) page: Field,
    /// The section's own address, its anchor included; stored only.
    pub(super) url: Field,
    /// The headings down to the section, its page's title first; stored only.
    pub(super) path: Field,
    /// The page's title, ranked.
    pub(super) title: Field,
    /// The section's heading, ranked.
    pub(super) heading: Field,
    /// The section's prose, ranked.
    pub(super) prose: Field,
    /// The section's code, each identifier whole and in its parts, for matching.
    pub(super) code: Field,
    /// The section's code, whitespace squeezed, for spelling out the words a
    /// result matched; stored only.
    pub(super) code_text: Field,
    /// A slide's speaker notes, ranked.
    pub(super) notes: Field,
    /// The page's `description` and `keywords`, ranked.
    pub(super) meta: Field,
    /// The page's title unstemmed, for near and prefix matches.
    pub(super) title_words: Field,
    /// The section's heading unstemmed, for near and prefix matches.
    pub(super) heading_words: Field,
    /// The section's prose unstemmed, for near and prefix matches.
    pub(super) prose_words: Field,
    /// The page's kept words as one term, stemmed and as typed: what a query
    /// naming the whole title matches.
    pub(super) title_exact: Field,
    /// The section's kept words as one term, stemmed and as typed: what a query
    /// naming the whole heading matches.
    pub(super) heading_exact: Field,
}

/// The index's one writer, and what was published when it last indexed —
/// every page, by address, read or not — once it has.
pub(super) struct Indexer {
    /// The writer every change goes through.
    writer: IndexWriter,
    /// What was published when it last indexed; `None` before it has.
    published: Option<Published>,
    /// The code reference's pages indexed, by address, each with a hash of
    /// what it reads: a page is indexed again only when that changed.
    code: BTreeMap<String, u64>,
}

/// One section, ready to be a tantivy document.
pub(super) struct Entry<'a> {
    /// The page the section is on.
    pub(super) page: &'a Page,
    /// The section's heading; a slide's and a code page's is the page's title.
    pub(super) heading: &'a str,
    /// The section's address, with its anchor when it has one.
    pub(super) url: String,
    /// The headings down to the section, its page's title first.
    pub(super) path: Vec<String>,
    /// Its heading's level; 0 for the text before a page's first heading.
    pub(super) depth: u8,
    /// Its place on its page, from 0.
    pub(super) order: usize,
    /// The section's prose, whitespace squeezed: a slide's headings and text
    /// together; a code page's doc comment and the prose that adds to it.
    pub(super) prose: &'a str,
    /// The section's code, whitespace squeezed; a code page's declaration.
    pub(super) code: &'a str,
    /// A slide's speaker notes; empty for any other page.
    pub(super) notes: &'a str,
    /// The page's `description` and `keywords` as one line of words.
    pub(super) meta: &'a str,
}

impl Search {
    /// Indexes what the document `entry` publishes, among the documents of `folder`.
    pub fn build(folder: &Folder, entry: &Path) -> Self {
        let mut schema = Schema::builder();
        let text = |tokenizer: &str, record: IndexRecordOption, stored: bool| {
            let options = TextOptions::default().set_indexing_options(
                TextFieldIndexing::default()
                    .set_tokenizer(tokenizer)
                    .set_index_option(record),
            );
            if stored {
                options.set_stored()
            } else {
                options
            }
        };
        let ranked = |stored| text(STEMMED, IndexRecordOption::WithFreqsAndPositions, stored);
        let plain = text(PLAIN, IndexRecordOption::Basic, false);
        let raw = text(RAW, IndexRecordOption::Basic, false);
        let fields = Fields {
            // Indexed whole, so a page's sections are deleted by its address.
            page: schema.add_text_field("page", STRING | STORED),
            url: schema.add_text_field("url", STORED),
            path: schema.add_text_field("path", STORED),
            title: schema.add_text_field("title", ranked(true)),
            heading: schema.add_text_field("heading", ranked(true)),
            prose: schema.add_text_field("prose", ranked(true)),
            code: schema.add_text_field("code", text(CODE, IndexRecordOption::WithFreqs, false)),
            code_text: schema.add_text_field("code_text", STORED),
            notes: schema.add_text_field("notes", ranked(true)),
            meta: schema.add_text_field("meta", ranked(true)),
            title_words: schema.add_text_field("title_words", plain.clone()),
            heading_words: schema.add_text_field("heading_words", plain.clone()),
            prose_words: schema.add_text_field("prose_words", plain),
            title_exact: schema.add_text_field("title_exact", raw.clone()),
            heading_exact: schema.add_text_field("heading_exact", raw),
        };
        for name in ["depth", "order", "nav", PLACE] {
            schema.add_u64_field(name, FAST);
        }
        // Sections stay in reading order, however their pages were indexed,
        // so sections that score alike rank as they read.
        let tantivy = tantivy::Index::builder()
            .schema(schema.build())
            .settings(IndexSettings {
                sort_by_field: Some(IndexSortByField {
                    field: PLACE.to_string(),
                    order: Order::Asc,
                }),
                ..IndexSettings::default()
            })
            .create_in_ram()
            .expect("an index in memory can always be made");
        tantivy.tokenizers().register(
            CODE,
            TextAnalyzer::builder(WhitespaceTokenizer::default())
                .filter(LowerCaser)
                .build(),
        );
        let analyzer = |name: &str| {
            tantivy
                .tokenizers()
                .get(name)
                .expect("tantivy registers its default and en_stem tokenizers")
        };
        let (stemmed, plain) = (analyzer(STEMMED), analyzer(PLAIN));
        // One thread at the smallest budget tantivy allows, 15 MB: a docs
        // folder is small, and the index lives in memory.
        let writer: IndexWriter = tantivy
            .writer_with_num_threads(1, 15_000_000)
            .expect("an index in memory has no lock to contend for");
        // It merges only when told, after each change (`compact`).
        writer.set_merge_policy(Box::new(NoMergePolicy));
        let reader = tantivy
            .reader_builder()
            .reload_policy(ReloadPolicy::Manual)
            .try_into()
            .expect("an index in memory can always be read");
        let searcher = reader.searcher();
        let search = Self {
            fields,
            reader,
            indexer: Mutex::new(Some(Indexer {
                writer,
                published: None,
                code: BTreeMap::new(),
            })),
            stemmed,
            plain,
            entry: entry.to_path_buf(),
            snapshot: RwLock::new(Arc::new(Snapshot::new(searcher, BTreeMap::new()))),
        };
        search.index(folder, &[]);
        search
    }

    /// Indexes what `entry` publishes, commits it once and lets the writer
    /// go, threads and all, with what it kept between saves: for files that
    /// never change, such as a published version's.
    pub fn frozen(folder: &Folder, entry: &Path) -> Self {
        let search = Self::build(folder, entry);
        if let Some(indexer) = lock(&search.indexer).take() {
            let _ = indexer.writer.wait_merging_threads();
        }
        search
    }

    /// Brings the index up to what is published now, a page at a time. When
    /// `paths` can change what is published ([`Published::moved_by`]), it is
    /// found again, whole: a page no longer published leaves; a page newly
    /// published, or whose unit — kind, trail, document, address, place in
    /// the nav — differs, or whose file is one of `paths` or under one, is
    /// read again. Otherwise what is published is as it was, and only the
    /// pages `paths` reach are read again. Every other page stays as it was
    /// indexed. All in one commit, then compacted, so the index answers as
    /// one built fresh would. A frozen index has no writer, and stays as it
    /// is.
    pub(super) fn index(&self, folder: &Folder, paths: &[PathBuf]) {
        let mut indexer = lock(&self.indexer);
        let Some(Indexer {
            writer,
            published,
            code,
        }) = indexer.as_mut()
        else {
            return;
        };
        let read = |unit: &Unit| paths.iter().any(|path| unit.reached(path));
        let mut pages = self
            .snapshot
            .read()
            .unwrap_or_else(|p| p.into_inner())
            .pages
            .clone();
        let remove = |url: &str, pages: &mut Pages| {
            writer.delete_term(Term::from_field_text(self.fields.page, url));
            pages.remove(url);
        };
        // Each document is loaded once per pass, and its widgets read once,
        // through the pass's own cache: what a page's tags expand to is what
        // its page shows now.
        let (found, mut pass, again): (Option<Published>, Pass, Vec<Unit>) = match published {
            Some(was) if !was.moved_by(paths) => {
                let again: Vec<Unit> = was
                    .units
                    .values()
                    .filter(|unit| read(unit))
                    .cloned()
                    .collect();
                for unit in &again {
                    remove(&unit.url(), &mut pages);
                }
                let documents = std::mem::take(&mut was.documents);
                (None, Pass::with(folder, documents), again)
            }
            _ => {
                let mut pass = Pass::new(folder);
                let now = Published::find(&mut pass, &self.entry);
                let none = BTreeMap::new();
                let was = published.as_ref().map_or(&none, |was| &was.units);
                for (url, unit) in was {
                    if now
                        .units
                        .get(url)
                        .is_none_or(|now| now != unit || read(now))
                    {
                        remove(url, &mut pages);
                    }
                }
                let again = now
                    .units
                    .iter()
                    .filter(|(url, unit)| {
                        was.get(*url).is_none_or(|was| was != *unit || read(unit))
                    })
                    .map(|(_, unit)| unit.clone())
                    .collect();
                (Some(now), pass, again)
            }
        };
        for unit in &again {
            let Some(shown) = &unit.shown_in else {
                continue;
            };
            if let Some(set) = pass.widgets(shown) {
                self.add(writer, unit, set, &mut pages);
            }
        }
        self.add_code(writer, code, folder, paths, &mut pages);
        let documents = pass.into_documents();
        let committed = writer.commit().is_ok();
        match (found, published.as_mut()) {
            (Some(mut now), _) if committed => {
                now.documents = documents;
                *published = Some(now);
            }
            (None, Some(was)) => was.documents = documents,
            _ => {}
        }
        if !committed {
            // Back to the last commit, which `published` and `pages` describe.
            let _ = writer.rollback();
            return;
        }
        compact(writer);
        let _ = self.reader.reload();
        *self.snapshot.write().unwrap_or_else(|p| p.into_inner()) =
            Arc::new(Snapshot::new(self.reader.searcher(), pages));
    }

    /// Every page published as the index last found it, by address.
    #[cfg(test)]
    pub(super) fn units(&self) -> BTreeMap<String, Unit> {
        lock(&self.indexer)
            .as_ref()
            .and_then(|indexer| indexer.published.as_ref())
            .map(|published| published.units.clone())
            .unwrap_or_default()
    }

    /// Adds the sections of one page, its content rendered as its page
    /// shows it, with the tags of `widgets` expanded, and its record.
    pub(super) fn add(
        &self,
        writer: &IndexWriter,
        unit: &Unit,
        widgets: &Widgets,
        pages: &mut Pages,
    ) {
        let Ok(source) = std::fs::read_to_string(&unit.file) else {
            return;
        };
        let front = FrontMatter::read(&source);
        if front.search == Some(false) {
            return;
        }
        let read = read(&crate::page::content(widgets, &unit.file, source.clone()));
        let title = match unit.kind {
            PageKind::Slide => slide_title(&source, &read, unit.name.as_deref().unwrap_or("")),
            _ => crate::markup::title(&source, &unit.file),
        };
        let page = Page {
            title,
            url: unit.url(),
            trail: unit.trail.clone(),
            document: unit.document.clone(),
            kind: unit.kind,
            lede: read.lede.clone(),
            nav: unit.nav,
            title_stems: BTreeSet::new(),
            meta_stems: self.stems(&front.meta),
        };
        let page = Page {
            title_stems: self.stems(&page.title),
            ..page
        };
        let add = |entry: Entry| self.add_entry(writer, entry);
        match unit.kind {
            // A slide is one section, at its number: all its text, and its notes.
            PageKind::Slide => {
                let prose: Vec<&str> = read
                    .sections
                    .iter()
                    .flat_map(|s| [s.heading.as_str(), s.prose.as_str()])
                    .collect();
                let code: Vec<&str> = read.sections.iter().map(|s| s.code.as_str()).collect();
                let notes: Vec<String> = crate::markup::notes(&source)
                    .into_iter()
                    .map(|note| note.text)
                    .collect();
                add(Entry {
                    page: &page,
                    heading: &page.title,
                    url: page.url.clone(),
                    path: vec![page.title.clone()],
                    depth: 1,
                    order: 0,
                    prose: &squeeze(&prose.join(" ")),
                    code: &squeeze(&code.join(" ")),
                    notes: &squeeze(&notes.join(" ")),
                    meta: &front.meta,
                });
            }
            PageKind::Page | PageKind::Chapter => {
                let mut above: Vec<(u8, String)> = Vec::new();
                for (order, section) in read.sections.iter().enumerate() {
                    above.retain(|(level, _)| *level < section.level || section.level == 0);
                    if section.level > 0 {
                        above.push((section.level, section.heading.clone()));
                    }
                    let mut path: Vec<String> = above.iter().map(|(_, h)| h.clone()).collect();
                    if path.first() != Some(&page.title) {
                        path.insert(0, page.title.clone());
                    }
                    // As `page::doc` lays them out: with more than one
                    // chapter, each one's ids carry its name, and the chapter
                    // is an id itself.
                    let anchor = match (&section.id, &unit.name) {
                        (Some(id), Some(name)) => Some(format!("{name}--{id}")),
                        (Some(id), None) => Some(id.clone()),
                        (None, Some(name)) => Some(name.clone()),
                        (None, None) => None,
                    };
                    add(Entry {
                        page: &page,
                        heading: &section.heading,
                        url: match anchor {
                            Some(anchor) => format!("{}#{anchor}", unit.address),
                            None => unit.address.clone(),
                        },
                        path,
                        depth: section.level,
                        order,
                        prose: &section.prose,
                        code: &section.code,
                        notes: "",
                        meta: &front.meta,
                    });
                }
            }
        }
        pages.insert(page.url.clone(), page);
    }

    /// Indexes the served site's code reference as it reads now, when
    /// `paths` reach it — its code, its prose, its document file — or on the
    /// first pass: each page one section, its name, its doc and its
    /// declaration, after every page the nav reaches. Only the pages whose
    /// text changed, came or went are written.
    fn add_code(
        &self,
        writer: &IndexWriter,
        known: &mut BTreeMap<String, u64>,
        folder: &Folder,
        paths: &[PathBuf],
        pages: &mut Pages,
    ) {
        let roots = crate::code::input_roots(folder.served());
        let reached = paths.is_empty()
            || paths.iter().any(|path| {
                roots.iter().any(|root| path.starts_with(root))
                    || path
                        .extension()
                        .is_some_and(|ext| ext == "md" || ext == "yml" || ext == "yaml")
            });
        if !reached {
            return;
        }
        let entry = folder.entry();
        let found = crate::code::for_document(&entry.path())
            .map(|index| index.searched())
            .unwrap_or_default();
        let owner = Owner {
            title: entry.title.clone(),
            path: entry.part_url(&entry.path()),
        };
        let mut now = BTreeMap::new();
        for (at, found) in found.iter().enumerate() {
            use std::hash::{Hash, Hasher};
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            (&found.title, &found.trail, &found.prose, &found.code, at).hash(&mut hasher);
            let hash = hasher.finish();
            now.insert(found.url.clone(), hash);
            if known.get(&found.url) == Some(&hash) {
                continue;
            }
            writer.delete_term(Term::from_field_text(self.fields.page, &found.url));
            // Its doc as its page reads it: Markdown as text, code fences
            // as code.
            let prose = squeeze(&strip_tags(&crate::page::markdown::markdown(&found.prose)));
            let page = Page {
                title: found.title.clone(),
                url: found.url.clone(),
                trail: found.trail.clone(),
                document: owner.clone(),
                kind: PageKind::Page,
                lede: prose.split(". ").next().unwrap_or("").to_string(),
                // After every page the nav reaches.
                nav: CODE_NAV + at as u64,
                title_stems: self.stems(&found.title),
                meta_stems: BTreeSet::new(),
            };
            self.add_entry(
                writer,
                Entry {
                    page: &page,
                    heading: &page.title,
                    url: page.url.clone(),
                    path: vec![page.title.clone()],
                    depth: 1,
                    order: 0,
                    prose: &prose,
                    code: &squeeze(&found.code),
                    notes: "",
                    meta: "",
                },
            );
            pages.insert(page.url.clone(), page);
        }
        for url in known.keys() {
            if !now.contains_key(url) {
                writer.delete_term(Term::from_field_text(self.fields.page, url));
                pages.remove(url);
            }
        }
        *known = now;
    }

    /// Adds `entry` as one tantivy document through `writer`, its fields filled
    /// and its place in reading order set.
    pub(super) fn add_entry(&self, writer: &IndexWriter, entry: Entry) {
        let fields = self.fields;
        let schema = writer.index().schema();
        let fast = |name: &str| schema.get_field(name).expect("a fast field of the schema");
        let mut doc = TantivyDocument::default();
        doc.add_text(fields.page, &entry.page.url);
        doc.add_text(fields.url, &entry.url);
        for label in &entry.path {
            doc.add_text(fields.path, label);
        }
        for (ranked, words, text) in [
            (
                fields.title,
                Some(fields.title_words),
                entry.page.title.as_str(),
            ),
            (fields.heading, Some(fields.heading_words), entry.heading),
            (fields.prose, Some(fields.prose_words), entry.prose),
            (fields.notes, None, entry.notes),
            (fields.meta, None, entry.meta),
        ] {
            doc.add_text(ranked, text);
            if let Some(words) = words {
                doc.add_text(words, text);
            }
        }
        doc.add_text(fields.code, expand_code(entry.code));
        doc.add_text(fields.code_text, entry.code);
        for (field, text) in [
            (fields.title_exact, entry.page.title.as_str()),
            (fields.heading_exact, entry.heading),
        ] {
            let words = self.words(text, false);
            let kept = kept(&words);
            doc.add_text(field, joined(&kept, |word| &word.stem));
            doc.add_text(field, joined(&kept, |word| &word.typed));
        }
        doc.add_u64(fast("depth"), u64::from(entry.depth));
        doc.add_u64(fast("order"), entry.order as u64);
        doc.add_u64(fast("nav"), entry.page.nav);
        doc.add_u64(fast(PLACE), entry.page.nav << 32 | entry.order as u64);
        let _ = writer.add_document(doc);
    }
}

/// Merges the index into one segment, leaving out the sections deleted. A
/// deleted section still counts in how many sections hold a word until its
/// segment is merged — in a word's BM25 score, and in whether the index
/// holds it at all — so without this a page saved would rank, and
/// near-match, otherwise than in an index built fresh.
fn compact(writer: &mut IndexWriter) {
    let Ok(segments) = writer.index().searchable_segment_metas() else {
        return;
    };
    if segments.len() > 1 || segments.iter().any(|segment| segment.has_deletes()) {
        let ids: Vec<_> = segments.iter().map(|segment| segment.id()).collect();
        let _ = writer.merge(&ids).wait();
    }
}