lb_rs/subscribers/
search.rs

1use crate::Lb;
2use crate::model::errors::{LbResult, Unexpected};
3use crate::model::file::File;
4use crate::service::activity::RankingWeights;
5use crate::service::events::Event;
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::{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; // 128kb
19
20#[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    /// Lockbook's search implementation.
44    ///
45    /// Takes an input and a configuration. The configuration describes whether we are searching
46    /// paths, documents or both.
47    ///
48    /// Document searches are handled by [tantivy](https://github.com/quickwit-oss/tantivy), and as
49    /// such support [tantivy's advanced query
50    /// syntax](https://docs.rs/tantivy/latest/tantivy/query/struct.QueryParser.html).
51    /// In the future we plan to ingest a bunch of metadata and expose a full advanced search mode.
52    ///
53    /// Path searches are implemented as a subsequence filter with a number of hueristics to sort
54    /// the results. Preference is given to shorter paths, filename matches, suggested docs, and
55    /// documents that are editable in platform.
56    ///
57    /// Additionally if a path search contains a string, greater than 8 characters long that is
58    /// contained within any of the paths in the search index, that result is returned with the
59    /// highest score. lb:// style ids are also supported.
60    #[instrument(level = "debug", skip(self), err(Debug))]
61    pub async fn search(&self, input: &str, cfg: SearchConfig) -> LbResult<Vec<SearchResult>> {
62        // show suggested docs if the input string is empty
63        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 we haven't signed in yet, we'll leave our index entry and our event subscriber will
155        // handle the state change
156        if self.keychain.get_account().is_err() {
157            return Ok(());
158        }
159
160        let metadata_index = SearchMetadata::populate(self).await?;
161        *self.search.metadata_index.write().await = metadata_index.clone();
162        self.update_tantivy(vec![], metadata_index.files.iter().map(|f| f.id).collect())
163            .await;
164
165        Ok(())
166    }
167
168    #[instrument(level = "debug", skip(self))]
169    pub fn setup_search(&self) {
170        if self.config.background_work {
171            let lb = self.clone();
172            let mut rx = self.subscribe();
173            tokio::spawn(async move {
174                lb.build_index().await.unwrap();
175                loop {
176                    let evt = match rx.recv().await {
177                        Ok(evt) => evt,
178                        Err(err) => {
179                            error!("failed to receive from a channel {err}");
180                            return;
181                        }
182                    };
183
184                    match evt {
185                        Event::MetadataChanged => {
186                            if let Some(replacement_index) =
187                                SearchMetadata::populate(&lb).await.log_and_ignore()
188                            {
189                                let current_index = lb.search.metadata_index.read().await.clone();
190                                let deleted_ids = replacement_index.compute_deleted(&current_index);
191                                *lb.search.metadata_index.write().await = replacement_index;
192                                lb.update_tantivy(vec![], deleted_ids).await;
193                            }
194                        }
195                        Event::DocumentWritten(id, _) => {
196                            lb.update_tantivy(vec![id], vec![id]).await;
197                        }
198                        _ => {}
199                    };
200                }
201            });
202        }
203    }
204
205    async fn update_tantivy(&self, delete: Vec<Uuid>, add: Vec<Uuid>) {
206        let mut index_writer: IndexWriter = self.search.tantivy_index.writer(50_000_000).unwrap();
207        let schema = self.search.tantivy_index.schema();
208        let id_field = schema.get_field("id").unwrap();
209        let id_str = schema.get_field("id_str").unwrap();
210        let content = schema.get_field("content").unwrap();
211
212        for id in delete {
213            let term = Term::from_field_text(id_str, &id.to_string());
214            index_writer.delete_term(term);
215        }
216
217        for id in add {
218            let id_bytes = id.as_bytes().as_slice();
219            let id_string = id.to_string();
220            let Some(file) = self
221                .search
222                .metadata_index
223                .read()
224                .await
225                .files
226                .iter()
227                .find(|f| f.id == id)
228                .cloned()
229            else {
230                continue;
231            };
232
233            if !file.name.ends_with(".md") || file.is_folder() {
234                continue;
235            };
236
237            let doc = String::from_utf8(self.read_document(file.id, false).await.unwrap()).unwrap();
238
239            if doc.len() > CONTENT_MAX_LEN_BYTES {
240                continue;
241            };
242
243            index_writer
244                .add_document(doc!(
245                    id_field => id_bytes,
246                    id_str => id_string,
247                    content => doc,
248                ))
249                .unwrap();
250        }
251
252        index_writer.commit().unwrap();
253    }
254}
255
256impl Default for SearchIndex {
257    fn default() -> Self {
258        let mut schema_builder = Schema::builder();
259        schema_builder.add_bytes_field("id", STORED);
260        schema_builder.add_text_field("id_str", TEXT | STORED);
261        schema_builder.add_text_field("content", TEXT | STORED);
262
263        let schema = schema_builder.build();
264
265        let index = Index::create_in_ram(schema.clone());
266
267        // doing this here would be a bad idea if not for in-ram empty index
268        let reader = index
269            .reader_builder()
270            .reload_policy(ReloadPolicy::OnCommitWithDelay)
271            .try_into()
272            .unwrap();
273
274        Self {
275            ready: Default::default(),
276            tantivy_index: index,
277            tantivy_reader: reader,
278            metadata_index: Default::default(),
279        }
280    }
281}
282
283#[derive(Debug, Serialize)]
284pub struct ContentMatch {
285    pub paragraph: String,
286    pub matched_indices: Vec<usize>,
287    pub score: i64,
288}
289
290impl SearchResult {
291    pub fn id(&self) -> Uuid {
292        match self {
293            SearchResult::DocumentMatch { id, .. } | SearchResult::PathMatch { id, .. } => *id,
294        }
295    }
296
297    pub fn path(&self) -> &str {
298        match self {
299            SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => path,
300        }
301    }
302
303    pub fn name(&self) -> &str {
304        match self {
305            SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => {
306                path.split('/').next_back().unwrap_or_default()
307            }
308        }
309    }
310
311    pub fn score(&self) -> i64 {
312        match self {
313            SearchResult::DocumentMatch { content_matches, .. } => content_matches
314                .iter()
315                .map(|m| m.score)
316                .max()
317                .unwrap_or_default(),
318            SearchResult::PathMatch { score, .. } => *score,
319        }
320    }
321}
322
323#[derive(Default, Clone)]
324pub struct SearchMetadata {
325    files: Vec<File>,
326    paths: Vec<(Uuid, String)>,
327    suggested_docs: Vec<Uuid>,
328}
329
330impl SearchMetadata {
331    async fn populate(lb: &Lb) -> LbResult<Self> {
332        let files = lb.list_metadatas().await?;
333        let paths = lb.list_paths_with_ids(None).await?;
334        let suggested_docs = lb.suggested_docs(RankingWeights::default()).await?;
335
336        Ok(SearchMetadata { files, paths, suggested_docs })
337    }
338
339    fn compute_deleted(&self, old: &SearchMetadata) -> Vec<Uuid> {
340        let mut deleted_ids = vec![];
341
342        for old_file in &old.files {
343            if !self.files.iter().any(|new_f| new_f.id == old_file.id) {
344                deleted_ids.push(old_file.id);
345            }
346        }
347
348        deleted_ids
349    }
350
351    fn empty_search(&self) -> LbResult<Vec<SearchResult>> {
352        let mut results = vec![];
353
354        for id in &self.suggested_docs {
355            let path = self
356                .paths
357                .iter()
358                .find(|(path_id, _)| id == path_id)
359                .map(|(_, path)| path.clone())
360                .unwrap_or_default();
361
362            results.push(SearchResult::PathMatch {
363                id: *id,
364                path,
365                matched_indices: vec![],
366                score: 0,
367            });
368        }
369
370        Ok(results)
371    }
372
373    fn path_search(&self, query: &str) -> LbResult<Vec<SearchResult>> {
374        let mut results = self.path_candidates(query)?;
375        self.score_paths(&mut results);
376
377        results.sort_by_key(|r| -r.score());
378
379        if let Some(result) = self.id_match(query) {
380            results.insert(0, result);
381        }
382
383        Ok(results)
384    }
385
386    fn id_match(&self, query: &str) -> Option<SearchResult> {
387        if query.len() < 8 {
388            return None;
389        }
390
391        let query = if query.starts_with("lb://") {
392            query.replacen("lb://", "", 1)
393        } else {
394            query.to_string()
395        };
396
397        for (id, path) in &self.paths {
398            if id.to_string().contains(&query) {
399                return Some(SearchResult::PathMatch {
400                    id: *id,
401                    path: path.clone(),
402                    matched_indices: vec![],
403                    score: 100,
404                });
405            }
406        }
407
408        None
409    }
410
411    fn path_candidates(&self, query: &str) -> LbResult<Vec<SearchResult>> {
412        let mut search_results = vec![];
413
414        for (id, path) in &self.paths {
415            let mut matched_indices = vec![];
416
417            let mut query_iter = query.chars().rev();
418            let mut current_query_char = query_iter.next();
419
420            for (path_ind, path_char) in path.char_indices().rev() {
421                if let Some(qc) = current_query_char {
422                    if qc.eq_ignore_ascii_case(&path_char) {
423                        matched_indices.push(path_ind);
424                        current_query_char = query_iter.next();
425                    }
426                } else {
427                    break;
428                }
429            }
430
431            if current_query_char.is_none() {
432                search_results.push(SearchResult::PathMatch {
433                    id: *id,
434                    path: path.clone(),
435                    matched_indices,
436                    score: 0,
437                });
438            }
439        }
440        Ok(search_results)
441    }
442
443    fn score_paths(&self, candidates: &mut [SearchResult]) {
444        // tunable bonuses for path search
445        let smaller_paths = 10;
446        let suggested = 10;
447        let filename = 30;
448        let editable = 3;
449
450        candidates.sort_by_key(|a| a.path().len());
451
452        // the 10 smallest paths start with a mild advantage
453        for i in 0..smaller_paths {
454            if let Some(SearchResult::PathMatch { id: _, path: _, matched_indices: _, score }) =
455                candidates.get_mut(i)
456            {
457                *score = (smaller_paths - i) as i64;
458            }
459        }
460
461        // items in suggested docs have their score boosted
462        for cand in candidates.iter_mut() {
463            if self.suggested_docs.contains(&cand.id()) {
464                if let SearchResult::PathMatch { id: _, path: _, matched_indices: _, score } = cand
465                {
466                    *score += suggested;
467                }
468            }
469        }
470
471        // to what extent is the match in the name of the file
472        for cand in candidates.iter_mut() {
473            if let SearchResult::PathMatch { id: _, path, matched_indices, score } = cand {
474                let mut name_match = 0;
475                let mut name_size = 0;
476
477                for (i, c) in path.char_indices().rev() {
478                    if c == '/' {
479                        break;
480                    }
481                    name_size += 1;
482                    if matched_indices.contains(&i) {
483                        name_match += 1;
484                    }
485                }
486
487                let match_portion = name_match as f32 / name_size.max(1) as f32;
488                *score += (match_portion * filename as f32) as i64;
489            }
490        }
491
492        // if this document is editable in platform
493        for cand in candidates.iter_mut() {
494            if let SearchResult::PathMatch { id: _, path, matched_indices: _, score } = cand {
495                if path.ends_with(".md") || path.ends_with(".svg") {
496                    *score += editable;
497                }
498            }
499        }
500    }
501}