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