forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

directory.rs461 lines, 16.8 KiBHistoryRawDownload
1//! Every note's metadata and searchable plain text, kept in memory. Sidebar counts,
2//! title lookups and search read it instead of scanning the notes table, which costs
3//! about 1 µs a row (a second at a million notes).
4//!
5//! Writers never touch it: they record a [`Change`] after committing, and the next
6//! reader applies the pending changes by re-reading those notes.
7
8use std::collections::HashMap;
9
10use hashbrown::HashTable;
11use rustc_hash::FxHashSet;
12use std::sync::{Arc, RwLock};
13
14use super::{NoteMeta, plain_text, preview};
15use crate::matcher;
16
17/// Bytes of plain text kept in memory per note: a billion lines over a thousand notes
18/// would not fit, and a megabyte each still held a gigabyte there. Words are indexed
19/// from the whole text whatever its length; longer notes are matched from the store.
20pub(super) const PLAIN_KEPT: usize = 64 << 10;
21
22pub(super) struct Entry {
23 /// The id, title, notebook id and searchable plain text, one after another in one
24 /// allocation: a million notes' separate strings cost more in headers than in text.
25 /// The plain text is its first [`PLAIN_KEPT`] bytes for a longer one.
26 text: Box<str>,
27 /// Where the title, the notebook id and the plain text start in `text`.
28 at: [u32; 3],
29 in_notebook: bool,
30 /// Whether the plain text is only the start of the text. Words are indexed from all of it.
31 pub plain_cut: bool,
32 pub created_at: i64,
33 pub updated_at: i64,
34 pub trashed_at: Option<i64>,
35 /// Where in the plain text the preview is: the start of the text after the title,
36 /// shown in lists. A copy of its own would cost as much as all the short notes' text.
37 preview: (u32, u32),
38 /// The distinct words of the title, then of the text, as [`Vocab`] ids.
39 words: Box<[u32]>,
40 title_words: u32,
41}
42
43impl Entry {
44 fn new(meta: NoteMeta, plain: &str, plain_cut: bool, preview: &str, title: &[u32], text: &[u32]) -> Self {
45 // Any occurrence of the preview is the same text.
46 let preview = match plain.find(preview) {
47 Some(at) => (at as u32, (at + preview.len()) as u32),
48 None => {
49 let end = plain.char_indices().nth(super::PREVIEW_CHARS).map_or(plain.len(), |(i, _)| i);
50 (0, end as u32)
51 }
52 };
53 let words = title.iter().chain(text).copied().collect();
54 let mut entry = Self::packed(&meta, plain);
55 entry.plain_cut = plain_cut;
56 entry.preview = preview;
57 entry.words = words;
58 entry.title_words = title.len() as u32;
59 entry
60 }
61
62 /// The entry's strings and times from `meta`, with `plain` as its text and no words.
63 fn packed(meta: &NoteMeta, plain: &str) -> Self {
64 let notebook = meta.notebook_id.as_deref().unwrap_or("");
65 let mut text = String::with_capacity(meta.id.len() + meta.title.len() + notebook.len() + plain.len());
66 let mut at = [0; 3];
67 for (i, part) in [&meta.id, &meta.title, notebook, plain].into_iter().enumerate() {
68 if i > 0 {
69 at[i - 1] = text.len() as u32;
70 }
71 text.push_str(part);
72 }
73 Self {
74 text: text.into_boxed_str(),
75 at,
76 in_notebook: meta.notebook_id.is_some(),
77 plain_cut: false,
78 created_at: meta.created_at,
79 updated_at: meta.updated_at,
80 trashed_at: meta.trashed_at,
81 preview: (0, 0),
82 words: Box::new([]),
83 title_words: 0,
84 }
85 }
86
87 pub fn id(&self) -> &str {
88 &self.text[..self.at[0] as usize]
89 }
90
91 pub fn title(&self) -> &str {
92 &self.text[self.at[0] as usize..self.at[1] as usize]
93 }
94
95 pub fn notebook_id(&self) -> Option<&str> {
96 self.in_notebook.then(|| &self.text[self.at[1] as usize..self.at[2] as usize])
97 }
98
99 pub fn plain(&self) -> &str {
100 &self.text[self.at[2] as usize..]
101 }
102
103 pub fn meta(&self) -> NoteMeta {
104 NoteMeta {
105 id: self.id().to_owned(),
106 title: self.title().to_owned(),
107 created_at: self.created_at,
108 updated_at: self.updated_at,
109 notebook_id: self.notebook_id().map(str::to_owned),
110 trashed_at: self.trashed_at,
111 }
112 }
113
114 pub fn preview(&self) -> &str {
115 &self.plain()[self.preview.0 as usize..self.preview.1 as usize]
116 }
117
118 pub fn title_words(&self) -> &[u32] {
119 &self.words[..self.title_words as usize]
120 }
121
122 pub fn text_words(&self) -> &[u32] {
123 &self.words[self.title_words as usize..]
124 }
125
126 fn with_meta(&self, meta: &NoteMeta) -> Self {
127 Self {
128 plain_cut: self.plain_cut,
129 preview: self.preview,
130 words: self.words.clone(),
131 title_words: self.title_words,
132 ..Self::packed(meta, self.plain())
133 }
134 }
135}
136
137/// Every distinct folded word any note has had. Search matches each word once rather
138/// than every occurrence in every note: a million notes share far fewer words. Words
139/// are only added, so ids taken from entries stay valid.
140#[derive(Default)]
141pub(super) struct Vocab {
142 /// Ids of the words, hashed by the word: the words are not stored twice.
143 ids: HashTable<u32>,
144 /// Every word's characters one after another, and where each word ends: millions
145 /// of words in allocations of their own would cost more than their characters.
146 chars: Vec<char>,
147 ends: Vec<usize>,
148 /// Recent search terms' costs in every word, newest last: typing a query repeats
149 /// its earlier terms, and a palette keystroke searches texts and titles alike.
150 /// A table shorter than the vocabulary lacks only the words added since.
151 pub costs: std::sync::Mutex<Vec<(Box<[char]>, matcher::Options, Arc<Vec<u8>>)>>,
152}
153
154/// A committed write the directory has not seen yet.
155pub(super) enum Change {
156 /// The note was created, edited, moved, trashed, restored or deleted.
157 Note(String),
158 /// The notebook was deleted, and its notes became unfiled.
159 NotebookGone(String),
160}
161
162#[derive(Default)]
163pub(super) struct Counts {
164 /// Notes outside the trash.
165 pub live: usize,
166 /// Notes outside the trash in no notebook.
167 pub unfiled: usize,
168 pub trashed: usize,
169 /// Notes outside the trash per notebook id. Notebooks without notes are absent.
170 pub notebooks: HashMap<String, usize>,
171}
172
173impl Counts {
174 fn add(&mut self, e: &Entry, n: isize) {
175 let bump = |c: &mut usize| *c = c.saturating_add_signed(n);
176 if e.trashed_at.is_some() {
177 bump(&mut self.trashed);
178 return;
179 }
180 bump(&mut self.live);
181 match e.notebook_id() {
182 None => bump(&mut self.unfiled),
183 Some(nb) => {
184 if !self.notebooks.contains_key(nb) {
185 self.notebooks.insert(nb.to_owned(), 0);
186 }
187 let c = self.notebooks.get_mut(nb).unwrap();
188 bump(c);
189 if *c == 0 {
190 self.notebooks.remove(nb);
191 }
192 }
193 }
194 }
195}
196
197impl Vocab {
198 pub fn len(&self) -> usize {
199 self.ends.len()
200 }
201
202 pub fn word(&self, id: usize) -> &[char] {
203 word_in(&self.chars, &self.ends, id)
204 }
205
206 fn id(&self, word: &[char]) -> Option<u32> {
207 self.ids.find(hash(word), |&id| self.word(id as usize) == word).copied()
208 }
209
210 fn add(&mut self, word: &[char]) {
211 if self.id(word).is_none() {
212 let id = self.ends.len() as u32;
213 self.chars.extend_from_slice(word);
214 self.ends.push(self.chars.len());
215 let (chars, ends) = (&self.chars, &self.ends);
216 self.ids.insert_unique(hash(word), id, |&id| hash(word_in(chars, ends, id as usize)));
217 }
218 }
219
220 /// Drops the spare capacity growth left, once the words are all read.
221 fn shrink(&mut self) {
222 self.chars.shrink_to_fit();
223 self.ends.shrink_to_fit();
224 let (chars, ends) = (&self.chars, &self.ends);
225 self.ids.shrink_to_fit(|&id| hash(word_in(chars, ends, id as usize)));
226 }
227}
228
229/// Word `id` of a vocabulary's characters and word ends.
230fn word_in<'a>(chars: &'a [char], ends: &[usize], id: usize) -> &'a [char] {
231 &chars[if id == 0 { 0 } else { ends[id - 1] }..ends[id]]
232}
233
234fn hash<T: std::hash::Hash + ?Sized>(t: &T) -> u64 {
235 use std::hash::BuildHasher;
236 rustc_hash::FxBuildHasher.hash_one(t)
237}
238
239/// Notes' rows with their plain text and words, read without the directory.
240pub(super) struct Prepared(Vec<Ready>);
241
242/// [`prepare`] of one note, on the calling thread only.
243pub(super) fn prepare_one(meta: NoteMeta, body: String) -> Prepared {
244 let mut prepared = prepare_with(vec![(meta, body)], |rows, f| rows.into_iter().map(f).collect());
245 prepared.0.shrink_to_fit();
246 prepared
247}
248
249/// Reads notes' plain text and words, on every core. This is the costly part of
250/// indexing a note, and needs no access to the directory.
251pub(super) fn prepare(rows: Vec<(NoteMeta, String)>) -> Prepared {
252 prepare_with(rows, |rows, f| par_map(rows, f))
253}
254
255type Row = (NoteMeta, String);
256type Ready = (NoteMeta, String, bool, String, Vec<Box<[char]>>, Vec<Box<[char]>>);
257
258fn prepare_with(rows: Vec<Row>, map: impl FnOnce(Vec<Row>, &(dyn Fn(Row) -> Ready + Sync)) -> Vec<Ready>) -> Prepared {
259 let words = |text: &str| {
260 // Folded once per distinct word: a long note repeats its words millions of times.
261 let distinct: FxHashSet<&str> = matcher::words(text).collect();
262 let mut words: Vec<Box<[char]>> = distinct.into_iter().map(matcher::fold_word).collect();
263 words.sort_unstable();
264 words.dedup();
265 words
266 };
267 Prepared(map(rows, &|(meta, body)| {
268 let mut plain = plain_text(&body);
269 let (title, text) = (words(&meta.title), words(&plain));
270 let plain_cut = plain.len() > PLAIN_KEPT;
271 if plain_cut {
272 let mut end = PLAIN_KEPT;
273 while !plain.is_char_boundary(end) {
274 end -= 1;
275 }
276 plain.truncate(end);
277 }
278 (meta, plain, plain_cut, preview(&body), title, text)
279 }))
280}
281
282#[derive(Default)]
283pub(super) struct Directory {
284 /// Slot of each note in `slots`, hashed by the note's id.
285 index: HashTable<u32>,
286 /// The notes in a flat list, so a search can split it between threads and read it
287 /// in place. A removed note leaves its slot empty until a new note takes it.
288 slots: Vec<Option<Arc<Entry>>>,
289 free: Vec<usize>,
290 pub counts: Counts,
291 pub vocab: Arc<RwLock<Vocab>>,
292}
293
294impl Directory {
295 /// Inserts or replaces notes from their rows and markdown bodies. The text is read
296 /// on every core: at startup this indexes every note.
297 pub fn put_many(&mut self, rows: Vec<(NoteMeta, String)>) {
298 self.put_prepared(prepare(rows));
299 }
300
301 /// Updates a note's metadata and keeps its words, for a note whose text is indexed
302 /// later; a note new to the directory has no words until then.
303 pub fn set_meta(&mut self, meta: NoteMeta) {
304 let entry = match self.remove(&meta.id) {
305 Some(old) => old.with_meta(&meta),
306 None => Entry::new(meta, "", false, "", &[], &[]),
307 };
308 self.insert(entry);
309 }
310
311 pub fn updated_at(&self, id: &str) -> Option<i64> {
312 self.get(id).map(|e| e.updated_at)
313 }
314
315 /// Inserts or replaces notes from [`prepare`]d rows.
316 pub fn put_prepared(&mut self, Prepared(prepared): Prepared) {
317 // Words new to the vocabulary are found under the read lock, then added once.
318 let unknown: Vec<FxHashSet<&[char]>> = {
319 let vocab = self.vocab.read().unwrap();
320 par_chunks(&prepared, |chunk| {
321 chunk
322 .iter()
323 .flat_map(|(_, _, _, _, title, text)| title.iter().chain(text))
324 .filter(|w| vocab.id(w).is_none())
325 .map(|w| &**w)
326 .collect()
327 })
328 };
329 let mut vocab = self.vocab.write().unwrap();
330 for word in unknown.into_iter().flatten() {
331 vocab.add(word);
332 }
333 drop(vocab);
334 let vocab = self.vocab.read().unwrap();
335 let ids_of = |words: Vec<Box<[char]>>| -> Vec<u32> {
336 let mut ids: Vec<u32> = words.iter().map(|w| vocab.id(w).unwrap()).collect();
337 ids.sort_unstable();
338 ids
339 };
340 let entries = par_map(prepared, |(meta, plain, plain_cut, preview, title, text)| {
341 Entry::new(meta, &plain, plain_cut, &preview, &ids_of(title), &ids_of(text))
342 });
343 drop(vocab);
344 for entry in entries {
345 self.remove(entry.id());
346 self.insert(entry);
347 }
348 }
349
350 fn insert(&mut self, entry: Entry) {
351 self.counts.add(&entry, 1);
352 let h = hash(entry.id());
353 let entry = Some(Arc::new(entry));
354 let slot = match self.free.pop() {
355 Some(slot) => {
356 self.slots[slot] = entry;
357 slot
358 }
359 None => {
360 self.slots.push(entry);
361 self.slots.len() - 1
362 }
363 };
364 let slots = &self.slots;
365 self.index.insert_unique(h, slot as u32, |&s| hash(slots[s as usize].as_ref().unwrap().id()));
366 }
367
368 /// Drops the spare capacity growth left, once every note is read.
369 pub fn shrink(&mut self) {
370 self.slots.shrink_to_fit();
371 self.vocab.write().unwrap().shrink();
372 }
373
374 fn slot(&self, id: &str) -> Option<usize> {
375 let slots = &self.slots;
376 self.index.find(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).map(|&s| s as usize)
377 }
378
379 pub fn remove(&mut self, id: &str) -> Option<Arc<Entry>> {
380 let slots = &self.slots;
381 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;
382 let old = self.slots[slot].take()?;
383 self.free.push(slot);
384 self.counts.add(&old, -1);
385 Some(old)
386 }
387
388 pub fn get(&self, id: &str) -> Option<&Arc<Entry>> {
389 self.slots[self.slot(id)?].as_ref()
390 }
391
392 /// Every note, trashed ones too, with empty slots between them.
393 pub fn slots(&self) -> &[Option<Arc<Entry>>] {
394 &self.slots
395 }
396
397 pub fn entries(&self) -> impl Iterator<Item = &Arc<Entry>> {
398 self.slots.iter().flatten()
399 }
400
401 pub fn unfile(&mut self, notebook_id: &str) {
402 let ids: Vec<String> = self
403 .entries()
404 .filter(|e| e.notebook_id() == Some(notebook_id))
405 .map(|e| e.id().to_owned())
406 .collect();
407 for id in ids {
408 let old = self.remove(&id).unwrap();
409 let mut meta = old.meta();
410 meta.notebook_id = None;
411 self.insert(old.with_meta(&meta));
412 }
413 }
414
415 /// Notes outside the trash.
416 pub fn live(&self) -> Vec<Arc<Entry>> {
417 self.entries().filter(|e| e.trashed_at.is_none()).cloned().collect()
418 }
419}
420
421/// `f` of every item on scoped threads, in order. Threads take the next item when
422/// done, so a few huge notes do not hold back the rest.
423fn par_map<T: Send, U: Send>(items: Vec<T>, f: impl Fn(T) -> U + Sync) -> Vec<U> {
424 let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len().max(1));
425 let n = items.len();
426 let items: Vec<std::sync::Mutex<Option<T>>> = items.into_iter().map(|t| std::sync::Mutex::new(Some(t))).collect();
427 let next = std::sync::atomic::AtomicUsize::new(0);
428 let (items, next, f) = (&items, &next, &f);
429 let mut done: Vec<(usize, U)> = std::thread::scope(|scope| {
430 let handles: Vec<_> = (0..threads)
431 .map(|_| {
432 scope.spawn(move || {
433 let mut out = Vec::new();
434 loop {
435 // Items are taken a few at a time: most are small.
436 let start = next.fetch_add(64, std::sync::atomic::Ordering::Relaxed);
437 if start >= n {
438 return out;
439 }
440 for (i, item) in items.iter().enumerate().skip(start).take(64) {
441 out.push((i, f(item.lock().unwrap().take().unwrap())));
442 }
443 }
444 })
445 })
446 .collect();
447 handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
448 });
449 done.sort_unstable_by_key(|(i, _)| *i);
450 done.into_iter().map(|(_, u)| u).collect()
451}
452
453/// `f` of each of about one slice of `items` per core, in order.
454fn par_chunks<'a, T: Sync, U: Send>(items: &'a [T], f: impl Fn(&'a [T]) -> U + Sync) -> Vec<U> {
455 let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
456 let f = &f;
457 std::thread::scope(|scope| {
458 let handles: Vec<_> = items.chunks(items.len().div_ceil(threads).max(1)).map(|chunk| scope.spawn(move || f(chunk))).collect();
459 handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
460 })
461}