1use crate::model::errors::{LbResult, Unexpected};
2use crate::model::file::File;
3use crate::service::activity::RankingWeights;
4use crate::service::events::Event;
5use crate::{Lb, tokio_spawn};
6use serde::Serialize;
7use std::ops::Range;
8use std::sync::Arc;
9use std::sync::atomic::AtomicBool;
10use tantivy::collector::TopDocs;
11use tantivy::query::QueryParser;
12use tantivy::schema::{INDEXED, STORED, Schema, TEXT, Value};
13use tantivy::snippet::SnippetGenerator;
14use tantivy::{Index, IndexReader, IndexWriter, ReloadPolicy, TantivyDocument, Term, doc};
15use tokio::sync::RwLock;
16use uuid::Uuid;
17
18const CONTENT_MAX_LEN_BYTES: usize = 128 * 1024; #[derive(Clone)]
21pub struct SearchIndex {
22 pub ready: Arc<AtomicBool>,
23
24 pub metadata_index: Arc<RwLock<SearchMetadata>>,
25 pub tantivy_index: Index,
26 pub tantivy_reader: IndexReader,
27}
28
29#[derive(Copy, Clone, Debug)]
30pub enum SearchConfig {
31 Paths,
32 Documents,
33 PathsAndDocuments,
34}
35
36#[derive(Debug)]
37pub enum SearchResult {
38 DocumentMatch { id: Uuid, path: String, content_matches: Vec<ContentMatch> },
39 PathMatch { id: Uuid, path: String, matched_indices: Vec<usize>, score: i64 },
40}
41
42impl Lb {
43 #[instrument(level = "debug", skip(self, input), err(Debug))]
61 pub async fn search(&self, input: &str, cfg: SearchConfig) -> LbResult<Vec<SearchResult>> {
62 if input.is_empty() {
64 return self.search.metadata_index.read().await.empty_search();
65 }
66
67 match cfg {
68 SearchConfig::Paths => {
69 let mut results = self.search.metadata_index.read().await.path_search(input)?;
70 results.truncate(5);
71 Ok(results)
72 }
73 SearchConfig::Documents => {
74 let mut results = self.search_content(input).await?;
75 results.truncate(10);
76 Ok(results)
77 }
78 SearchConfig::PathsAndDocuments => {
79 let mut results = self.search.metadata_index.read().await.path_search(input)?;
80 results.truncate(4);
81 results.append(&mut self.search_content(input).await?);
82 Ok(results)
83 }
84 }
85 }
86
87 async fn search_content(&self, input: &str) -> LbResult<Vec<SearchResult>> {
88 let searcher = self.search.tantivy_reader.searcher();
89 let schema = self.search.tantivy_index.schema();
90 let id_field = schema.get_field("id").unwrap();
91 let content = schema.get_field("content").unwrap();
92
93 let query_parser = QueryParser::for_index(&self.search.tantivy_index, vec![content]);
94 let mut results = vec![];
95
96 if let Ok(query) = query_parser.parse_query(input) {
97 let mut snippet_generator =
98 SnippetGenerator::create(&searcher, &query, content).map_unexpected()?;
99 snippet_generator.set_max_num_chars(100);
100
101 let top_docs = searcher
102 .search(&query, &TopDocs::with_limit(10))
103 .map_unexpected()?;
104
105 for (_score, doc_address) in top_docs {
106 let retrieved_doc: TantivyDocument = searcher.doc(doc_address).map_unexpected()?;
107 let id = Uuid::from_slice(
108 retrieved_doc
109 .get_first(id_field)
110 .map(|val| val.as_bytes().unwrap_or_default())
111 .unwrap_or_default(),
112 )
113 .map_unexpected()?;
114
115 let snippet = snippet_generator.snippet_from_doc(&retrieved_doc);
116 let path = self
117 .search
118 .metadata_index
119 .read()
120 .await
121 .paths
122 .iter()
123 .find(|(path_id, _)| *path_id == id)
124 .map(|(_, path)| path.to_string())
125 .unwrap_or_default();
126
127 results.push(SearchResult::DocumentMatch {
128 id,
129 path,
130 content_matches: vec![ContentMatch {
131 paragraph: snippet.fragment().to_string(),
132 matched_indices: Self::highlight_to_matches(snippet.highlighted()),
133 score: 0,
134 }],
135 });
136 }
137 }
138 Ok(results)
139 }
140
141 fn highlight_to_matches(ranges: &[Range<usize>]) -> Vec<usize> {
142 let mut matches = vec![];
143 for range in ranges {
144 for i in range.clone() {
145 matches.push(i);
146 }
147 }
148
149 matches
150 }
151
152 #[instrument(level = "debug", skip(self), err(Debug))]
153 pub async fn build_index(&self) -> LbResult<()> {
154 if self.keychain.get_account().is_err() {
157 return Ok(());
158 }
159
160 let new_metadata = SearchMetadata::populate(self).await?;
161
162 let (deleted_ids, all_current_ids) = {
163 let mut current_metadata = self.search.metadata_index.write().await;
164 let deleted = new_metadata.compute_deleted(¤t_metadata);
165 let current = new_metadata.files.iter().map(|f| f.id).collect::<Vec<_>>();
166 *current_metadata = new_metadata;
167 (deleted, current)
168 };
169
170 self.update_tantivy(deleted_ids, all_current_ids).await;
171
172 Ok(())
173 }
174
175 #[instrument(level = "debug", skip(self))]
176 pub fn setup_search(&self) {
177 if self.config.background_work {
178 let lb = self.clone();
179 let mut rx = self.subscribe();
180 tokio_spawn!(async move {
181 lb.build_index().await.unwrap();
182 loop {
183 let evt = match rx.recv().await {
184 Ok(evt) => evt,
185 Err(err) => {
186 error!("failed to receive from a channel {err}");
187 return;
188 }
189 };
190
191 match evt {
192 Event::MetadataChanged => {
193 if let Some(replacement_index) =
194 SearchMetadata::populate(&lb).await.log_and_ignore()
195 {
196 let current_index = lb.search.metadata_index.read().await.clone();
197 let deleted_ids = replacement_index.compute_deleted(¤t_index);
198 *lb.search.metadata_index.write().await = replacement_index;
199 lb.update_tantivy(deleted_ids, vec![]).await;
200 }
201 }
202 Event::DocumentWritten(id, _) => {
203 lb.update_tantivy(vec![id], vec![id]).await;
204 }
205 _ => {}
206 };
207 }
208 });
209 }
210 }
211
212 async fn update_tantivy(&self, delete: Vec<Uuid>, add: Vec<Uuid>) {
213 let mut index_writer: IndexWriter = self.search.tantivy_index.writer(50_000_000).unwrap();
214 let schema = self.search.tantivy_index.schema();
215 let id_field = schema.get_field("id").unwrap();
216 let id_str = schema.get_field("id_str").unwrap();
217 let content = schema.get_field("content").unwrap();
218
219 for id in delete {
220 let term = Term::from_field_bytes(id_field, id.as_bytes());
221 index_writer.delete_term(term);
222 }
223
224 for id in add {
225 let id_bytes = id.as_bytes().as_slice();
226 let id_string = id.to_string();
227 let Some(file) = self
228 .search
229 .metadata_index
230 .read()
231 .await
232 .files
233 .iter()
234 .find(|f| f.id == id)
235 .cloned()
236 else {
237 continue;
238 };
239
240 if !file.name.ends_with(".md") || file.is_folder() {
241 continue;
242 };
243
244 let Ok(doc) = self.read_document(file.id, false).await else {
245 continue;
246 };
247
248 if doc.len() > CONTENT_MAX_LEN_BYTES {
249 continue;
250 };
251
252 let Ok(doc) = String::from_utf8(doc) else {
253 continue;
254 };
255
256 index_writer
257 .add_document(doc!(
258 id_field => id_bytes,
259 id_str => id_string,
260 content => doc,
261 ))
262 .unwrap();
263 }
264
265 index_writer.commit().unwrap();
266 }
267}
268
269impl Default for SearchIndex {
270 fn default() -> Self {
271 let mut schema_builder = Schema::builder();
272 schema_builder.add_bytes_field("id", INDEXED | STORED);
273 schema_builder.add_text_field("id_str", TEXT | STORED);
274 schema_builder.add_text_field("content", TEXT | STORED);
275
276 let schema = schema_builder.build();
277
278 let index = Index::create_in_ram(schema.clone());
279
280 let reader = index
282 .reader_builder()
283 .reload_policy(ReloadPolicy::OnCommitWithDelay)
284 .try_into()
285 .unwrap();
286
287 Self {
288 ready: Default::default(),
289 tantivy_index: index,
290 tantivy_reader: reader,
291 metadata_index: Default::default(),
292 }
293 }
294}
295
296#[derive(Debug, Serialize)]
297pub struct ContentMatch {
298 pub paragraph: String,
299 pub matched_indices: Vec<usize>,
300 pub score: i64,
301}
302
303impl SearchResult {
304 pub fn id(&self) -> Uuid {
305 match self {
306 SearchResult::DocumentMatch { id, .. } | SearchResult::PathMatch { id, .. } => *id,
307 }
308 }
309
310 pub fn path(&self) -> &str {
311 match self {
312 SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => path,
313 }
314 }
315
316 pub fn name(&self) -> &str {
317 match self {
318 SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => {
319 path.split('/').next_back().unwrap_or_default()
320 }
321 }
322 }
323
324 pub fn score(&self) -> i64 {
325 match self {
326 SearchResult::DocumentMatch { content_matches, .. } => content_matches
327 .iter()
328 .map(|m| m.score)
329 .max()
330 .unwrap_or_default(),
331 SearchResult::PathMatch { score, .. } => *score,
332 }
333 }
334}
335
336#[derive(Default, Clone)]
337pub struct SearchMetadata {
338 files: Vec<File>,
339 paths: Vec<(Uuid, String)>,
340 suggested_docs: Vec<Uuid>,
341}
342
343impl SearchMetadata {
344 async fn populate(lb: &Lb) -> LbResult<Self> {
345 let files = lb.list_metadatas().await?;
346 let paths = lb.list_paths_with_ids(None).await?;
347 let suggested_docs = lb.suggested_docs(RankingWeights::default()).await?;
348
349 Ok(SearchMetadata { files, paths, suggested_docs })
350 }
351
352 fn compute_deleted(&self, old: &SearchMetadata) -> Vec<Uuid> {
353 let mut deleted_ids = vec![];
354
355 for old_file in &old.files {
356 if !self.files.iter().any(|new_f| new_f.id == old_file.id) {
357 deleted_ids.push(old_file.id);
358 }
359 }
360
361 deleted_ids
362 }
363
364 fn empty_search(&self) -> LbResult<Vec<SearchResult>> {
365 let mut results = vec![];
366
367 for id in &self.suggested_docs {
368 let path = self
369 .paths
370 .iter()
371 .find(|(path_id, _)| id == path_id)
372 .map(|(_, path)| path.clone())
373 .unwrap_or_default();
374
375 results.push(SearchResult::PathMatch {
376 id: *id,
377 path,
378 matched_indices: vec![],
379 score: 0,
380 });
381 }
382
383 Ok(results)
384 }
385
386 fn path_search(&self, query: &str) -> LbResult<Vec<SearchResult>> {
387 let mut results = self.path_candidates(query)?;
388 self.score_paths(&mut results);
389
390 results.sort_by_key(|r| -r.score());
391
392 if let Some(result) = self.id_match(query) {
393 results.insert(0, result);
394 }
395
396 Ok(results)
397 }
398
399 fn id_match(&self, query: &str) -> Option<SearchResult> {
400 if query.len() < 8 {
401 return None;
402 }
403
404 let query = if query.starts_with("lb://") {
405 query.replacen("lb://", "", 1)
406 } else {
407 query.to_string()
408 };
409
410 for (id, path) in &self.paths {
411 if id.to_string().contains(&query) {
412 return Some(SearchResult::PathMatch {
413 id: *id,
414 path: path.clone(),
415 matched_indices: vec![],
416 score: 100,
417 });
418 }
419 }
420
421 None
422 }
423
424 fn path_candidates(&self, query: &str) -> LbResult<Vec<SearchResult>> {
425 let mut search_results = vec![];
426
427 for (id, path) in &self.paths {
428 let mut matched_indices = vec![];
429
430 let mut query_iter = query.chars().rev();
431 let mut current_query_char = query_iter.next();
432
433 for (path_ind, path_char) in path.char_indices().rev() {
434 if let Some(qc) = current_query_char {
435 if qc.eq_ignore_ascii_case(&path_char) {
436 matched_indices.push(path_ind);
437 current_query_char = query_iter.next();
438 }
439 } else {
440 break;
441 }
442 }
443
444 if current_query_char.is_none() {
445 search_results.push(SearchResult::PathMatch {
446 id: *id,
447 path: path.clone(),
448 matched_indices,
449 score: 0,
450 });
451 }
452 }
453 Ok(search_results)
454 }
455
456 fn score_paths(&self, candidates: &mut [SearchResult]) {
457 let smaller_paths = 10;
459 let suggested = 10;
460 let filename = 30;
461 let editable = 3;
462
463 candidates.sort_by_key(|a| a.path().len());
464
465 for i in 0..smaller_paths {
467 if let Some(SearchResult::PathMatch { id: _, path: _, matched_indices: _, score }) =
468 candidates.get_mut(i)
469 {
470 *score = (smaller_paths - i) as i64;
471 }
472 }
473
474 for cand in candidates.iter_mut() {
476 if self.suggested_docs.contains(&cand.id()) {
477 if let SearchResult::PathMatch { id: _, path: _, matched_indices: _, score } = cand
478 {
479 *score += suggested;
480 }
481 }
482 }
483
484 for cand in candidates.iter_mut() {
486 if let SearchResult::PathMatch { id: _, path, matched_indices, score } = cand {
487 let mut name_match = 0;
488 let mut name_size = 0;
489
490 for (i, c) in path.char_indices().rev() {
491 if c == '/' {
492 break;
493 }
494 name_size += 1;
495 if matched_indices.contains(&i) {
496 name_match += 1;
497 }
498 }
499
500 let match_portion = name_match as f32 / name_size.max(1) as f32;
501 *score += (match_portion * filename as f32) as i64;
502 }
503 }
504
505 for cand in candidates.iter_mut() {
507 if let SearchResult::PathMatch { id: _, path, matched_indices: _, score } = cand {
508 if path.ends_with(".md") || path.ends_with(".svg") {
509 *score += editable;
510 }
511 }
512 }
513 }
514}