1use 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
32const MAX_PAGES: usize = 10;
35const SECTIONS_PER_PAGE: usize = 3;
36
37#[derive(Debug, Clone, Serialize, PartialEq, Default)]
40pub struct Answer {
41 pub pages: Vec<PageResult>,
42}
43
44#[derive(Debug, Clone, Serialize, PartialEq)]
46pub struct PageResult {
47 pub title: String,
48 pub url: String,
50 pub trail: Vec<String>,
52 pub document: Owner,
53 pub kind: PageKind,
54 pub title_match: bool,
56 pub lede: String,
58 pub sections: Vec<SectionResult>,
60 pub more: usize,
62}
63
64#[derive(Debug, Clone, Serialize, PartialEq)]
67pub struct SectionResult {
68 pub heading: String,
69 pub path: Vec<String>,
71 pub url: String,
73 pub snippet: String,
75 pub words: Vec<String>,
76}
77
78#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
80#[serde(rename_all = "lowercase")]
81pub enum PageKind {
82 Page,
83 Chapter,
84 Slide,
85}
86
87#[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 entry: PathBuf,
102 pages: RwLock<Pages>,
104}
105
106#[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 nav: u64,
117 title_stems: BTreeSet<String>,
120 meta_stems: BTreeSet<String>,
121}
122
123type Pages = BTreeMap<String, Page>;
125
126struct 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 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 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 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 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 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 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;