//! Every note's metadata and searchable plain text, kept in memory. Sidebar counts, //! title lookups and search read it instead of scanning the notes table, which costs //! about 1 µs a row (a second at a million notes). //! //! Writers never touch it: they record a [`Change`] after committing, and the next //! reader applies the pending changes by re-reading those notes. use std::collections::HashMap; use hashbrown::HashTable; use rustc_hash::FxHashSet; use std::sync::{Arc, RwLock}; use super::{NoteMeta, plain_text, preview}; use crate::matcher; /// Bytes of plain text kept in memory per note: a billion lines over a thousand notes /// would not fit, and a megabyte each still held a gigabyte there. Words are indexed /// from the whole text whatever its length; longer notes are matched from the store. pub(super) const PLAIN_KEPT: usize = 64 << 10; pub(super) struct Entry { /// The id, title, notebook id and searchable plain text, one after another in one /// allocation: a million notes' separate strings cost more in headers than in text. /// The plain text is its first [`PLAIN_KEPT`] bytes for a longer one. text: Box, /// Where the title, the notebook id and the plain text start in `text`. at: [u32; 3], in_notebook: bool, /// Whether the plain text is only the start of the text. Words are indexed from all of it. pub plain_cut: bool, pub created_at: i64, pub updated_at: i64, pub trashed_at: Option, /// Where in the plain text the preview is: the start of the text after the title, /// shown in lists. A copy of its own would cost as much as all the short notes' text. preview: (u32, u32), /// The distinct words of the title, then of the text, as [`Vocab`] ids. words: Box<[u32]>, title_words: u32, } impl Entry { fn new(meta: NoteMeta, plain: &str, plain_cut: bool, preview: &str, title: &[u32], text: &[u32]) -> Self { // Any occurrence of the preview is the same text. let preview = match plain.find(preview) { Some(at) => (at as u32, (at + preview.len()) as u32), None => { let end = plain.char_indices().nth(super::PREVIEW_CHARS).map_or(plain.len(), |(i, _)| i); (0, end as u32) } }; let words = title.iter().chain(text).copied().collect(); let mut entry = Self::packed(&meta, plain); entry.plain_cut = plain_cut; entry.preview = preview; entry.words = words; entry.title_words = title.len() as u32; entry } /// The entry's strings and times from `meta`, with `plain` as its text and no words. fn packed(meta: &NoteMeta, plain: &str) -> Self { let notebook = meta.notebook_id.as_deref().unwrap_or(""); let mut text = String::with_capacity(meta.id.len() + meta.title.len() + notebook.len() + plain.len()); let mut at = [0; 3]; for (i, part) in [&meta.id, &meta.title, notebook, plain].into_iter().enumerate() { if i > 0 { at[i - 1] = text.len() as u32; } text.push_str(part); } Self { text: text.into_boxed_str(), at, in_notebook: meta.notebook_id.is_some(), plain_cut: false, created_at: meta.created_at, updated_at: meta.updated_at, trashed_at: meta.trashed_at, preview: (0, 0), words: Box::new([]), title_words: 0, } } pub fn id(&self) -> &str { &self.text[..self.at[0] as usize] } pub fn title(&self) -> &str { &self.text[self.at[0] as usize..self.at[1] as usize] } pub fn notebook_id(&self) -> Option<&str> { self.in_notebook.then(|| &self.text[self.at[1] as usize..self.at[2] as usize]) } pub fn plain(&self) -> &str { &self.text[self.at[2] as usize..] } pub fn meta(&self) -> NoteMeta { NoteMeta { id: self.id().to_owned(), title: self.title().to_owned(), created_at: self.created_at, updated_at: self.updated_at, notebook_id: self.notebook_id().map(str::to_owned), trashed_at: self.trashed_at, } } pub fn preview(&self) -> &str { &self.plain()[self.preview.0 as usize..self.preview.1 as usize] } pub fn title_words(&self) -> &[u32] { &self.words[..self.title_words as usize] } pub fn text_words(&self) -> &[u32] { &self.words[self.title_words as usize..] } fn with_meta(&self, meta: &NoteMeta) -> Self { Self { plain_cut: self.plain_cut, preview: self.preview, words: self.words.clone(), title_words: self.title_words, ..Self::packed(meta, self.plain()) } } } /// Every distinct folded word any note has had. Search matches each word once rather /// than every occurrence in every note: a million notes share far fewer words. Words /// are only added, so ids taken from entries stay valid. #[derive(Default)] pub(super) struct Vocab { /// Ids of the words, hashed by the word: the words are not stored twice. ids: HashTable, /// Every word's characters one after another, and where each word ends: millions /// of words in allocations of their own would cost more than their characters. chars: Vec, ends: Vec, /// Recent search terms' costs in every word, newest last: typing a query repeats /// its earlier terms, and a palette keystroke searches texts and titles alike. /// A table shorter than the vocabulary lacks only the words added since. pub costs: std::sync::Mutex, matcher::Options, Arc>)>>, } /// A committed write the directory has not seen yet. pub(super) enum Change { /// The note was created, edited, moved, trashed, restored or deleted. Note(String), /// The notebook was deleted, and its notes became unfiled. NotebookGone(String), } #[derive(Default)] pub(super) struct Counts { /// Notes outside the trash. pub live: usize, /// Notes outside the trash in no notebook. pub unfiled: usize, pub trashed: usize, /// Notes outside the trash per notebook id. Notebooks without notes are absent. pub notebooks: HashMap, } impl Counts { fn add(&mut self, e: &Entry, n: isize) { let bump = |c: &mut usize| *c = c.saturating_add_signed(n); if e.trashed_at.is_some() { bump(&mut self.trashed); return; } bump(&mut self.live); match e.notebook_id() { None => bump(&mut self.unfiled), Some(nb) => { if !self.notebooks.contains_key(nb) { self.notebooks.insert(nb.to_owned(), 0); } let c = self.notebooks.get_mut(nb).unwrap(); bump(c); if *c == 0 { self.notebooks.remove(nb); } } } } } impl Vocab { pub fn len(&self) -> usize { self.ends.len() } pub fn word(&self, id: usize) -> &[char] { word_in(&self.chars, &self.ends, id) } fn id(&self, word: &[char]) -> Option { self.ids.find(hash(word), |&id| self.word(id as usize) == word).copied() } fn add(&mut self, word: &[char]) { if self.id(word).is_none() { let id = self.ends.len() as u32; self.chars.extend_from_slice(word); self.ends.push(self.chars.len()); let (chars, ends) = (&self.chars, &self.ends); self.ids.insert_unique(hash(word), id, |&id| hash(word_in(chars, ends, id as usize))); } } /// Drops the spare capacity growth left, once the words are all read. fn shrink(&mut self) { self.chars.shrink_to_fit(); self.ends.shrink_to_fit(); let (chars, ends) = (&self.chars, &self.ends); self.ids.shrink_to_fit(|&id| hash(word_in(chars, ends, id as usize))); } } /// Word `id` of a vocabulary's characters and word ends. fn word_in<'a>(chars: &'a [char], ends: &[usize], id: usize) -> &'a [char] { &chars[if id == 0 { 0 } else { ends[id - 1] }..ends[id]] } fn hash(t: &T) -> u64 { use std::hash::BuildHasher; rustc_hash::FxBuildHasher.hash_one(t) } /// Notes' rows with their plain text and words, read without the directory. pub(super) struct Prepared(Vec); /// [`prepare`] of one note, on the calling thread only. pub(super) fn prepare_one(meta: NoteMeta, body: String) -> Prepared { let mut prepared = prepare_with(vec![(meta, body)], |rows, f| rows.into_iter().map(f).collect()); prepared.0.shrink_to_fit(); prepared } /// Reads notes' plain text and words, on every core. This is the costly part of /// indexing a note, and needs no access to the directory. pub(super) fn prepare(rows: Vec<(NoteMeta, String)>) -> Prepared { prepare_with(rows, |rows, f| par_map(rows, f)) } type Row = (NoteMeta, String); type Ready = (NoteMeta, String, bool, String, Vec>, Vec>); fn prepare_with(rows: Vec, map: impl FnOnce(Vec, &(dyn Fn(Row) -> Ready + Sync)) -> Vec) -> Prepared { let words = |text: &str| { // Folded once per distinct word: a long note repeats its words millions of times. let distinct: FxHashSet<&str> = matcher::words(text).collect(); let mut words: Vec> = distinct.into_iter().map(matcher::fold_word).collect(); words.sort_unstable(); words.dedup(); words }; Prepared(map(rows, &|(meta, body)| { let mut plain = plain_text(&body); let (title, text) = (words(&meta.title), words(&plain)); let plain_cut = plain.len() > PLAIN_KEPT; if plain_cut { let mut end = PLAIN_KEPT; while !plain.is_char_boundary(end) { end -= 1; } plain.truncate(end); } (meta, plain, plain_cut, preview(&body), title, text) })) } #[derive(Default)] pub(super) struct Directory { /// Slot of each note in `slots`, hashed by the note's id. index: HashTable, /// The notes in a flat list, so a search can split it between threads and read it /// in place. A removed note leaves its slot empty until a new note takes it. slots: Vec>>, free: Vec, pub counts: Counts, pub vocab: Arc>, } impl Directory { /// Inserts or replaces notes from their rows and markdown bodies. The text is read /// on every core: at startup this indexes every note. pub fn put_many(&mut self, rows: Vec<(NoteMeta, String)>) { self.put_prepared(prepare(rows)); } /// Updates a note's metadata and keeps its words, for a note whose text is indexed /// later; a note new to the directory has no words until then. pub fn set_meta(&mut self, meta: NoteMeta) { let entry = match self.remove(&meta.id) { Some(old) => old.with_meta(&meta), None => Entry::new(meta, "", false, "", &[], &[]), }; self.insert(entry); } pub fn updated_at(&self, id: &str) -> Option { self.get(id).map(|e| e.updated_at) } /// Inserts or replaces notes from [`prepare`]d rows. pub fn put_prepared(&mut self, Prepared(prepared): Prepared) { // Words new to the vocabulary are found under the read lock, then added once. let unknown: Vec> = { let vocab = self.vocab.read().unwrap(); par_chunks(&prepared, |chunk| { chunk .iter() .flat_map(|(_, _, _, _, title, text)| title.iter().chain(text)) .filter(|w| vocab.id(w).is_none()) .map(|w| &**w) .collect() }) }; let mut vocab = self.vocab.write().unwrap(); for word in unknown.into_iter().flatten() { vocab.add(word); } drop(vocab); let vocab = self.vocab.read().unwrap(); let ids_of = |words: Vec>| -> Vec { let mut ids: Vec = words.iter().map(|w| vocab.id(w).unwrap()).collect(); ids.sort_unstable(); ids }; let entries = par_map(prepared, |(meta, plain, plain_cut, preview, title, text)| { Entry::new(meta, &plain, plain_cut, &preview, &ids_of(title), &ids_of(text)) }); drop(vocab); for entry in entries { self.remove(entry.id()); self.insert(entry); } } fn insert(&mut self, entry: Entry) { self.counts.add(&entry, 1); let h = hash(entry.id()); let entry = Some(Arc::new(entry)); let slot = match self.free.pop() { Some(slot) => { self.slots[slot] = entry; slot } None => { self.slots.push(entry); self.slots.len() - 1 } }; let slots = &self.slots; self.index.insert_unique(h, slot as u32, |&s| hash(slots[s as usize].as_ref().unwrap().id())); } /// Drops the spare capacity growth left, once every note is read. pub fn shrink(&mut self) { self.slots.shrink_to_fit(); self.vocab.write().unwrap().shrink(); } fn slot(&self, id: &str) -> Option { let slots = &self.slots; self.index.find(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).map(|&s| s as usize) } pub fn remove(&mut self, id: &str) -> Option> { let slots = &self.slots; let slot = self.index.find_entry(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).ok()?.remove().0 as usize; let old = self.slots[slot].take()?; self.free.push(slot); self.counts.add(&old, -1); Some(old) } pub fn get(&self, id: &str) -> Option<&Arc> { self.slots[self.slot(id)?].as_ref() } /// Every note, trashed ones too, with empty slots between them. pub fn slots(&self) -> &[Option>] { &self.slots } pub fn entries(&self) -> impl Iterator> { self.slots.iter().flatten() } pub fn unfile(&mut self, notebook_id: &str) { let ids: Vec = self .entries() .filter(|e| e.notebook_id() == Some(notebook_id)) .map(|e| e.id().to_owned()) .collect(); for id in ids { let old = self.remove(&id).unwrap(); let mut meta = old.meta(); meta.notebook_id = None; self.insert(old.with_meta(&meta)); } } /// Notes outside the trash. pub fn live(&self) -> Vec> { self.entries().filter(|e| e.trashed_at.is_none()).cloned().collect() } } /// `f` of every item on scoped threads, in order. Threads take the next item when /// done, so a few huge notes do not hold back the rest. fn par_map(items: Vec, f: impl Fn(T) -> U + Sync) -> Vec { let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len().max(1)); let n = items.len(); let items: Vec>> = items.into_iter().map(|t| std::sync::Mutex::new(Some(t))).collect(); let next = std::sync::atomic::AtomicUsize::new(0); let (items, next, f) = (&items, &next, &f); let mut done: Vec<(usize, U)> = std::thread::scope(|scope| { let handles: Vec<_> = (0..threads) .map(|_| { scope.spawn(move || { let mut out = Vec::new(); loop { // Items are taken a few at a time: most are small. let start = next.fetch_add(64, std::sync::atomic::Ordering::Relaxed); if start >= n { return out; } for (i, item) in items.iter().enumerate().skip(start).take(64) { out.push((i, f(item.lock().unwrap().take().unwrap()))); } } }) }) .collect(); handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() }); done.sort_unstable_by_key(|(i, _)| *i); done.into_iter().map(|(_, u)| u).collect() } /// `f` of each of about one slice of `items` per core, in order. fn par_chunks<'a, T: Sync, U: Send>(items: &'a [T], f: impl Fn(&'a [T]) -> U + Sync) -> Vec { let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); let f = &f; std::thread::scope(|scope| { let handles: Vec<_> = items.chunks(items.len().div_ceil(threads).max(1)).map(|chunk| scope.spawn(move || f(chunk))).collect(); handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() }) }