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, input), 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 Ok(doc) = String::from_utf8(self.read_document(file.id, false).await.unwrap())
238            else {
239                continue;
240            };
241
242            if doc.len() > CONTENT_MAX_LEN_BYTES {
243                continue;
244            };
245
246            index_writer
247                .add_document(doc!(
248                    id_field => id_bytes,
249                    id_str => id_string,
250                    content => doc,
251                ))
252                .unwrap();
253        }
254
255        index_writer.commit().unwrap();
256    }
257}
258
259impl Default for SearchIndex {
260    fn default() -> Self {
261        let mut schema_builder = Schema::builder();
262        schema_builder.add_bytes_field("id", STORED);
263        schema_builder.add_text_field("id_str", TEXT | STORED);
264        schema_builder.add_text_field("content", TEXT | STORED);
265
266        let schema = schema_builder.build();
267
268        let index = Index::create_in_ram(schema.clone());
269
270        // doing this here would be a bad idea if not for in-ram empty index
271        let reader = index
272            .reader_builder()
273            .reload_policy(ReloadPolicy::OnCommitWithDelay)
274            .try_into()
275            .unwrap();
276
277        Self {
278            ready: Default::default(),
279            tantivy_index: index,
280            tantivy_reader: reader,
281            metadata_index: Default::default(),
282        }
283    }
284}
285
286#[derive(Debug, Serialize)]
287pub struct ContentMatch {
288    pub paragraph: String,
289    pub matched_indices: Vec<usize>,
290    pub score: i64,
291}
292
293impl SearchResult {
294    pub fn id(&self) -> Uuid {
295        match self {
296            SearchResult::DocumentMatch { id, .. } | SearchResult::PathMatch { id, .. } => *id,
297        }
298    }
299
300    pub fn path(&self) -> &str {
301        match self {
302            SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => path,
303        }
304    }
305
306    pub fn name(&self) -> &str {
307        match self {
308            SearchResult::DocumentMatch { path, .. } | SearchResult::PathMatch { path, .. } => {
309                path.split('/').next_back().unwrap_or_default()
310            }
311        }
312    }
313
314    pub fn score(&self) -> i64 {
315        match self {
316            SearchResult::DocumentMatch { content_matches, .. } => content_matches
317                .iter()
318                .map(|m| m.score)
319                .max()
320                .unwrap_or_default(),
321            SearchResult::PathMatch { score, .. } => *score,
322        }
323    }
324}
325
326#[derive(Default, Clone)]
327pub struct SearchMetadata {
328    files: Vec<File>,
329    paths: Vec<(Uuid, String)>,
330    suggested_docs: Vec<Uuid>,
331}
332
333impl SearchMetadata {
334    async fn populate(lb: &Lb) -> LbResult<Self> {
335        let files = lb.list_metadatas().await?;
336        let paths = lb.list_paths_with_ids(None).await?;
337        let suggested_docs = lb.suggested_docs(RankingWeights::default()).await?;
338
339        Ok(SearchMetadata { files, paths, suggested_docs })
340    }
341
342    fn compute_deleted(&self, old: &SearchMetadata) -> Vec<Uuid> {
343        let mut deleted_ids = vec![];
344
345        for old_file in &old.files {
346            if !self.files.iter().any(|new_f| new_f.id == old_file.id) {
347                deleted_ids.push(old_file.id);
348            }
349        }
350
351        deleted_ids
352    }
353
354    fn empty_search(&self) -> LbResult<Vec<SearchResult>> {
355        let mut results = vec![];
356
357        for id in &self.suggested_docs {
358            let path = self
359                .paths
360                .iter()
361                .find(|(path_id, _)| id == path_id)
362                .map(|(_, path)| path.clone())
363                .unwrap_or_default();
364
365            results.push(SearchResult::PathMatch {
366                id: *id,
367                path,
368                matched_indices: vec![],
369                score: 0,
370            });
371        }
372
373        Ok(results)
374    }
375
376    fn path_search(&self, query: &str) -> LbResult<Vec<SearchResult>> {
377        let mut results = self.path_candidates(query)?;
378        self.score_paths(&mut results);
379
380        results.sort_by_key(|r| -r.score());
381
382        if let Some(result) = self.id_match(query) {
383            results.insert(0, result);
384        }
385
386        Ok(results)
387    }
388
389    fn id_match(&self, query: &str) -> Option<SearchResult> {
390        if query.len() < 8 {
391            return None;
392        }
393
394        let query = if query.starts_with("lb://") {
395            query.replacen("lb://", "", 1)
396        } else {
397            query.to_string()
398        };
399
400        for (id, path) in &self.paths {
401            if id.to_string().contains(&query) {
402                return Some(SearchResult::PathMatch {
403                    id: *id,
404                    path: path.clone(),
405                    matched_indices: vec![],
406                    score: 100,
407                });
408            }
409        }
410
411        None
412    }
413
414    fn path_candidates(&self, query: &str) -> LbResult<Vec<SearchResult>> {
415        let mut search_results = vec![];
416
417        for (id, path) in &self.paths {
418            let mut matched_indices = vec![];
419
420            let mut query_iter = query.chars().rev();
421            let mut current_query_char = query_iter.next();
422
423            for (path_ind, path_char) in path.char_indices().rev() {
424                if let Some(qc) = current_query_char {
425                    if qc.eq_ignore_ascii_case(&path_char) {
426                        matched_indices.push(path_ind);
427                        current_query_char = query_iter.next();
428                    }
429                } else {
430                    break;
431                }
432            }
433
434            if current_query_char.is_none() {
435                search_results.push(SearchResult::PathMatch {
436                    id: *id,
437                    path: path.clone(),
438                    matched_indices,
439                    score: 0,
440                });
441            }
442        }
443        Ok(search_results)
444    }
445
446    fn score_paths(&self, candidates: &mut [SearchResult]) {
447        // tunable bonuses for path search
448        let smaller_paths = 10;
449        let suggested = 10;
450        let filename = 30;
451        let editable = 3;
452
453        candidates.sort_by_key(|a| a.path().len());
454
455        // the 10 smallest paths start with a mild advantage
456        for i in 0..smaller_paths {
457            if let Some(SearchResult::PathMatch { id: _, path: _, matched_indices: _, score }) =
458                candidates.get_mut(i)
459            {
460                *score = (smaller_paths - i) as i64;
461            }
462        }
463
464        // items in suggested docs have their score boosted
465        for cand in candidates.iter_mut() {
466            if self.suggested_docs.contains(&cand.id()) {
467                if let SearchResult::PathMatch { id: _, path: _, matched_indices: _, score } = cand
468                {
469                    *score += suggested;
470                }
471            }
472        }
473
474        // to what extent is the match in the name of the file
475        for cand in candidates.iter_mut() {
476            if let SearchResult::PathMatch { id: _, path, matched_indices, score } = cand {
477                let mut name_match = 0;
478                let mut name_size = 0;
479
480                for (i, c) in path.char_indices().rev() {
481                    if c == '/' {
482                        break;
483                    }
484                    name_size += 1;
485                    if matched_indices.contains(&i) {
486                        name_match += 1;
487                    }
488                }
489
490                let match_portion = name_match as f32 / name_size.max(1) as f32;
491                *score += (match_portion * filename as f32) as i64;
492            }
493        }
494
495        // if this document is editable in platform
496        for cand in candidates.iter_mut() {
497            if let SearchResult::PathMatch { id: _, path, matched_indices: _, score } = cand {
498                if path.ends_with(".md") || path.ends_with(".svg") {
499                    *score += editable;
500                }
501            }
502        }
503    }
504}