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::*;
const MAX_PAGES: usize = 10;
const SECTIONS_PER_PAGE: usize = 3;
#[derive(Debug, Clone, Serialize, PartialEq, Default)]
pub struct Answer {
pub pages: Vec<PageResult>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct PageResult {
pub title: String,
pub url: String,
pub trail: Vec<String>,
pub document: Owner,
pub kind: PageKind,
pub title_match: bool,
pub lede: String,
pub sections: Vec<SectionResult>,
pub more: usize,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SectionResult {
pub heading: String,
pub path: Vec<String>,
pub url: String,
pub snippet: String,
pub words: Vec<String>,
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PageKind {
Page,
Chapter,
Slide,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Owner {
pub title: String,
pub path: String,
}
pub struct Search {
fields: Fields,
reader: IndexReader,
indexer: Mutex<Option<Indexer>>,
stemmed: TextAnalyzer,
plain: TextAnalyzer,
entry: PathBuf,
snapshot: RwLock<Arc<Snapshot>>,
}
struct Snapshot {
searcher: Searcher,
pages: Pages,
tokens: Vec<u64>,
}
impl Snapshot {
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,
}
}
}
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)
}
}
#[derive(Debug, Clone)]
struct Page {
title: String,
url: String,
trail: Vec<String>,
document: Owner,
kind: PageKind,
lede: String,
nav: u64,
title_stems: BTreeSet<String>,
meta_stems: BTreeSet<String>,
}
type Pages = BTreeMap<String, Page>;
struct Found {
heading: String,
path: Vec<String>,
url: String,
prose: String,
code: String,
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
impl Search {
pub fn is_live(&self) -> bool {
lock(&self.indexer).is_some()
}
pub fn bytes(&self) -> u64 {
self.reader
.searcher()
.space_usage()
.map(|usage| usage.total().get_bytes())
.unwrap_or(0)
}
pub fn changed(&self, folder: &Folder, paths: &[PathBuf]) {
let matters = |path: &PathBuf| {
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);
}
}
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();
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));
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])),
}
}
let titled = |page: &Page| self.title_match(&parsed, &page.title);
grouped.sort_by(|a, b| {
let (ta, tb) = (titled(a.1), titled(b.1));
ta.cmp(&tb)
.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);
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;