1use std::collections::{HashMap, HashSet};
101use std::fs::File;
102use std::io::{BufWriter, Write};
103use std::path::{Path, PathBuf};
104use std::sync::atomic::{AtomicU64, Ordering};
105use std::sync::{Arc, Mutex, Weak};
106use std::thread::JoinHandle;
107use std::time::{SystemTime, UNIX_EPOCH};
108
109use serde_json::{json, Value};
110
111use super::index_file::{
112 self, Encoded, EncodedChunk, IndexKey, MainPart, CHUNK_INCOMING, CHUNK_WEIGHTS,
113};
114use crate::graph::GraphIndex;
115use crate::notices::{self, NoticeLevel, Notifier};
116use crate::options::ByteSize;
117
118pub const MANIFEST_FORMAT: &str = "ursa-indexes";
120pub const MANIFEST_VERSION: u64 = 2;
122const MANIFEST: &str = "manifest.json";
123const UNNAMED: &str = "a graph";
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Entry {
129 pub key: IndexKey,
130 pub file: String,
132 pub graph: String,
134 pub size: u64,
135 pub created: u64,
137 pub last_used: u64,
139}
140
141impl Entry {
142 fn to_json(&self) -> Value {
143 json!({
144 "file": self.file,
145 "graph": self.graph,
146 "size": self.size,
147 "created": self.created,
148 "last_used": self.last_used,
149 "key": self.key.to_json(),
150 })
151 }
152
153 fn from_json(value: &Value) -> Option<Self> {
154 let file = value.get("file")?.as_str()?.to_string();
155 if file.is_empty() || file.contains(['/', '\\']) || file.starts_with('.') {
157 return None;
158 }
159 Some(Self {
160 key: IndexKey::from_json(value.get("key")?)?,
161 file,
162 graph: value
163 .get("graph")
164 .and_then(Value::as_str)
165 .unwrap_or(UNNAMED)
166 .to_string(),
167 size: value.get("size")?.as_u64()?,
168 created: value.get("created")?.as_u64()?,
169 last_used: value.get("last_used")?.as_u64()?,
170 })
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
176pub enum Saved {
177 Stored { size: u64, grows_to: Option<u64> },
181 ReadOnly,
183 TooLarge { size: u64, limit: u64 },
185 OverLimit { stored: u64, limit: u64 },
189 NoRoom { size: u64, limit: u64 },
192 Unstorable(String),
194}
195
196impl Saved {
197 pub fn loses_work(&self) -> bool {
200 matches!(
201 self,
202 Saved::TooLarge { .. }
203 | Saved::OverLimit { .. }
204 | Saved::NoRoom { .. }
205 | Saved::Unstorable(_)
206 )
207 }
208
209 pub fn describe(&self, database: &str) -> String {
212 match self {
213 Saved::Stored {
214 size,
215 grows_to: None,
216 } => format!(
217 "stored in {database} ({}, with its reverse adjacency)",
218 notices::size(*size)
219 ),
220 Saved::Stored {
221 size,
222 grows_to: Some(grown),
223 } => format!(
224 "stored in {database} ({}; about {} once an algorithm adds the reverse \
225 adjacency)",
226 notices::size(*size),
227 notices::size(*grown)
228 ),
229 Saved::ReadOnly => format!("not stored: {database} is open read-only"),
230 Saved::TooLarge { size, limit } => format!(
231 "not stored: it takes {}, more than ursa.index_storage_limit ({}); SET \
232 ursa.index_storage_limit = '{}' to keep it",
233 notices::size(*size),
234 ByteSize(*limit),
235 ByteSize(suggested_limit(*size))
236 ),
237 Saved::OverLimit { stored, limit } => format!(
238 "not stored: the indexes {database} stores take {}, more than \
239 ursa.index_storage_limit ({}); they are kept, and new indexes are not stored \
240 until it is raised",
241 notices::size(*stored),
242 ByteSize(*limit)
243 ),
244 Saved::NoRoom { size, limit } => format!(
245 "not stored: the stored indexes running queries use leave less than its {} of \
246 ursa.index_storage_limit ({})",
247 notices::size(*size),
248 ByteSize(*limit)
249 ),
250 Saved::Unstorable(why) => format!("not stored: {why}"),
251 }
252 }
253}
254
255pub fn suggested_limit(size: u64) -> u64 {
259 size.saturating_mul(2)
260 .checked_next_power_of_two()
261 .unwrap_or(u64::MAX)
262 .max(1 << 20)
263}
264
265#[derive(Debug)]
267pub struct IndexStore {
268 dir: PathBuf,
269 writable: bool,
270 database: String,
272 limit: AtomicU64,
275 state: Mutex<State>,
276 pending: Mutex<Vec<JoinHandle<()>>>,
277 notifier: Mutex<Notifier>,
280}
281
282#[derive(Debug, Default)]
283struct State {
284 loaded: bool,
286 entries: Vec<Entry>,
287 reserved: u64,
289 live: HashMap<String, Live>,
293 damaged: HashSet<(String, MainPart)>,
298}
299
300#[derive(Debug)]
302struct Live {
303 index: Weak<GraphIndex>,
304 main: MainPart,
305 chunks: HashSet<(u32, Vec<u8>)>,
307 declined: HashSet<(u32, Vec<u8>)>,
309 graph: String,
310}
311
312impl IndexStore {
313 pub fn new(dir: PathBuf, writable: bool, database: String, limit: u64) -> Self {
317 Self {
318 dir,
319 writable,
320 database,
321 limit: AtomicU64::new(limit),
322 state: Mutex::new(State::default()),
323 pending: Mutex::new(Vec::new()),
324 notifier: Mutex::new(Notifier::silent()),
325 }
326 }
327
328 pub fn dir(&self) -> &Path {
329 &self.dir
330 }
331
332 pub fn is_writable(&self) -> bool {
333 self.writable
334 }
335
336 pub fn database(&self) -> &str {
338 &self.database
339 }
340
341 pub fn limit(&self) -> u64 {
343 self.limit.load(Ordering::Relaxed)
344 }
345
346 pub fn set_limit(&self, limit: u64) {
350 self.limit.store(limit, Ordering::Relaxed);
351 }
352
353 pub fn stored_bytes(&self) -> u64 {
356 if !self.writable {
357 return manifest_bytes(&self.dir);
358 }
359 let state = self.state();
360 if !state.loaded {
361 return manifest_bytes(&self.dir);
362 }
363 state.reserved + state.entries.iter().map(|e| e.size).sum::<u64>()
364 }
365
366 fn state(&self) -> std::sync::MutexGuard<'_, State> {
367 self.state.lock().unwrap_or_else(|e| e.into_inner())
368 }
369
370 fn notifier(&self) -> Notifier {
371 self.notifier
372 .lock()
373 .unwrap_or_else(|e| e.into_inner())
374 .clone()
375 }
376
377 fn use_notifier(&self, notifier: &Notifier) {
378 *self.notifier.lock().unwrap_or_else(|e| e.into_inner()) = notifier.clone();
379 }
380
381 pub fn entries(&self) -> Vec<Entry> {
383 if !self.writable {
384 return read_manifest(&self.dir);
385 }
386 let mut state = self.state();
387 self.ensure_loaded(&mut state);
388 state.entries.clone()
389 }
390
391 fn ensure_loaded(&self, state: &mut State) {
393 if state.loaded {
394 return;
395 }
396 state.loaded = true;
397 let manifest = read_manifest_checked(&self.dir);
398 let mut entries = manifest.entries;
399 let before = entries.len();
400 entries.retain(|e| self.dir.join(&e.file).is_file());
401 let mut files = HashSet::new();
403 let mut fingerprints = HashSet::new();
404 entries.retain(|e| {
405 files.insert(e.file.clone()) && fingerprints.insert(e.key.fingerprint.clone())
406 });
407 let changed = entries.len() != before || manifest.foreign.is_some();
408 let mut freed = 0;
411 if let Ok(listing) = std::fs::read_dir(&self.dir) {
412 for item in listing.flatten() {
413 let name = item.file_name().to_string_lossy().into_owned();
414 let ours = name.ends_with(".idx") || name.ends_with(".tmp");
415 if ours && !files.contains(&name) {
416 freed += item.metadata().map_or(0, |m| m.len());
417 let _ = std::fs::remove_file(item.path());
418 }
419 }
420 }
421 if let Some(n) = manifest.foreign.filter(|n| *n > 0) {
422 self.notifier().say(NoticeLevel::On, || {
423 format!(
424 "removed {n} stored {} ({}) from {} written by another version of ursa; \
425 each is built again when it is first used",
426 if n == 1 { "index" } else { "indexes" },
427 notices::size(freed),
428 self.database
429 )
430 });
431 }
432 state.entries = entries;
433 if changed {
434 let _ = write_manifest(&self.dir, &state.entries);
435 }
436 }
437
438 pub fn keys_counted(&self, key: &IndexKey) -> bool {
444 read_key_counts(&self.dir).contains(key)
445 }
446
447 pub fn record_keys_counted(&self, key: IndexKey) {
451 if !self.writable {
452 return;
453 }
454 let _state = self.state();
457 let mut counted = read_key_counts(&self.dir);
458 counted.retain(|k| k.fingerprint != key.fingerprint);
460 counted.push(key);
461 if counted.len() > KEY_COUNTS_KEPT {
462 counted.drain(..counted.len() - KEY_COUNTS_KEPT);
463 }
464 let _ = write_key_counts(&self.dir, &counted);
465 }
466
467 pub fn contains(&self, key: &IndexKey) -> bool {
470 self.entries().iter().any(|e| e.key == *key)
471 }
472
473 pub fn load(
477 self: &Arc<Self>,
478 key: &IndexKey,
479 notifier: &Notifier,
480 ) -> Option<(Arc<GraphIndex>, u64)> {
481 let entry = if self.writable {
482 self.use_notifier(notifier);
483 let mut state = self.state();
484 self.ensure_loaded(&mut state);
485 state.entries.iter().find(|e| e.key == *key)?.clone()
486 } else {
487 read_manifest(&self.dir)
488 .into_iter()
489 .find(|e| e.key == *key)?
490 };
491 let file = entry.file.clone();
492 let read = index_file::read_file(&self.dir.join(&file), key);
493 let mut state = self.state();
494 match read {
495 Ok(stored) if state.damaged.contains(&(file.clone(), stored.main)) => None,
496 Ok(stored) => {
497 let has_incoming = stored.chunks.iter().any(|c| c.kind == CHUNK_INCOMING);
498 let chunks = stored
499 .chunks
500 .iter()
501 .map(|c| (c.kind, c.name.clone()))
502 .collect();
503 let weights: Vec<index_file::ChunkInfo> = stored
504 .chunks
505 .into_iter()
506 .filter(|c| c.kind == CHUNK_WEIGHTS)
507 .collect();
508 let keys = weights
509 .iter()
510 .filter_map(|c| String::from_utf8(c.name.clone()).ok())
511 .collect();
512 let (path, main) = (self.dir.join(&file), stored.main);
513 let n_edges = stored.topology.n_edges();
514 if let Some(checks) = &stored.unverified {
515 let (store, file) = (Arc::downgrade(self), file.clone());
518 checks.on_damage(Box::new(move || {
519 if let Some(store) = store.upgrade() {
520 store.discard(&file, main);
521 }
522 }));
523 }
524 let read = Box::new(move |key: &str| {
525 let chunk = weights.iter().find(|c| c.name == key.as_bytes())?;
526 index_file::read_weights(&path, main, chunk, n_edges).ok()
527 });
528 let index = Arc::new(
529 GraphIndex::new(Arc::new(stored.topology), Arc::new(stored.ids))
530 .with_dropped(stored.dropped.n_dropped, stored.dropped.kept)
531 .with_stored_weights(keys, read)
532 .with_unverified(stored.unverified),
533 );
534 state.live.insert(
535 file.clone(),
536 Live {
537 index: Arc::downgrade(&index),
538 main: stored.main,
539 chunks,
540 declined: HashSet::new(),
541 graph: entry.graph.clone(),
542 },
543 );
544 if self.writable {
545 let now = tick(&state.entries);
546 if let Some(entry) = state.entries.iter_mut().find(|e| e.file == file) {
547 entry.last_used = now;
548 let _ = write_manifest(&self.dir, &state.entries);
549 }
550 }
551 drop(state);
552 if stored.version != index_file::VERSION && self.writable {
553 let version = stored.version;
554 self.upgrade(key, &index, &entry.graph, version, has_incoming, notifier);
555 }
556 Some((index, entry.size))
557 }
558 Err(_) => {
559 if self.writable {
560 let before = state.entries.len();
561 state.entries.retain(|e| e.file != file);
562 if state.entries.len() != before {
563 let _ = std::fs::remove_file(self.dir.join(&file));
564 let _ = write_manifest(&self.dir, &state.entries);
565 }
566 }
567 None
568 }
569 }
570 }
571
572 fn upgrade(
580 self: &Arc<Self>,
581 key: &IndexKey,
582 index: &Arc<GraphIndex>,
583 graph: &str,
584 version: u32,
585 has_incoming: bool,
586 notifier: &Notifier,
587 ) {
588 let until = match version {
590 index_file::VERSION_2 => "it is read whole",
591 _ => "each process that looks a node up by its id builds the ids' lookup table",
592 };
593 if has_incoming {
594 index.topology.incoming();
595 }
596 let saved = self.save(key.clone(), Arc::clone(index), graph, notifier);
597 notifier.say(NoticeLevel::On, || match saved {
598 Saved::Stored { size, .. } => format!(
599 "rewriting the stored index for {graph} in {} ({}) in the current format: an \
600 older version of ursa stored it, and {until} until it is rewritten",
601 self.database,
602 notices::size(size)
603 ),
604 _ => format!(
605 "an older version of ursa stored the index for {graph} in {}; {until} \
606 until it can be rewritten in the current format, and was {}",
607 self.database,
608 saved.describe(&self.database)
609 ),
610 });
611 }
612
613 fn discard(&self, file: &str, main: MainPart) {
619 let mut state = self.state();
620 state.damaged.insert((file.to_string(), main));
621 if !self.writable {
622 return;
623 }
624 self.ensure_loaded(&mut state);
625 if state.live.get(file).is_some_and(|live| live.main != main) {
626 return;
627 }
628 let before = state.entries.len();
629 state.entries.retain(|e| e.file != file);
630 state.live.remove(file);
631 if state.entries.len() != before {
632 let _ = write_manifest(&self.dir, &state.entries);
633 drop(state);
634 let _ = std::fs::remove_file(self.dir.join(file));
635 }
636 }
637
638 pub fn save(
643 self: &Arc<Self>,
644 key: IndexKey,
645 index: Arc<GraphIndex>,
646 graph: &str,
647 notifier: &Notifier,
648 ) -> Saved {
649 if !self.writable {
650 return Saved::ReadOnly;
651 }
652 self.use_notifier(notifier);
653 let limit = self.limit();
654 let encoded = match Encoded::with_dropped(
655 &key,
656 &index.topology,
657 &index.ids,
658 index.n_dropped(),
659 index.kept_rows(),
660 ) {
661 Ok(encoded) => encoded,
662 Err(e) => return Saved::Unstorable(e.to_string()),
663 };
664 let main = encoded.file_size();
665 let size = if main > limit {
666 main
667 } else {
668 index
670 .topology
671 .incoming_if_built()
672 .map(|incoming| EncodedChunk::incoming(incoming, main).end())
673 .filter(|end| *end <= limit)
674 .unwrap_or(main)
675 };
676 drop(encoded);
677 if size > limit {
678 return Saved::TooLarge { size, limit };
679 }
680 let with_incoming = size > main;
681 let grows_to = (!with_incoming).then(|| {
682 size.saturating_add(incoming_estimate(
683 index.topology.n_nodes() as u64,
684 index.topology.n_edges() as u64,
685 ))
686 });
687 let file = format!("{:016x}.idx", key.hash());
688
689 let mut state = self.state();
690 self.ensure_loaded(&mut state);
691 let replaced: Vec<String> = state
694 .entries
695 .iter()
696 .filter(|e| e.key.fingerprint == key.fingerprint || e.file == file)
697 .map(|e| e.file.clone())
698 .collect();
699 let evicted = match room_for(&state, size, &replaced, &[], limit) {
700 Ok(evicted) => evicted,
701 Err(NoRoom::OverLimit { stored }) => return Saved::OverLimit { stored, limit },
702 Err(NoRoom::InUse) => return Saved::NoRoom { size, limit },
703 };
704 let gone = self.remove(&mut state, &replaced, &evicted, notifier, limit);
705 state.reserved += size;
706 drop(state);
707 for file in gone {
708 let _ = std::fs::remove_file(self.dir.join(file));
709 }
710
711 let store = Arc::clone(self);
712 let (graph, notifier) = (graph.to_string(), notifier.clone());
713 let spawned = std::thread::Builder::new()
714 .name("ursa-index-write".into())
715 .spawn(move || {
716 let written = store.write(&key, &index, &file, size, with_incoming, &graph);
717 if let Err(e) = written {
718 store.state().reserved -= size;
719 notifier.say(NoticeLevel::On, || {
720 format!(
721 "could not store the index for {graph} in {}: {e}; it is built \
722 again when next needed",
723 store.database
724 )
725 });
726 }
727 });
728 match spawned {
729 Ok(handle) => {
730 let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
731 pending.retain(|h| !h.is_finished());
732 pending.push(handle);
733 Saved::Stored { size, grows_to }
734 }
735 Err(e) => {
736 self.state().reserved -= size;
737 Saved::Unstorable(format!("cannot start its write: {e}"))
738 }
739 }
740 }
741
742 fn remove(
745 &self,
746 state: &mut State,
747 replaced: &[String],
748 evicted: &[String],
749 notifier: &Notifier,
750 limit: u64,
751 ) -> Vec<String> {
752 if replaced.is_empty() && evicted.is_empty() {
753 return Vec::new();
754 }
755 let mut gone = Vec::new();
756 state.entries.retain(|e| {
757 if evicted.contains(&e.file) {
758 notifier.say(NoticeLevel::On, || {
759 format!(
760 "evicted the stored index for {} ({}, the least recently used) from {} \
761 to stay within ursa.index_storage_limit ({})",
762 e.graph,
763 notices::size(e.size),
764 self.database,
765 ByteSize(limit)
766 )
767 });
768 }
769 let keep = !replaced.contains(&e.file) && !evicted.contains(&e.file);
770 if !keep {
771 gone.push(e.file.clone());
772 }
773 keep
774 });
775 let _ = write_manifest(&self.dir, &state.entries);
776 gone
777 }
778
779 pub fn flush(&self) {
784 let handles = std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()));
785 for handle in handles {
786 let _ = handle.join();
787 }
788 if self.writable {
789 self.append_chunks();
790 }
791 }
792
793 fn append_chunks(&self) {
799 let notifier = self.notifier();
800 let limit = self.limit();
801 let mut state = self.state();
802 self.ensure_loaded(&mut state);
803 let files: Vec<String> = state.live.keys().cloned().collect();
804 let mut gone = Vec::new();
805 for file in files {
806 let live = &state.live[&file];
807 let Some(index) = live.index.upgrade() else {
808 continue;
809 };
810 let (main, graph) = (live.main, live.graph.clone());
811 let mut todo: Vec<(u32, Vec<u8>)> = Vec::new();
812 if index.topology.incoming_if_built().is_some() {
813 todo.push((CHUNK_INCOMING, Vec::new()));
814 }
815 let weight_sets = index.weight_sets();
816 todo.extend(
817 weight_sets
818 .iter()
819 .map(|(key, _)| (CHUNK_WEIGHTS, key.as_bytes().to_vec())),
820 );
821 todo.retain(|chunk| !live.chunks.contains(chunk) && !live.declined.contains(chunk));
822 for (kind, name) in todo {
823 let Some(entry) = state.entries.iter().position(|e| e.file == file) else {
824 break;
825 };
826 let columns: Vec<&[f64]> = match kind {
827 CHUNK_WEIGHTS => weight_sets
828 .iter()
829 .find(|(key, _)| key.as_bytes() == name.as_slice())
830 .map(|(_, w)| w.iter().map(|c| c.as_slice()).collect())
831 .unwrap_or_default(),
832 _ => Vec::new(),
833 };
834 let encode = |start| match kind {
835 CHUNK_WEIGHTS => EncodedChunk::weights(
836 std::str::from_utf8(&name).unwrap_or_default(),
837 &columns,
838 start,
839 ),
840 _ => EncodedChunk::incoming(
841 index.topology.incoming_if_built().expect("checked above"),
842 start,
843 ),
844 };
845 let size = state.entries[entry].size;
846 let need = encode(size).size();
847 let what = chunk_noun(kind);
848 let room = room_for(&state, need, &[], std::slice::from_ref(&file), limit);
849 let Ok(evicted) = room else {
850 notifier.say(NoticeLevel::On, || match room {
851 Err(NoRoom::OverLimit { stored }) => format!(
852 "did not store the {what} of the index for {graph} ({}) in {}: the \
853 stored indexes already take {}, more than \
854 ursa.index_storage_limit ({})",
855 notices::size(need),
856 self.database,
857 notices::size(stored),
858 ByteSize(limit)
859 ),
860 _ => format!(
861 "did not store the {what} of the index for {graph} ({}) in {}: it \
862 would take the stored indexes past ursa.index_storage_limit ({})",
863 notices::size(need),
864 self.database,
865 ByteSize(limit)
866 ),
867 });
868 if let Some(live) = state.live.get_mut(&file) {
869 live.declined.insert((kind, name));
870 }
871 continue;
872 };
873 gone.extend(self.remove(&mut state, &[], &evicted, ¬ifier, limit));
874 let Some(entry) = state.entries.iter().position(|e| e.file == file) else {
875 break;
876 };
877 let result =
878 index_file::append_chunk(&self.dir.join(&file), main, kind, &name, encode);
879 match result {
880 Ok(appended_len) => {
881 if let Some(live) = state.live.get_mut(&file) {
882 live.chunks.insert((kind, name));
883 }
884 if let Some(len) = appended_len {
885 state.entries[entry].size = len;
886 let _ = write_manifest(&self.dir, &state.entries);
887 let stored =
888 state.reserved + state.entries.iter().map(|e| e.size).sum::<u64>();
889 say_appended(
890 ¬ifier,
891 &Appended {
892 what: chunk_noun(kind),
893 graph: &graph,
894 database: &self.database,
895 added: len.saturating_sub(size),
896 total: len,
897 stored,
898 limit,
899 },
900 );
901 }
902 }
903 Err(e) => notifier.say(NoticeLevel::On, || {
904 format!(
905 "could not store the {} of {graph} in {}: {e}",
906 chunk_noun(kind),
907 self.database
908 )
909 }),
910 }
911 }
912 }
913 drop(state);
914 for file in gone {
915 let _ = std::fs::remove_file(self.dir.join(file));
916 }
917 }
918
919 fn write(
923 &self,
924 key: &IndexKey,
925 index: &Arc<GraphIndex>,
926 file: &str,
927 planned: u64,
928 with_incoming: bool,
929 graph: &str,
930 ) -> std::io::Result<()> {
931 let encoded = Encoded::with_dropped(
932 key,
933 &index.topology,
934 &index.ids,
935 index.n_dropped(),
936 index.kept_rows(),
937 )?;
938 let incoming = index
939 .topology
940 .incoming_if_built()
941 .filter(|_| with_incoming)
942 .map(|incoming| EncodedChunk::incoming(incoming, encoded.file_size()));
943 let size = incoming
944 .as_ref()
945 .map_or(encoded.file_size(), EncodedChunk::end);
946 std::fs::create_dir_all(&self.dir)?;
947 let path = self.dir.join(file);
948 let temp = self.dir.join(format!("{file}.tmp"));
949 let written = (|| {
950 let out = File::create(&temp)?;
951 let mut writer = BufWriter::with_capacity(1 << 20, out);
952 let main = encoded.write_to(&mut writer)?;
953 if let Some(chunk) = &incoming {
954 chunk.write_to(&mut writer)?;
955 }
956 let out = writer.into_inner().map_err(|e| e.into_error())?;
957 out.sync_all()?;
958 std::fs::rename(&temp, &path)?;
959 Ok(main)
960 })();
961 let main = match written {
962 Ok(main) => main,
963 Err(e) => {
964 let _ = std::fs::remove_file(&temp);
965 return Err(e);
966 }
967 };
968
969 let mut state = self.state();
970 state.reserved -= planned;
971 state.entries.retain(|e| e.file != file);
972 let now = tick(&state.entries);
973 state.entries.push(Entry {
974 key: key.clone(),
975 file: file.to_string(),
976 graph: graph.to_string(),
977 size,
978 created: now,
979 last_used: now,
980 });
981 let chunks = incoming
982 .iter()
983 .map(|_| (CHUNK_INCOMING, Vec::new()))
984 .collect();
985 state.live.insert(
986 file.to_string(),
987 Live {
988 index: Arc::downgrade(index),
989 main,
990 chunks,
991 declined: HashSet::new(),
992 graph: graph.to_string(),
993 },
994 );
995 state.live.retain(|_, live| live.index.strong_count() > 0);
996 let saved = write_manifest(&self.dir, &state.entries);
997 drop(state);
998 sync_dir(&self.dir);
999 saved
1000 }
1001}
1002
1003impl Drop for IndexStore {
1004 fn drop(&mut self) {
1005 self.flush();
1006 }
1007}
1008
1009#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1011enum NoRoom {
1012 OverLimit { stored: u64 },
1015 InUse,
1017}
1018
1019fn room_for(
1026 state: &State,
1027 need: u64,
1028 dropping: &[String],
1029 keep: &[String],
1030 limit: u64,
1031) -> Result<Vec<String>, NoRoom> {
1032 let staying = |e: &&Entry| !dropping.contains(&e.file);
1033 let mut total: u64 = state.reserved
1034 + state
1035 .entries
1036 .iter()
1037 .filter(staying)
1038 .map(|e| e.size)
1039 .sum::<u64>();
1040 if total > limit {
1041 return Err(NoRoom::OverLimit { stored: total });
1042 }
1043 let mut candidates: Vec<&Entry> = state
1044 .entries
1045 .iter()
1046 .filter(staying)
1047 .filter(|e| !keep.contains(&e.file) && !in_use(&state.live, &e.file))
1048 .collect();
1049 candidates.sort_by_key(|e| (e.last_used, e.created));
1050 let mut evicted = Vec::new();
1051 let mut candidates = candidates.into_iter();
1052 while total.saturating_add(need) > limit {
1053 let entry = candidates.next().ok_or(NoRoom::InUse)?;
1054 total -= entry.size;
1055 evicted.push(entry.file.clone());
1056 }
1057 Ok(evicted)
1058}
1059
1060fn in_use(live: &HashMap<String, Live>, file: &str) -> bool {
1064 live.get(file)
1065 .is_some_and(|live| live.index.strong_count() > 1)
1066}
1067
1068fn tick(entries: &[Entry]) -> u64 {
1071 let now = SystemTime::now()
1072 .duration_since(UNIX_EPOCH)
1073 .map(|d| d.as_millis() as u64)
1074 .unwrap_or(0);
1075 let latest = entries
1076 .iter()
1077 .map(|e| e.last_used.max(e.created))
1078 .max()
1079 .map_or(0, |t| t + 1);
1080 now.max(latest)
1081}
1082
1083struct Manifest {
1086 entries: Vec<Entry>,
1087 foreign: Option<usize>,
1088}
1089
1090pub fn read_manifest(dir: &Path) -> Vec<Entry> {
1093 read_manifest_checked(dir).entries
1094}
1095
1096pub fn manifest_bytes(dir: &Path) -> u64 {
1098 read_manifest(dir).iter().map(|e| e.size).sum()
1099}
1100
1101pub fn incoming_estimate(n_nodes: u64, n_edges: u64) -> u64 {
1105 n_nodes
1106 .saturating_add(1)
1107 .saturating_mul(8)
1108 .saturating_add(n_edges.saturating_mul(8))
1109 .saturating_add(4096)
1110}
1111
1112fn read_manifest_checked(dir: &Path) -> Manifest {
1113 let empty = |foreign| Manifest {
1114 entries: Vec::new(),
1115 foreign,
1116 };
1117 let Ok(text) = std::fs::read_to_string(dir.join(MANIFEST)) else {
1118 return empty(None);
1119 };
1120 let Ok(value) = serde_json::from_str::<Value>(&text) else {
1121 return empty(None);
1122 };
1123 if value.get("format").and_then(Value::as_str) != Some(MANIFEST_FORMAT) {
1124 return empty(None);
1125 }
1126 let listed = value.get("indexes").and_then(Value::as_array);
1127 if value.get("version").and_then(Value::as_u64) != Some(MANIFEST_VERSION) {
1128 return empty(Some(listed.map_or(0, Vec::len)));
1129 }
1130 Manifest {
1131 entries: listed
1132 .map(|entries| entries.iter().filter_map(Entry::from_json).collect())
1133 .unwrap_or_default(),
1134 foreign: None,
1135 }
1136}
1137
1138const KEY_COUNTS: &str = "vertex_keys.json";
1142const KEY_COUNTS_FORMAT: &str = "ursa-vertex-keys";
1143const KEY_COUNTS_VERSION: u64 = 1;
1144const KEY_COUNTS_KEPT: usize = 64;
1146
1147fn read_key_counts(dir: &Path) -> Vec<IndexKey> {
1150 let Ok(text) = std::fs::read_to_string(dir.join(KEY_COUNTS)) else {
1151 return Vec::new();
1152 };
1153 let Ok(value) = serde_json::from_str::<Value>(&text) else {
1154 return Vec::new();
1155 };
1156 if value.get("format").and_then(Value::as_str) != Some(KEY_COUNTS_FORMAT)
1157 || value.get("version").and_then(Value::as_u64) != Some(KEY_COUNTS_VERSION)
1158 {
1159 return Vec::new();
1160 }
1161 value
1162 .get("counted")
1163 .and_then(Value::as_array)
1164 .map(|keys| keys.iter().filter_map(IndexKey::from_json).collect())
1165 .unwrap_or_default()
1166}
1167
1168fn write_key_counts(dir: &Path, counted: &[IndexKey]) -> std::io::Result<()> {
1170 std::fs::create_dir_all(dir)?;
1171 let value = json!({
1172 "format": KEY_COUNTS_FORMAT,
1173 "version": KEY_COUNTS_VERSION,
1174 "counted": counted.iter().map(IndexKey::to_json).collect::<Vec<_>>(),
1175 });
1176 let mut text = serde_json::to_string_pretty(&value).map_err(std::io::Error::other)?;
1177 text.push('\n');
1178 let temp = dir.join(format!("{KEY_COUNTS}.new"));
1180 {
1181 let mut file = File::create(&temp)?;
1182 file.write_all(text.as_bytes())?;
1183 file.sync_all()?;
1184 }
1185 std::fs::rename(&temp, dir.join(KEY_COUNTS))?;
1186 sync_dir(dir);
1187 Ok(())
1188}
1189
1190fn write_manifest(dir: &Path, entries: &[Entry]) -> std::io::Result<()> {
1192 std::fs::create_dir_all(dir)?;
1193 let value = json!({
1194 "format": MANIFEST_FORMAT,
1195 "version": MANIFEST_VERSION,
1196 "indexes": entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
1197 });
1198 let mut text = serde_json::to_string_pretty(&value).map_err(std::io::Error::other)?;
1199 text.push('\n');
1200 let temp = dir.join(format!("{MANIFEST}.tmp"));
1201 {
1202 let mut file = File::create(&temp)?;
1203 file.write_all(text.as_bytes())?;
1204 file.sync_all()?;
1205 }
1206 std::fs::rename(&temp, dir.join(MANIFEST))?;
1207 sync_dir(dir);
1208 Ok(())
1209}
1210
1211fn sync_dir(dir: &Path) {
1213 #[cfg(unix)]
1214 if let Ok(dir) = File::open(dir) {
1215 let _ = dir.sync_all();
1216 }
1217 #[cfg(not(unix))]
1218 let _ = dir;
1219}
1220
1221fn chunk_noun(kind: u32) -> &'static str {
1223 match kind {
1224 CHUNK_WEIGHTS => "evaluated weights",
1225 _ => "reverse adjacency",
1226 }
1227}
1228
1229const NEAR_LIMIT_PERCENT: u64 = 90;
1232
1233struct Appended<'a> {
1235 what: &'static str,
1236 graph: &'a str,
1237 database: &'a str,
1238 added: u64,
1240 total: u64,
1242 stored: u64,
1244 limit: u64,
1245}
1246
1247fn say_appended(notifier: &Notifier, appended: &Appended) {
1251 let near =
1252 appended.stored.saturating_mul(100) >= appended.limit.saturating_mul(NEAR_LIMIT_PERCENT);
1253 let level = if near {
1254 NoticeLevel::On
1255 } else {
1256 NoticeLevel::All
1257 };
1258 notifier.say(level, || appended_notice(appended, near));
1259}
1260
1261fn appended_notice(appended: &Appended, near: bool) -> String {
1262 let mut text = format!(
1263 "stored the {} of {} in {} (+{}, {} in all)",
1264 appended.what,
1265 appended.graph,
1266 appended.database,
1267 notices::size(appended.added),
1268 notices::size(appended.total)
1269 );
1270 if near {
1271 text.push_str(&format!(
1272 "; the stored indexes now take {} of ursa.index_storage_limit ({})",
1273 notices::size(appended.stored),
1274 ByteSize(appended.limit)
1275 ));
1276 }
1277 text
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282 use super::*;
1283
1284 #[test]
1285 fn the_notice_for_a_stored_reverse_adjacency() {
1286 let gib = 1u64 << 30;
1287 let appended = Appended {
1288 what: "reverse adjacency",
1289 graph: "bsky23p",
1290 database: "bsky10.ursa",
1291 added: gib + gib / 10,
1292 total: 2 * gib + gib / 2,
1293 stored: 2 * gib + gib / 2,
1294 limit: 20 * gib,
1295 };
1296 assert_eq!(
1297 appended_notice(&appended, false),
1298 "stored the reverse adjacency of bsky23p in bsky10.ursa (+1.1 GiB, 2.5 GiB in all)"
1299 );
1300 assert_eq!(
1301 appended_notice(&appended, true),
1302 "stored the reverse adjacency of bsky23p in bsky10.ursa (+1.1 GiB, 2.5 GiB in all); \
1303 the stored indexes now take 2.5 GiB of ursa.index_storage_limit (20GiB)"
1304 );
1305 }
1306
1307 #[test]
1308 fn eviction_only_makes_room_and_never_below_a_lowered_limit() {
1309 let entry = |file: &str, size, last_used| Entry {
1310 key: IndexKey::new(file.into(), Vec::new()),
1311 file: file.into(),
1312 graph: file.into(),
1313 size,
1314 created: 0,
1315 last_used,
1316 };
1317 let state = State {
1318 loaded: true,
1319 entries: vec![entry("a", 300, 1), entry("b", 300, 2), entry("c", 300, 3)],
1320 ..State::default()
1321 };
1322 assert_eq!(room_for(&state, 100, &[], &[], 1000), Ok(vec![]));
1324 assert_eq!(room_for(&state, 200, &[], &[], 1000), Ok(vec!["a".into()]));
1326 assert_eq!(
1327 room_for(&state, 700, &[], &[], 1000),
1328 Ok(vec!["a".into(), "b".into()])
1329 );
1330 assert_eq!(
1333 room_for(&state, 1, &[], &[], 500),
1334 Err(NoRoom::OverLimit { stored: 900 })
1335 );
1336 assert_eq!(room_for(&state, 100, &["c".into()], &[], 700), Ok(vec![]));
1338 assert_eq!(
1340 room_for(&state, 900, &[], &["a".into(), "b".into()], 1000),
1341 Err(NoRoom::InUse)
1342 );
1343 }
1344
1345 #[test]
1346 fn a_stored_notice_says_how_the_index_grows() {
1347 let gib = 1u64 << 30;
1348 assert_eq!(
1349 Saved::Stored {
1350 size: 768 << 20,
1351 grows_to: Some(3 * gib / 2)
1352 }
1353 .describe("club.ursa"),
1354 "stored in club.ursa (768.0 MiB; about 1.5 GiB once an algorithm adds the reverse \
1355 adjacency)"
1356 );
1357 assert_eq!(
1358 Saved::Stored {
1359 size: 3 * gib / 2,
1360 grows_to: None
1361 }
1362 .describe("club.ursa"),
1363 "stored in club.ursa (1.5 GiB, with its reverse adjacency)"
1364 );
1365 let more = incoming_estimate(10_000_000, 95_700_000);
1367 assert!((800 << 20..810 << 20).contains(&more), "{more}");
1368 }
1369
1370 #[test]
1371 fn the_suggested_limit_leaves_room_for_the_in_adjacency() {
1372 let gib = 1u64 << 30;
1373 assert_eq!(suggested_limit(21 * gib), 64 * gib);
1374 assert_eq!(suggested_limit(1_503_238_554), 4 * gib);
1375 assert_eq!(suggested_limit(3000), 1 << 20);
1376 assert_eq!(ByteSize(suggested_limit(13 * gib)).to_string(), "32GiB");
1377 }
1378}