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::UserSignedIn => {
193 lb.build_index().await.log_and_ignore();
194 }
195 Event::MetadataChanged(_) => {
196 if let Some(replacement_index) =
197 SearchMetadata::populate(&lb).await.log_and_ignore()
198 {
199 let current_index = lb.search.metadata_index.read().await.clone();
200 let deleted_ids = replacement_index.compute_deleted(¤t_index);
201 *lb.search.metadata_index.write().await = replacement_index;
202 lb.update_tantivy(deleted_ids, vec![]).await;
203 }
204 }
205 Event::DocumentWritten(id, _) => {
206 lb.update_tantivy(vec![id], vec![id]).await;
207 }
208 _ => {}
209 };
210 }
211 });
212 }
213 }
214
215 async fn update_tantivy(&self, delete: Vec<Uuid>, add: Vec<Uuid>) {
216 let mut index_writer: IndexWriter = self.search.tantivy_index.writer(50_000_000).unwrap();
217 let schema = self.search.tantivy_index.schema();
218 let id_field = schema.get_field("id").unwrap();
219 let id_str = schema.get_field("id_str").unwrap();
220 let content = schema.get_field("content").unwrap();
221
222 for id in delete {
223 let term = Term::from_field_bytes(id_field, id.as_bytes());
224 index_writer.delete_term(term);
225 }
226
227 for id in add {
228 let id_bytes = id.as_bytes().as_slice();
229 let id_string = id.to_string();
230 let Some(file) = self
231 .search
232 .metadata_index
233 .read()
234 .await
235 .files
236 .iter()
237 .find(|f| f.id == id)
238 .cloned()
239 else {
240 continue;
241 };
242
243 if !file.name.ends_with(".md") || file.is_folder() {
244 continue;
245 };
246
247 let Ok(doc) = self.read_document(file.id, false).await else {
248 error!("failed to read doc");
249 continue;
250 };
251
252 if doc.len() > CONTENT_MAX_LEN_BYTES {
253 continue;
254 };
255
256 let Ok(doc) = String::from_utf8(doc) else {
257 continue;
258 };
259
260 index_writer
261 .add_document(doc!(
262 id_field => id_bytes,
263 id_str => id_string,
264 content => doc,
265 ))
266 .unwrap();
267 }
268
269 index_writer.commit().unwrap();
270 }
271}
272
273impl Default for SearchIndex {
274 fn default() -> Self {
275 let mut schema_builder = Schema::builder();
276 schema_builder.add_bytes_field("id", INDEXED | STORED);
277 schema_builder.add_text_field("id_str", TEXT | STORED);
278 schema_builder.add_text_field("content", TEXT | STORED);
279
280 let schema = schema_builder.build();
281
282 let index = Index::create_in_ram(schema.clone());
283
284 let reader = index
286 .reader_builder()
287 .reload_policy(ReloadPolicy::OnCommitWithDelay)
288 .try_into()
289 .unwrap();
290
291 Self {
292 ready: Default::default(),
293 tantivy_index: index,
294 tantivy_reader: reader,
295 metadata_index: Default::default(),
296 }
297 }
298}
299
300#[derive(Debug, Serialize)]
301pub struct ContentMatch {
302 pub paragraph: String,
303 pub matched_indices: Vec<usize>,
304 pub score: i64,
305}
306
307impl SearchResult {
308 pub fn id(&self) -> Uuid {
309 match self {
310 SearchResult::DocumentMatch { id, .. } | SearchResult::PathMatch { id, .. } => *id,
311 }
312 }
313
314 pub fn path(&self) -> &str {
315 match self {
316 SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => path,
317 }
318 }
319
320 pub fn name(&self) -> &str {
321 match self {
322 SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => {
323 path.split('/').next_back().unwrap_or_default()
324 }
325 }
326 }
327
328 pub fn score(&self) -> i64 {
329 match self {
330 SearchResult::DocumentMatch { content_matches, .. } => content_matches
331 .iter()
332 .map(|m| m.score)
333 .max()
334 .unwrap_or_default(),
335 SearchResult::PathMatch { score, .. } => *score,
336 }
337 }
338}
339
340#[derive(Default, Clone)]
341pub struct SearchMetadata {
342 files: Vec<File>,
343 paths: Vec<(Uuid, String)>,
344 suggested_docs: Vec<Uuid>,
345}
346
347impl SearchMetadata {
348 async fn populate(lb: &Lb) -> LbResult<Self> {
349 let files = lb.list_metadatas().await?;
350 let paths = lb.list_paths_with_ids(None).await?;
351 let suggested_docs = lb.suggested_docs(RankingWeights::default()).await?;
352
353 Ok(SearchMetadata { files, paths, suggested_docs })
354 }
355
356 fn compute_deleted(&self, old: &SearchMetadata) -> Vec<Uuid> {
357 let mut deleted_ids = vec![];
358
359 for old_file in &old.files {
360 if !self.files.iter().any(|new_f| new_f.id == old_file.id) {
361 deleted_ids.push(old_file.id);
362 }
363 }
364
365 deleted_ids
366 }
367
368 fn empty_search(&self) -> LbResult<Vec<SearchResult>> {
369 let mut results = vec![];
370
371 for id in &self.suggested_docs {
372 let path = self
373 .paths
374 .iter()
375 .find(|(path_id, _)| id == path_id)
376 .map(|(_, path)| path.clone())
377 .unwrap_or_default();
378
379 results.push(SearchResult::PathMatch {
380 id: *id,
381 path,
382 matched_indices: vec![],
383 score: 0,
384 });
385 }
386
387 Ok(results)
388 }
389
390 fn path_search(&self, query: &str) -> LbResult<Vec<SearchResult>> {
391 let mut results = self.path_candidates(query)?;
392 self.score_paths(&mut results);
393
394 results.sort_by_key(|r| -r.score());
395
396 if let Some(result) = self.id_match(query) {
397 results.insert(0, result);
398 }
399
400 Ok(results)
401 }
402
403 fn id_match(&self, query: &str) -> Option<SearchResult> {
404 if query.len() < 8 {
405 return None;
406 }
407
408 let query = if query.starts_with("lb://") {
409 query.replacen("lb://", "", 1)
410 } else {
411 query.to_string()
412 };
413
414 for (id, path) in &self.paths {
415 if id.to_string().contains(&query) {
416 return Some(SearchResult::PathMatch {
417 id: *id,
418 path: path.clone(),
419 matched_indices: vec![],
420 score: 100,
421 });
422 }
423 }
424
425 None
426 }
427
428 fn path_candidates(&self, query: &str) -> LbResult<Vec<SearchResult>> {
429 let mut search_results = vec![];
430
431 for (id, path) in &self.paths {
432 let mut matched_indices = vec![];
433
434 let mut query_iter = query.chars().rev();
435 let mut current_query_char = query_iter.next();
436
437 for (path_ind, path_char) in path.char_indices().rev() {
438 if let Some(qc) = current_query_char {
439 if qc.eq_ignore_ascii_case(&path_char) {
440 matched_indices.push(path_ind);
441 current_query_char = query_iter.next();
442 }
443 } else {
444 break;
445 }
446 }
447
448 if current_query_char.is_none() {
449 search_results.push(SearchResult::PathMatch {
450 id: *id,
451 path: path.clone(),
452 matched_indices,
453 score: 0,
454 });
455 }
456 }
457 Ok(search_results)
458 }
459
460 fn score_paths(&self, candidates: &mut [SearchResult]) {
461 let smaller_paths = 10;
463 let suggested = 10;
464 let filename = 30;
465 let editable = 3;
466
467 candidates.sort_by_key(|a| a.path().len());
468
469 for i in 0..smaller_paths {
471 if let Some(SearchResult::PathMatch { id: _, path: _, matched_indices: _, score }) =
472 candidates.get_mut(i)
473 {
474 *score = (smaller_paths - i) as i64;
475 }
476 }
477
478 for cand in candidates.iter_mut() {
480 if self.suggested_docs.contains(&cand.id()) {
481 if let SearchResult::PathMatch { id: _, path: _, matched_indices: _, score } = cand
482 {
483 *score += suggested;
484 }
485 }
486 }
487
488 for cand in candidates.iter_mut() {
490 if let SearchResult::PathMatch { id: _, path, matched_indices, score } = cand {
491 let mut name_match = 0;
492 let mut name_size = 0;
493
494 for (i, c) in path.char_indices().rev() {
495 if c == '/' {
496 break;
497 }
498 name_size += 1;
499 if matched_indices.contains(&i) {
500 name_match += 1;
501 }
502 }
503
504 let match_portion = name_match as f32 / name_size.max(1) as f32;
505 *score += (match_portion * filename as f32) as i64;
506 }
507 }
508
509 for cand in candidates.iter_mut() {
511 if let SearchResult::PathMatch { id: _, path, matched_indices: _, score } = cand {
512 if path.ends_with(".md") || path.ends_with(".svg") {
513 *score += editable;
514 }
515 }
516 }
517 }
518}