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