Skip to main content

hashtree_cli/socialgraph/
mod.rs

1pub mod access;
2pub mod crawler;
3pub mod local_lists;
4pub mod snapshot;
5
6pub use access::SocialGraphAccessControl;
7pub use crawler::SocialGraphCrawler;
8pub use local_lists::{
9    read_local_list_file_state, sync_local_list_files_force, sync_local_list_files_if_changed,
10    LocalListFileState, LocalListSyncOutcome,
11};
12
13mod index_buckets;
14
15use index_buckets::{
16    dedupe_events, latest_metadata_events_by_pubkey, EventIndexBucket, ProfileIndexBucket,
17};
18
19use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
20use std::path::{Path, PathBuf};
21use std::sync::{Arc, Mutex as StdMutex};
22
23use anyhow::{Context, Result};
24use bytes::Bytes;
25use futures::executor::block_on;
26use hashtree_core::{nhash_encode_full, Cid, HashTree, HashTreeConfig, NHashData};
27use hashtree_index::BTree;
28use hashtree_nostr::{
29    is_parameterized_replaceable_kind, is_replaceable_kind, ListEventsOptions, NostrEventStore,
30    NostrEventStoreError, ProfileGuard as NostrProfileGuard, StoredNostrEvent,
31};
32#[cfg(test)]
33use hashtree_nostr::{
34    reset_profile as reset_nostr_profile, set_profile_enabled as set_nostr_profile_enabled,
35    take_profile as take_nostr_profile,
36};
37use nostr::{Event, Filter, JsonUtil, Kind, SingleLetterTag};
38use nostr_social_graph::{
39    BinaryBudget, GraphStats, NostrEvent as GraphEvent, SocialGraph,
40    SocialGraphBackend as NostrSocialGraphBackend,
41};
42use nostr_social_graph_heed::HeedSocialGraph;
43
44use crate::storage::{LocalStore, StorageRouter};
45
46#[cfg(test)]
47use std::sync::{Mutex, MutexGuard, OnceLock};
48#[cfg(test)]
49use std::time::Instant;
50
51pub type UserSet = BTreeSet<[u8; 32]>;
52
53const DEFAULT_ROOT_HEX: &str = "0000000000000000000000000000000000000000000000000000000000000000";
54const EVENTS_ROOT_FILE: &str = "events-root.msgpack";
55const AMBIENT_EVENTS_ROOT_FILE: &str = "events-root-ambient.msgpack";
56const AMBIENT_EVENTS_BLOB_DIR: &str = "ambient-blobs";
57const PROFILE_SEARCH_ROOT_FILE: &str = "profile-search-root.msgpack";
58const PROFILES_BY_PUBKEY_ROOT_FILE: &str = "profiles-by-pubkey-root.msgpack";
59const UNKNOWN_FOLLOW_DISTANCE: u32 = 1000;
60const DEFAULT_SOCIALGRAPH_MAP_SIZE_BYTES: u64 = 64 * 1024 * 1024;
61const SOCIALGRAPH_MAX_DBS: u32 = 16;
62const PROFILE_SEARCH_INDEX_ORDER: usize = 64;
63const PROFILE_SEARCH_PREFIX: &str = "p:";
64const PROFILE_NAME_MAX_LENGTH: usize = 100;
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum EventStorageClass {
68    Public,
69    Ambient,
70}
71
72#[cfg_attr(not(test), allow(dead_code))]
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub(crate) enum EventQueryScope {
75    PublicOnly,
76    AmbientOnly,
77    All,
78}
79
80#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
81struct StoredCid {
82    hash: [u8; 32],
83    key: Option<[u8; 32]>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
87pub struct StoredProfileSearchEntry {
88    pub pubkey: String,
89    pub name: String,
90    #[serde(default)]
91    pub aliases: Vec<String>,
92    #[serde(default)]
93    pub nip05: Option<String>,
94    pub created_at: u64,
95    pub event_nhash: String,
96}
97
98#[derive(Debug, Clone, Default, serde::Serialize)]
99pub struct SocialGraphStats {
100    pub total_users: usize,
101    pub root: Option<String>,
102    pub total_follows: usize,
103    pub max_depth: u32,
104    pub size_by_distance: BTreeMap<u32, usize>,
105    pub enabled: bool,
106}
107
108#[derive(Debug, Clone)]
109struct DistanceCache {
110    stats: SocialGraphStats,
111    users_by_distance: BTreeMap<u32, Vec<[u8; 32]>>,
112}
113
114#[derive(Debug, thiserror::Error)]
115#[error("{0}")]
116pub struct UpstreamGraphBackendError(String);
117
118pub struct SocialGraphStore {
119    graph: StdMutex<HeedSocialGraph>,
120    distance_cache: StdMutex<Option<DistanceCache>>,
121    public_events: EventIndexBucket,
122    ambient_events: EventIndexBucket,
123    profile_index: ProfileIndexBucket,
124    profile_index_overmute_threshold: StdMutex<f64>,
125}
126
127pub trait SocialGraphBackend: Send + Sync {
128    fn stats(&self) -> Result<SocialGraphStats>;
129    fn users_by_follow_distance(&self, distance: u32) -> Result<Vec<[u8; 32]>>;
130    fn follow_distance(&self, pk_bytes: &[u8; 32]) -> Result<Option<u32>>;
131    fn follow_list_created_at(&self, owner: &[u8; 32]) -> Result<Option<u64>>;
132    fn followed_targets(&self, owner: &[u8; 32]) -> Result<UserSet>;
133    fn is_overmuted_user(&self, user_pk: &[u8; 32], threshold: f64) -> Result<bool>;
134    fn profile_search_root(&self) -> Result<Option<Cid>> {
135        Ok(None)
136    }
137    fn snapshot_chunks(&self, root: &[u8; 32], options: &BinaryBudget) -> Result<Vec<Bytes>>;
138    fn ingest_event(&self, event: &Event) -> Result<()>;
139    fn ingest_event_with_storage_class(
140        &self,
141        event: &Event,
142        storage_class: EventStorageClass,
143    ) -> Result<()> {
144        let _ = storage_class;
145        self.ingest_event(event)
146    }
147    fn ingest_events(&self, events: &[Event]) -> Result<()> {
148        for event in events {
149            self.ingest_event(event)?;
150        }
151        Ok(())
152    }
153    fn ingest_events_with_storage_class(
154        &self,
155        events: &[Event],
156        storage_class: EventStorageClass,
157    ) -> Result<()> {
158        for event in events {
159            self.ingest_event_with_storage_class(event, storage_class)?;
160        }
161        Ok(())
162    }
163    fn ingest_graph_events(&self, events: &[Event]) -> Result<()> {
164        self.ingest_events(events)
165    }
166    fn query_events(&self, filter: &Filter, limit: usize) -> Result<Vec<Event>>;
167}
168
169#[cfg(test)]
170pub type TestLockGuard = MutexGuard<'static, ()>;
171
172#[cfg(test)]
173static NDB_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
174
175#[cfg(test)]
176pub fn test_lock() -> TestLockGuard {
177    NDB_TEST_LOCK
178        .get_or_init(|| Mutex::new(()))
179        .lock()
180        .unwrap_or_else(|err| err.into_inner())
181}
182
183pub fn open_social_graph_store(data_dir: &Path) -> Result<Arc<SocialGraphStore>> {
184    open_social_graph_store_with_mapsize(data_dir, None)
185}
186
187pub fn open_social_graph_store_with_mapsize(
188    data_dir: &Path,
189    mapsize_bytes: Option<u64>,
190) -> Result<Arc<SocialGraphStore>> {
191    let db_dir = data_dir.join("socialgraph");
192    open_social_graph_store_at_path(&db_dir, mapsize_bytes)
193}
194
195pub fn open_social_graph_store_with_storage(
196    data_dir: &Path,
197    store: Arc<StorageRouter>,
198    mapsize_bytes: Option<u64>,
199) -> Result<Arc<SocialGraphStore>> {
200    let db_dir = data_dir.join("socialgraph");
201    open_social_graph_store_at_path_with_storage(&db_dir, store, mapsize_bytes)
202}
203
204pub fn open_social_graph_store_at_path(
205    db_dir: &Path,
206    mapsize_bytes: Option<u64>,
207) -> Result<Arc<SocialGraphStore>> {
208    let config = hashtree_config::Config::load_or_default();
209    let backend = &config.storage.backend;
210    let local_store = Arc::new(
211        LocalStore::new_with_lmdb_map_size(db_dir.join("blobs"), backend, mapsize_bytes)
212            .map_err(|err| anyhow::anyhow!("Failed to create social graph blob store: {err}"))?,
213    );
214    let store = Arc::new(StorageRouter::new(local_store));
215    open_social_graph_store_at_path_with_storage(db_dir, store, mapsize_bytes)
216}
217
218pub fn open_social_graph_store_at_path_with_storage(
219    db_dir: &Path,
220    store: Arc<StorageRouter>,
221    mapsize_bytes: Option<u64>,
222) -> Result<Arc<SocialGraphStore>> {
223    let ambient_backend = store.local_store().backend();
224    let ambient_local = Arc::new(
225        LocalStore::new_with_lmdb_map_size(
226            db_dir.join(AMBIENT_EVENTS_BLOB_DIR),
227            &ambient_backend,
228            mapsize_bytes,
229        )
230        .map_err(|err| {
231            anyhow::anyhow!("Failed to create social graph ambient blob store: {err}")
232        })?,
233    );
234    let ambient_store = Arc::new(StorageRouter::new(ambient_local));
235    open_social_graph_store_at_path_with_storage_split(db_dir, store, ambient_store, mapsize_bytes)
236}
237
238pub fn open_social_graph_store_at_path_with_storage_split(
239    db_dir: &Path,
240    public_store: Arc<StorageRouter>,
241    ambient_store: Arc<StorageRouter>,
242    mapsize_bytes: Option<u64>,
243) -> Result<Arc<SocialGraphStore>> {
244    std::fs::create_dir_all(db_dir)?;
245    if let Some(size) = mapsize_bytes {
246        ensure_social_graph_mapsize(db_dir, size)?;
247    }
248    let graph = HeedSocialGraph::open(db_dir, DEFAULT_ROOT_HEX)
249        .context("open nostr-social-graph heed backend")?;
250
251    Ok(Arc::new(SocialGraphStore {
252        graph: StdMutex::new(graph),
253        distance_cache: StdMutex::new(None),
254        public_events: EventIndexBucket {
255            event_store: NostrEventStore::new(Arc::clone(&public_store)),
256            root_path: db_dir.join(EVENTS_ROOT_FILE),
257        },
258        ambient_events: EventIndexBucket {
259            event_store: NostrEventStore::new(ambient_store),
260            root_path: db_dir.join(AMBIENT_EVENTS_ROOT_FILE),
261        },
262        profile_index: ProfileIndexBucket {
263            tree: HashTree::new(HashTreeConfig::new(Arc::clone(&public_store))),
264            index: BTree::new(
265                public_store,
266                hashtree_index::BTreeOptions {
267                    order: Some(PROFILE_SEARCH_INDEX_ORDER),
268                },
269            ),
270            by_pubkey_root_path: db_dir.join(PROFILES_BY_PUBKEY_ROOT_FILE),
271            search_root_path: db_dir.join(PROFILE_SEARCH_ROOT_FILE),
272        },
273        profile_index_overmute_threshold: StdMutex::new(1.0),
274    }))
275}
276
277pub fn set_social_graph_root(store: &SocialGraphStore, pk_bytes: &[u8; 32]) {
278    if let Err(err) = store.set_root(pk_bytes) {
279        tracing::warn!("Failed to set social graph root: {err}");
280    }
281}
282
283pub fn get_follow_distance(
284    backend: &(impl SocialGraphBackend + ?Sized),
285    pk_bytes: &[u8; 32],
286) -> Option<u32> {
287    backend.follow_distance(pk_bytes).ok().flatten()
288}
289
290pub fn get_follows(
291    backend: &(impl SocialGraphBackend + ?Sized),
292    pk_bytes: &[u8; 32],
293) -> Vec<[u8; 32]> {
294    match backend.followed_targets(pk_bytes) {
295        Ok(set) => set.into_iter().collect(),
296        Err(_) => Vec::new(),
297    }
298}
299
300pub fn is_overmuted(
301    backend: &(impl SocialGraphBackend + ?Sized),
302    _root_pk: &[u8; 32],
303    user_pk: &[u8; 32],
304    threshold: f64,
305) -> bool {
306    backend
307        .is_overmuted_user(user_pk, threshold)
308        .unwrap_or(false)
309}
310
311pub fn ingest_event(backend: &(impl SocialGraphBackend + ?Sized), _sub_id: &str, event_json: &str) {
312    let event = match Event::from_json(event_json) {
313        Ok(event) => event,
314        Err(_) => return,
315    };
316
317    if let Err(err) = backend.ingest_event(&event) {
318        tracing::warn!("Failed to ingest social graph event: {err}");
319    }
320}
321
322pub fn ingest_parsed_event(
323    backend: &(impl SocialGraphBackend + ?Sized),
324    event: &Event,
325) -> Result<()> {
326    backend.ingest_event(event)
327}
328
329pub fn ingest_parsed_event_with_storage_class(
330    backend: &(impl SocialGraphBackend + ?Sized),
331    event: &Event,
332    storage_class: EventStorageClass,
333) -> Result<()> {
334    backend.ingest_event_with_storage_class(event, storage_class)
335}
336
337pub fn ingest_parsed_events(
338    backend: &(impl SocialGraphBackend + ?Sized),
339    events: &[Event],
340) -> Result<()> {
341    backend.ingest_events(events)
342}
343
344pub fn ingest_parsed_events_with_storage_class(
345    backend: &(impl SocialGraphBackend + ?Sized),
346    events: &[Event],
347    storage_class: EventStorageClass,
348) -> Result<()> {
349    backend.ingest_events_with_storage_class(events, storage_class)
350}
351
352pub fn ingest_graph_parsed_events(
353    backend: &(impl SocialGraphBackend + ?Sized),
354    events: &[Event],
355) -> Result<()> {
356    backend.ingest_graph_events(events)
357}
358
359pub fn query_events(
360    backend: &(impl SocialGraphBackend + ?Sized),
361    filter: &Filter,
362    limit: usize,
363) -> Vec<Event> {
364    backend.query_events(filter, limit).unwrap_or_default()
365}
366
367impl SocialGraphStore {
368    pub fn set_profile_index_overmute_threshold(&self, threshold: f64) {
369        *self
370            .profile_index_overmute_threshold
371            .lock()
372            .expect("profile index overmute threshold") = threshold;
373    }
374
375    fn profile_index_overmute_threshold(&self) -> f64 {
376        *self
377            .profile_index_overmute_threshold
378            .lock()
379            .expect("profile index overmute threshold")
380    }
381
382    fn invalidate_distance_cache(&self) {
383        *self.distance_cache.lock().unwrap() = None;
384    }
385
386    fn build_distance_cache(state: nostr_social_graph::SocialGraphState) -> Result<DistanceCache> {
387        let unique_ids = state
388            .unique_ids
389            .into_iter()
390            .map(|(pubkey, id)| decode_pubkey(&pubkey).map(|decoded| (id, decoded)))
391            .collect::<Result<HashMap<_, _>>>()?;
392
393        let mut users_by_distance = BTreeMap::new();
394        let mut size_by_distance = BTreeMap::new();
395        for (distance, users) in state.users_by_follow_distance {
396            let decoded = users
397                .into_iter()
398                .filter_map(|id| unique_ids.get(&id).copied())
399                .collect::<Vec<_>>();
400            size_by_distance.insert(distance, decoded.len());
401            users_by_distance.insert(distance, decoded);
402        }
403
404        let total_follows = state
405            .followed_by_user
406            .iter()
407            .map(|(_, targets)| targets.len())
408            .sum::<usize>();
409        let total_users = size_by_distance.values().copied().sum();
410        let max_depth = size_by_distance.keys().copied().max().unwrap_or_default();
411
412        Ok(DistanceCache {
413            stats: SocialGraphStats {
414                total_users,
415                root: Some(state.root),
416                total_follows,
417                max_depth,
418                size_by_distance,
419                enabled: true,
420            },
421            users_by_distance,
422        })
423    }
424
425    fn load_distance_cache(&self) -> Result<DistanceCache> {
426        if let Some(cache) = self.distance_cache.lock().unwrap().clone() {
427            return Ok(cache);
428        }
429
430        let state = {
431            let graph = self.graph.lock().unwrap();
432            graph.export_state().context("export social graph state")?
433        };
434        let cache = Self::build_distance_cache(state)?;
435        *self.distance_cache.lock().unwrap() = Some(cache.clone());
436        Ok(cache)
437    }
438
439    fn set_root(&self, root: &[u8; 32]) -> Result<()> {
440        let root_hex = hex::encode(root);
441        {
442            let mut graph = self.graph.lock().unwrap();
443            if should_replace_placeholder_root(&graph)? {
444                let fresh = SocialGraph::new(&root_hex);
445                graph
446                    .replace_state(&fresh.export_state())
447                    .context("replace placeholder social graph root")?;
448            } else {
449                graph
450                    .set_root(&root_hex)
451                    .context("set nostr-social-graph root")?;
452            }
453        }
454        self.invalidate_distance_cache();
455        Ok(())
456    }
457
458    fn stats(&self) -> Result<SocialGraphStats> {
459        Ok(self.load_distance_cache()?.stats)
460    }
461
462    fn follow_distance(&self, pk_bytes: &[u8; 32]) -> Result<Option<u32>> {
463        let graph = self.graph.lock().unwrap();
464        let distance = graph
465            .get_follow_distance(&hex::encode(pk_bytes))
466            .context("read social graph follow distance")?;
467        Ok((distance != UNKNOWN_FOLLOW_DISTANCE).then_some(distance))
468    }
469
470    fn users_by_follow_distance(&self, distance: u32) -> Result<Vec<[u8; 32]>> {
471        Ok(self
472            .load_distance_cache()?
473            .users_by_distance
474            .get(&distance)
475            .cloned()
476            .unwrap_or_default())
477    }
478
479    fn follow_list_created_at(&self, owner: &[u8; 32]) -> Result<Option<u64>> {
480        let graph = self.graph.lock().unwrap();
481        graph
482            .get_follow_list_created_at(&hex::encode(owner))
483            .context("read social graph follow list timestamp")
484    }
485
486    fn followed_targets(&self, owner: &[u8; 32]) -> Result<UserSet> {
487        let graph = self.graph.lock().unwrap();
488        decode_pubkey_set(
489            graph
490                .get_followed_by_user(&hex::encode(owner))
491                .context("read followed targets")?,
492        )
493    }
494
495    fn is_overmuted_user(&self, user_pk: &[u8; 32], threshold: f64) -> Result<bool> {
496        if threshold <= 0.0 {
497            return Ok(false);
498        }
499        let graph = self.graph.lock().unwrap();
500        graph
501            .is_overmuted(&hex::encode(user_pk), threshold)
502            .context("check social graph overmute")
503    }
504
505    #[cfg_attr(not(test), allow(dead_code))]
506    pub fn profile_search_root(&self) -> Result<Option<Cid>> {
507        self.profile_index.search_root()
508    }
509
510    #[cfg_attr(not(test), allow(dead_code))]
511    pub fn profiles_by_pubkey_root(&self) -> Result<Option<Cid>> {
512        self.profile_index.by_pubkey_root()
513    }
514
515    pub fn public_events_root(&self) -> Result<Option<Cid>> {
516        self.public_events.events_root()
517    }
518
519    pub(crate) fn write_public_events_root(&self, root: Option<&Cid>) -> Result<()> {
520        self.public_events.write_events_root(root)
521    }
522
523    #[cfg_attr(not(test), allow(dead_code))]
524    pub fn latest_profile_event(&self, pubkey_hex: &str) -> Result<Option<Event>> {
525        self.profile_index.profile_event_for_pubkey(pubkey_hex)
526    }
527
528    #[cfg_attr(not(test), allow(dead_code))]
529    pub fn profile_search_entries_for_prefix(
530        &self,
531        prefix: &str,
532    ) -> Result<Vec<(String, StoredProfileSearchEntry)>> {
533        self.profile_index.search_entries_for_prefix(prefix)
534    }
535
536    pub fn sync_profile_index_for_events(&self, events: &[Event]) -> Result<()> {
537        self.update_profile_index_for_events(events)
538    }
539
540    pub(crate) fn rebuild_profile_index_for_events(&self, events: &[Event]) -> Result<()> {
541        let latest_by_pubkey = self.filtered_latest_metadata_events_by_pubkey(events)?;
542        let (by_pubkey_root, search_root) = self
543            .profile_index
544            .rebuild_profile_events(latest_by_pubkey.into_values())?;
545        self.profile_index
546            .write_by_pubkey_root(by_pubkey_root.as_ref())?;
547        self.profile_index.write_search_root(search_root.as_ref())?;
548        Ok(())
549    }
550
551    pub(crate) async fn rebuild_profile_index_for_events_async(
552        &self,
553        events: &[Event],
554    ) -> Result<()> {
555        let latest_by_pubkey = self.filtered_latest_metadata_events_by_pubkey(events)?;
556        let (by_pubkey_root, search_root) = self
557            .profile_index
558            .rebuild_profile_events_async(latest_by_pubkey.into_values())
559            .await?;
560        self.profile_index
561            .write_by_pubkey_root(by_pubkey_root.as_ref())?;
562        self.profile_index.write_search_root(search_root.as_ref())?;
563        Ok(())
564    }
565
566    pub fn rebuild_profile_index_from_stored_events(&self) -> Result<usize> {
567        let public_events_root = self.public_events.events_root()?;
568        let ambient_events_root = self.ambient_events.events_root()?;
569        if public_events_root.is_none() && ambient_events_root.is_none() {
570            self.profile_index.write_by_pubkey_root(None)?;
571            self.profile_index.write_search_root(None)?;
572            return Ok(0);
573        }
574
575        let mut events = Vec::new();
576        for (bucket, root) in [
577            (&self.public_events, public_events_root),
578            (&self.ambient_events, ambient_events_root),
579        ] {
580            let Some(root) = root else {
581                continue;
582            };
583            let stored = block_on(bucket.event_store.list_by_kind_lossy(
584                Some(&root),
585                Kind::Metadata.as_u16() as u32,
586                ListEventsOptions::default(),
587            ))
588            .map_err(map_event_store_error)?;
589            events.extend(
590                stored
591                    .into_iter()
592                    .map(nostr_event_from_stored)
593                    .collect::<Result<Vec<_>>>()?,
594            );
595        }
596
597        let latest_count = self
598            .filtered_latest_metadata_events_by_pubkey(&events)?
599            .len();
600        self.rebuild_profile_index_for_events(&events)?;
601        Ok(latest_count)
602    }
603
604    pub async fn rebuild_profile_index_from_stored_events_async(&self) -> Result<usize> {
605        let public_events_root = self.public_events.events_root()?;
606        let ambient_events_root = self.ambient_events.events_root()?;
607        if public_events_root.is_none() && ambient_events_root.is_none() {
608            self.profile_index.write_by_pubkey_root(None)?;
609            self.profile_index.write_search_root(None)?;
610            return Ok(0);
611        }
612
613        let mut events = Vec::new();
614        for (bucket, root) in [
615            (&self.public_events, public_events_root),
616            (&self.ambient_events, ambient_events_root),
617        ] {
618            let Some(root) = root else {
619                continue;
620            };
621            let stored = bucket
622                .event_store
623                .list_by_kind_lossy(
624                    Some(&root),
625                    Kind::Metadata.as_u16() as u32,
626                    ListEventsOptions::default(),
627                )
628                .await
629                .map_err(map_event_store_error)?;
630            events.extend(
631                stored
632                    .into_iter()
633                    .map(nostr_event_from_stored)
634                    .collect::<Result<Vec<_>>>()?,
635            );
636        }
637
638        let latest_count = self
639            .filtered_latest_metadata_events_by_pubkey(&events)?
640            .len();
641        self.rebuild_profile_index_for_events_async(&events).await?;
642        Ok(latest_count)
643    }
644
645    pub fn rebuild_event_indexes_from_stored_events(&self) -> Result<(usize, usize)> {
646        let public_count =
647            self.rebuild_event_index_bucket_from_stored_events(&self.public_events)?;
648        let ambient_count =
649            self.rebuild_event_index_bucket_from_stored_events(&self.ambient_events)?;
650        self.rebuild_profile_index_from_stored_events()?;
651        Ok((public_count, ambient_count))
652    }
653
654    pub async fn rebuild_event_indexes_from_stored_events_async(&self) -> Result<(usize, usize)> {
655        let public_count = self
656            .rebuild_event_index_bucket_from_stored_events_async(&self.public_events)
657            .await?;
658        let ambient_count = self
659            .rebuild_event_index_bucket_from_stored_events_async(&self.ambient_events)
660            .await?;
661        self.rebuild_profile_index_from_stored_events_async()
662            .await?;
663        Ok((public_count, ambient_count))
664    }
665
666    fn rebuild_event_index_bucket_from_stored_events(
667        &self,
668        bucket: &EventIndexBucket,
669    ) -> Result<usize> {
670        let Some(root) = bucket.events_root()? else {
671            bucket.write_events_root(None)?;
672            return Ok(0);
673        };
674
675        let manifest = block_on(bucket.event_store.get_manifest(Some(&root)))
676            .map_err(map_event_store_error)?;
677        if manifest.by_kind_time_author.is_none() {
678            let next_root = block_on(bucket.event_store.upgrade_manifest_indexes(Some(&root)))
679                .map_err(map_event_store_error)?;
680            if next_root.as_ref() != Some(&root) {
681                bucket.write_events_root(next_root.as_ref())?;
682                return Ok(0);
683            }
684        }
685
686        let stored = block_on(
687            bucket
688                .event_store
689                .list_recent_lossy(Some(&root), ListEventsOptions::default()),
690        )
691        .map_err(map_event_store_error)?;
692        let count = stored.len();
693        let next_root =
694            block_on(bucket.event_store.build(None, stored)).map_err(map_event_store_error)?;
695        bucket.write_events_root(next_root.as_ref())?;
696        Ok(count)
697    }
698
699    async fn rebuild_event_index_bucket_from_stored_events_async(
700        &self,
701        bucket: &EventIndexBucket,
702    ) -> Result<usize> {
703        let Some(root) = bucket.events_root()? else {
704            bucket.write_events_root(None)?;
705            return Ok(0);
706        };
707
708        let manifest = bucket
709            .event_store
710            .get_manifest(Some(&root))
711            .await
712            .map_err(map_event_store_error)?;
713        if manifest.by_kind_time_author.is_none() {
714            let next_root = bucket
715                .event_store
716                .upgrade_manifest_indexes(Some(&root))
717                .await
718                .map_err(map_event_store_error)?;
719            if next_root.as_ref() != Some(&root) {
720                bucket.write_events_root(next_root.as_ref())?;
721                return Ok(0);
722            }
723        }
724
725        let stored = bucket
726            .event_store
727            .list_recent_lossy(Some(&root), ListEventsOptions::default())
728            .await
729            .map_err(map_event_store_error)?;
730        let count = stored.len();
731        let next_root = bucket
732            .event_store
733            .build(None, stored)
734            .await
735            .map_err(map_event_store_error)?;
736        bucket.write_events_root(next_root.as_ref())?;
737        Ok(count)
738    }
739
740    fn update_profile_index_for_events(&self, events: &[Event]) -> Result<()> {
741        let latest_by_pubkey = latest_metadata_events_by_pubkey(events);
742        let threshold = self.profile_index_overmute_threshold();
743
744        if latest_by_pubkey.is_empty() {
745            return Ok(());
746        }
747
748        let mut by_pubkey_root = self.profile_index.by_pubkey_root()?;
749        let mut search_root = self.profile_index.search_root()?;
750        let mut changed = false;
751
752        for event in latest_by_pubkey.into_values() {
753            let overmuted = self.is_overmuted_user(&event.pubkey.to_bytes(), threshold)?;
754            let (next_by_pubkey_root, next_search_root, updated) = if overmuted {
755                self.profile_index.remove_profile_event(
756                    by_pubkey_root.as_ref(),
757                    search_root.as_ref(),
758                    &event.pubkey.to_hex(),
759                )?
760            } else {
761                self.profile_index.update_profile_event(
762                    by_pubkey_root.as_ref(),
763                    search_root.as_ref(),
764                    event,
765                )?
766            };
767            if updated {
768                by_pubkey_root = next_by_pubkey_root;
769                search_root = next_search_root;
770                changed = true;
771            }
772        }
773
774        if changed {
775            self.profile_index
776                .write_by_pubkey_root(by_pubkey_root.as_ref())?;
777            self.profile_index.write_search_root(search_root.as_ref())?;
778        }
779
780        Ok(())
781    }
782
783    fn filtered_latest_metadata_events_by_pubkey<'a>(
784        &self,
785        events: &'a [Event],
786    ) -> Result<BTreeMap<String, &'a Event>> {
787        let threshold = self.profile_index_overmute_threshold();
788        let mut latest_by_pubkey = BTreeMap::<String, &Event>::new();
789        for event in events.iter().filter(|event| event.kind == Kind::Metadata) {
790            if self.is_overmuted_user(&event.pubkey.to_bytes(), threshold)? {
791                continue;
792            }
793            let pubkey = event.pubkey.to_hex();
794            match latest_by_pubkey.get(&pubkey) {
795                Some(current) if compare_nostr_events(event, current).is_le() => {}
796                _ => {
797                    latest_by_pubkey.insert(pubkey, event);
798                }
799            }
800        }
801        Ok(latest_by_pubkey)
802    }
803
804    fn snapshot_chunks(&self, root: &[u8; 32], options: &BinaryBudget) -> Result<Vec<Bytes>> {
805        let state = {
806            let graph = self.graph.lock().unwrap();
807            graph.export_state().context("export social graph state")?
808        };
809        let mut graph = SocialGraph::from_state(state).context("rebuild social graph state")?;
810        let root_hex = hex::encode(root);
811        if graph.get_root() != root_hex {
812            graph
813                .set_root(&root_hex)
814                .context("set snapshot social graph root")?;
815        }
816        let chunks = graph
817            .to_binary_chunks_with_budget(*options)
818            .context("encode social graph snapshot")?;
819        Ok(chunks.into_iter().map(Bytes::from).collect())
820    }
821
822    fn ingest_event(&self, event: &Event) -> Result<()> {
823        self.ingest_event_with_storage_class(event, self.default_storage_class_for(event)?)
824    }
825
826    fn ingest_events(&self, events: &[Event]) -> Result<()> {
827        if events.is_empty() {
828            return Ok(());
829        }
830
831        let mut public = Vec::new();
832        let mut ambient = Vec::new();
833        for event in events {
834            match self.default_storage_class_for(event)? {
835                EventStorageClass::Public => public.push(event.clone()),
836                EventStorageClass::Ambient => ambient.push(event.clone()),
837            }
838        }
839
840        if !public.is_empty() {
841            self.ingest_events_with_storage_class(&public, EventStorageClass::Public)?;
842        }
843        if !ambient.is_empty() {
844            self.ingest_events_with_storage_class(&ambient, EventStorageClass::Ambient)?;
845        }
846
847        Ok(())
848    }
849
850    fn apply_graph_events_only(&self, events: &[Event]) -> Result<()> {
851        let graph_events = events
852            .iter()
853            .filter(|event| is_social_graph_event(event.kind))
854            .collect::<Vec<_>>();
855        if graph_events.is_empty() {
856            return Ok(());
857        }
858
859        {
860            let mut graph = self.graph.lock().unwrap();
861            let mut snapshot = SocialGraph::from_state(
862                graph
863                    .export_state()
864                    .context("export social graph state for graph-only ingest")?,
865            )
866            .context("rebuild social graph state for graph-only ingest")?;
867            for event in graph_events {
868                snapshot.handle_event(&graph_event_from_nostr(event), true, 0.0);
869            }
870            graph
871                .replace_state(&snapshot.export_state())
872                .context("replace graph-only social graph state")?;
873        }
874        self.invalidate_distance_cache();
875        Ok(())
876    }
877
878    fn query_events(&self, filter: &Filter, limit: usize) -> Result<Vec<Event>> {
879        self.query_events_in_scope(filter, limit, EventQueryScope::All)
880    }
881
882    fn default_storage_class_for(&self, event: &Event) -> Result<EventStorageClass> {
883        let graph = self.graph.lock().unwrap();
884        let root_hex = graph.get_root().context("read social graph root")?;
885        if root_hex != DEFAULT_ROOT_HEX && root_hex == event.pubkey.to_hex() {
886            return Ok(EventStorageClass::Public);
887        }
888        Ok(EventStorageClass::Ambient)
889    }
890
891    fn bucket(&self, storage_class: EventStorageClass) -> &EventIndexBucket {
892        match storage_class {
893            EventStorageClass::Public => &self.public_events,
894            EventStorageClass::Ambient => &self.ambient_events,
895        }
896    }
897
898    fn ingest_event_with_storage_class(
899        &self,
900        event: &Event,
901        storage_class: EventStorageClass,
902    ) -> Result<()> {
903        let current_root = self.bucket(storage_class).events_root()?;
904        let next_root = self
905            .bucket(storage_class)
906            .store_event(current_root.as_ref(), event)?;
907        self.bucket(storage_class)
908            .write_events_root(Some(&next_root))?;
909
910        self.update_profile_index_for_events(std::slice::from_ref(event))?;
911
912        if is_social_graph_event(event.kind) {
913            {
914                let mut graph = self.graph.lock().unwrap();
915                graph
916                    .handle_event(&graph_event_from_nostr(event), true, 0.0)
917                    .context("ingest social graph event into nostr-social-graph")?;
918            }
919            self.invalidate_distance_cache();
920        }
921
922        Ok(())
923    }
924
925    fn ingest_events_with_storage_class(
926        &self,
927        events: &[Event],
928        storage_class: EventStorageClass,
929    ) -> Result<()> {
930        if events.is_empty() {
931            return Ok(());
932        }
933
934        let bucket = self.bucket(storage_class);
935        let current_root = bucket.events_root()?;
936        let stored_events = events
937            .iter()
938            .map(stored_event_from_nostr)
939            .collect::<Vec<_>>();
940        let next_root = block_on(
941            bucket
942                .event_store
943                .build(current_root.as_ref(), stored_events),
944        )
945        .map_err(map_event_store_error)?;
946        bucket.write_events_root(next_root.as_ref())?;
947
948        self.update_profile_index_for_events(events)?;
949
950        let graph_events = events
951            .iter()
952            .filter(|event| is_social_graph_event(event.kind))
953            .collect::<Vec<_>>();
954        if graph_events.is_empty() {
955            return Ok(());
956        }
957
958        {
959            let mut graph = self.graph.lock().unwrap();
960            let mut snapshot = SocialGraph::from_state(
961                graph
962                    .export_state()
963                    .context("export social graph state for batch ingest")?,
964            )
965            .context("rebuild social graph state for batch ingest")?;
966            for event in graph_events {
967                snapshot.handle_event(&graph_event_from_nostr(event), true, 0.0);
968            }
969            graph
970                .replace_state(&snapshot.export_state())
971                .context("replace batched social graph state")?;
972        }
973        self.invalidate_distance_cache();
974
975        Ok(())
976    }
977
978    pub(crate) fn query_events_in_scope(
979        &self,
980        filter: &Filter,
981        limit: usize,
982        scope: EventQueryScope,
983    ) -> Result<Vec<Event>> {
984        if limit == 0 {
985            return Ok(Vec::new());
986        }
987
988        let buckets: &[&EventIndexBucket] = match scope {
989            EventQueryScope::PublicOnly => &[&self.public_events],
990            EventQueryScope::AmbientOnly => &[&self.ambient_events],
991            EventQueryScope::All => &[&self.public_events, &self.ambient_events],
992        };
993
994        let mut candidates = Vec::new();
995        for bucket in buckets {
996            candidates.extend(bucket.query_events(filter, limit)?);
997        }
998
999        let mut deduped = dedupe_events(candidates);
1000        deduped.retain(|event| filter.match_event(event));
1001        deduped.truncate(limit);
1002        Ok(deduped)
1003    }
1004}
1005
1006impl SocialGraphBackend for SocialGraphStore {
1007    fn stats(&self) -> Result<SocialGraphStats> {
1008        SocialGraphStore::stats(self)
1009    }
1010
1011    fn users_by_follow_distance(&self, distance: u32) -> Result<Vec<[u8; 32]>> {
1012        SocialGraphStore::users_by_follow_distance(self, distance)
1013    }
1014
1015    fn follow_distance(&self, pk_bytes: &[u8; 32]) -> Result<Option<u32>> {
1016        SocialGraphStore::follow_distance(self, pk_bytes)
1017    }
1018
1019    fn follow_list_created_at(&self, owner: &[u8; 32]) -> Result<Option<u64>> {
1020        SocialGraphStore::follow_list_created_at(self, owner)
1021    }
1022
1023    fn followed_targets(&self, owner: &[u8; 32]) -> Result<UserSet> {
1024        SocialGraphStore::followed_targets(self, owner)
1025    }
1026
1027    fn is_overmuted_user(&self, user_pk: &[u8; 32], threshold: f64) -> Result<bool> {
1028        SocialGraphStore::is_overmuted_user(self, user_pk, threshold)
1029    }
1030
1031    fn profile_search_root(&self) -> Result<Option<Cid>> {
1032        SocialGraphStore::profile_search_root(self)
1033    }
1034
1035    fn snapshot_chunks(&self, root: &[u8; 32], options: &BinaryBudget) -> Result<Vec<Bytes>> {
1036        SocialGraphStore::snapshot_chunks(self, root, options)
1037    }
1038
1039    fn ingest_event(&self, event: &Event) -> Result<()> {
1040        SocialGraphStore::ingest_event(self, event)
1041    }
1042
1043    fn ingest_event_with_storage_class(
1044        &self,
1045        event: &Event,
1046        storage_class: EventStorageClass,
1047    ) -> Result<()> {
1048        SocialGraphStore::ingest_event_with_storage_class(self, event, storage_class)
1049    }
1050
1051    fn ingest_events(&self, events: &[Event]) -> Result<()> {
1052        SocialGraphStore::ingest_events(self, events)
1053    }
1054
1055    fn ingest_events_with_storage_class(
1056        &self,
1057        events: &[Event],
1058        storage_class: EventStorageClass,
1059    ) -> Result<()> {
1060        SocialGraphStore::ingest_events_with_storage_class(self, events, storage_class)
1061    }
1062
1063    fn ingest_graph_events(&self, events: &[Event]) -> Result<()> {
1064        SocialGraphStore::apply_graph_events_only(self, events)
1065    }
1066
1067    fn query_events(&self, filter: &Filter, limit: usize) -> Result<Vec<Event>> {
1068        SocialGraphStore::query_events(self, filter, limit)
1069    }
1070}
1071
1072impl NostrSocialGraphBackend for SocialGraphStore {
1073    type Error = UpstreamGraphBackendError;
1074
1075    fn get_root(&self) -> std::result::Result<String, Self::Error> {
1076        let graph = self.graph.lock().unwrap();
1077        graph
1078            .get_root()
1079            .context("read social graph root")
1080            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1081    }
1082
1083    fn set_root(&mut self, root: &str) -> std::result::Result<(), Self::Error> {
1084        let root_bytes =
1085            decode_pubkey(root).map_err(|err| UpstreamGraphBackendError(err.to_string()))?;
1086        SocialGraphStore::set_root(self, &root_bytes)
1087            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1088    }
1089
1090    fn handle_event(
1091        &mut self,
1092        event: &GraphEvent,
1093        allow_unknown_authors: bool,
1094        overmute_threshold: f64,
1095    ) -> std::result::Result<(), Self::Error> {
1096        {
1097            let mut graph = self.graph.lock().unwrap();
1098            graph
1099                .handle_event(event, allow_unknown_authors, overmute_threshold)
1100                .context("ingest social graph event into heed backend")
1101                .map_err(|err| UpstreamGraphBackendError(err.to_string()))?;
1102        }
1103        self.invalidate_distance_cache();
1104        Ok(())
1105    }
1106
1107    fn get_follow_distance(&self, user: &str) -> std::result::Result<u32, Self::Error> {
1108        let graph = self.graph.lock().unwrap();
1109        graph
1110            .get_follow_distance(user)
1111            .context("read social graph follow distance")
1112            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1113    }
1114
1115    fn is_following(
1116        &self,
1117        follower: &str,
1118        followed_user: &str,
1119    ) -> std::result::Result<bool, Self::Error> {
1120        let graph = self.graph.lock().unwrap();
1121        graph
1122            .is_following(follower, followed_user)
1123            .context("read social graph following edge")
1124            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1125    }
1126
1127    fn get_followed_by_user(&self, user: &str) -> std::result::Result<Vec<String>, Self::Error> {
1128        let graph = self.graph.lock().unwrap();
1129        graph
1130            .get_followed_by_user(user)
1131            .context("read followed-by-user list")
1132            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1133    }
1134
1135    fn get_followers_by_user(&self, user: &str) -> std::result::Result<Vec<String>, Self::Error> {
1136        let graph = self.graph.lock().unwrap();
1137        graph
1138            .get_followers_by_user(user)
1139            .context("read followers-by-user list")
1140            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1141    }
1142
1143    fn get_muted_by_user(&self, user: &str) -> std::result::Result<Vec<String>, Self::Error> {
1144        let graph = self.graph.lock().unwrap();
1145        graph
1146            .get_muted_by_user(user)
1147            .context("read muted-by-user list")
1148            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1149    }
1150
1151    fn get_user_muted_by(&self, user: &str) -> std::result::Result<Vec<String>, Self::Error> {
1152        let graph = self.graph.lock().unwrap();
1153        graph
1154            .get_user_muted_by(user)
1155            .context("read user-muted-by list")
1156            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1157    }
1158
1159    fn get_follow_list_created_at(
1160        &self,
1161        user: &str,
1162    ) -> std::result::Result<Option<u64>, Self::Error> {
1163        let graph = self.graph.lock().unwrap();
1164        graph
1165            .get_follow_list_created_at(user)
1166            .context("read social graph follow list timestamp")
1167            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1168    }
1169
1170    fn get_mute_list_created_at(
1171        &self,
1172        user: &str,
1173    ) -> std::result::Result<Option<u64>, Self::Error> {
1174        let graph = self.graph.lock().unwrap();
1175        graph
1176            .get_mute_list_created_at(user)
1177            .context("read social graph mute list timestamp")
1178            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1179    }
1180
1181    fn is_overmuted(&self, user: &str, threshold: f64) -> std::result::Result<bool, Self::Error> {
1182        let graph = self.graph.lock().unwrap();
1183        graph
1184            .is_overmuted(user, threshold)
1185            .context("check social graph overmute")
1186            .map_err(|err| UpstreamGraphBackendError(err.to_string()))
1187    }
1188}
1189
1190impl<T> SocialGraphBackend for Arc<T>
1191where
1192    T: SocialGraphBackend + ?Sized,
1193{
1194    fn stats(&self) -> Result<SocialGraphStats> {
1195        self.as_ref().stats()
1196    }
1197
1198    fn users_by_follow_distance(&self, distance: u32) -> Result<Vec<[u8; 32]>> {
1199        self.as_ref().users_by_follow_distance(distance)
1200    }
1201
1202    fn follow_distance(&self, pk_bytes: &[u8; 32]) -> Result<Option<u32>> {
1203        self.as_ref().follow_distance(pk_bytes)
1204    }
1205
1206    fn follow_list_created_at(&self, owner: &[u8; 32]) -> Result<Option<u64>> {
1207        self.as_ref().follow_list_created_at(owner)
1208    }
1209
1210    fn followed_targets(&self, owner: &[u8; 32]) -> Result<UserSet> {
1211        self.as_ref().followed_targets(owner)
1212    }
1213
1214    fn is_overmuted_user(&self, user_pk: &[u8; 32], threshold: f64) -> Result<bool> {
1215        self.as_ref().is_overmuted_user(user_pk, threshold)
1216    }
1217
1218    fn profile_search_root(&self) -> Result<Option<Cid>> {
1219        self.as_ref().profile_search_root()
1220    }
1221
1222    fn snapshot_chunks(&self, root: &[u8; 32], options: &BinaryBudget) -> Result<Vec<Bytes>> {
1223        self.as_ref().snapshot_chunks(root, options)
1224    }
1225
1226    fn ingest_event(&self, event: &Event) -> Result<()> {
1227        self.as_ref().ingest_event(event)
1228    }
1229
1230    fn ingest_event_with_storage_class(
1231        &self,
1232        event: &Event,
1233        storage_class: EventStorageClass,
1234    ) -> Result<()> {
1235        self.as_ref()
1236            .ingest_event_with_storage_class(event, storage_class)
1237    }
1238
1239    fn ingest_events(&self, events: &[Event]) -> Result<()> {
1240        self.as_ref().ingest_events(events)
1241    }
1242
1243    fn ingest_events_with_storage_class(
1244        &self,
1245        events: &[Event],
1246        storage_class: EventStorageClass,
1247    ) -> Result<()> {
1248        self.as_ref()
1249            .ingest_events_with_storage_class(events, storage_class)
1250    }
1251
1252    fn ingest_graph_events(&self, events: &[Event]) -> Result<()> {
1253        self.as_ref().ingest_graph_events(events)
1254    }
1255
1256    fn query_events(&self, filter: &Filter, limit: usize) -> Result<Vec<Event>> {
1257        self.as_ref().query_events(filter, limit)
1258    }
1259}
1260
1261fn should_replace_placeholder_root(graph: &HeedSocialGraph) -> Result<bool> {
1262    if graph.get_root().context("read current social graph root")? != DEFAULT_ROOT_HEX {
1263        return Ok(false);
1264    }
1265
1266    let GraphStats {
1267        users,
1268        follows,
1269        mutes,
1270        ..
1271    } = graph.size().context("size social graph")?;
1272    Ok(users <= 1 && follows == 0 && mutes == 0)
1273}
1274
1275fn decode_pubkey_set(values: Vec<String>) -> Result<UserSet> {
1276    let mut set = UserSet::new();
1277    for value in values {
1278        set.insert(decode_pubkey(&value)?);
1279    }
1280    Ok(set)
1281}
1282
1283fn decode_pubkey(value: &str) -> Result<[u8; 32]> {
1284    let mut bytes = [0u8; 32];
1285    hex::decode_to_slice(value, &mut bytes)
1286        .with_context(|| format!("decode social graph pubkey {value}"))?;
1287    Ok(bytes)
1288}
1289
1290fn is_social_graph_event(kind: Kind) -> bool {
1291    kind == Kind::ContactList || kind == Kind::MuteList
1292}
1293
1294fn graph_event_from_nostr(event: &Event) -> GraphEvent {
1295    GraphEvent {
1296        created_at: event.created_at.as_u64(),
1297        content: event.content.clone(),
1298        tags: event
1299            .tags
1300            .iter()
1301            .map(|tag| tag.as_slice().to_vec())
1302            .collect(),
1303        kind: event.kind.as_u16() as u32,
1304        pubkey: event.pubkey.to_hex(),
1305        id: event.id.to_hex(),
1306        sig: event.sig.to_string(),
1307    }
1308}
1309
1310fn stored_event_from_nostr(event: &Event) -> StoredNostrEvent {
1311    StoredNostrEvent {
1312        id: event.id.to_hex(),
1313        pubkey: event.pubkey.to_hex(),
1314        created_at: event.created_at.as_u64(),
1315        kind: event.kind.as_u16() as u32,
1316        tags: event
1317            .tags
1318            .iter()
1319            .map(|tag| tag.as_slice().to_vec())
1320            .collect(),
1321        content: event.content.clone(),
1322        sig: event.sig.to_string(),
1323    }
1324}
1325
1326fn nostr_event_from_stored(event: StoredNostrEvent) -> Result<Event> {
1327    let value = serde_json::json!({
1328        "id": event.id,
1329        "pubkey": event.pubkey,
1330        "created_at": event.created_at,
1331        "kind": event.kind,
1332        "tags": event.tags,
1333        "content": event.content,
1334        "sig": event.sig,
1335    });
1336    Event::from_json(value.to_string()).context("decode stored nostr event")
1337}
1338
1339pub(crate) fn stored_event_to_nostr_event(event: StoredNostrEvent) -> Result<Event> {
1340    nostr_event_from_stored(event)
1341}
1342
1343fn encode_cid(cid: &Cid) -> Result<Vec<u8>> {
1344    rmp_serde::to_vec_named(&StoredCid {
1345        hash: cid.hash,
1346        key: cid.key,
1347    })
1348    .context("encode social graph events root")
1349}
1350
1351fn decode_cid(bytes: &[u8]) -> Result<Option<Cid>> {
1352    let stored: StoredCid =
1353        rmp_serde::from_slice(bytes).context("decode social graph events root")?;
1354    Ok(Some(Cid {
1355        hash: stored.hash,
1356        key: stored.key,
1357    }))
1358}
1359
1360fn read_root_file(path: &Path) -> Result<Option<Cid>> {
1361    let Ok(bytes) = std::fs::read(path) else {
1362        return Ok(None);
1363    };
1364    decode_cid(&bytes)
1365}
1366
1367fn write_root_file(path: &Path, root: Option<&Cid>) -> Result<()> {
1368    let Some(root) = root else {
1369        if path.exists() {
1370            std::fs::remove_file(path)?;
1371        }
1372        return Ok(());
1373    };
1374
1375    let encoded = encode_cid(root)?;
1376    let tmp_path = path.with_extension("tmp");
1377    std::fs::write(&tmp_path, encoded)?;
1378    std::fs::rename(tmp_path, path)?;
1379    Ok(())
1380}
1381
1382fn normalize_profile_name(value: &serde_json::Value) -> Option<String> {
1383    let raw = value.as_str()?;
1384    let trimmed = raw.split_whitespace().collect::<Vec<_>>().join(" ");
1385    if trimmed.is_empty() {
1386        return None;
1387    }
1388    Some(trimmed.chars().take(PROFILE_NAME_MAX_LENGTH).collect())
1389}
1390
1391fn extract_profile_names(profile: &serde_json::Map<String, serde_json::Value>) -> Vec<String> {
1392    let mut names = Vec::new();
1393    let mut seen = HashSet::new();
1394
1395    for key in ["display_name", "displayName", "name", "username"] {
1396        let Some(value) = profile.get(key).and_then(normalize_profile_name) else {
1397            continue;
1398        };
1399        let lowered = value.to_lowercase();
1400        if seen.insert(lowered) {
1401            names.push(value);
1402        }
1403    }
1404
1405    names
1406}
1407
1408fn should_reject_profile_nip05(local_part: &str, primary_name: &str) -> bool {
1409    if local_part.len() == 1 || local_part.starts_with("npub1") {
1410        return true;
1411    }
1412
1413    primary_name
1414        .to_lowercase()
1415        .split_whitespace()
1416        .collect::<String>()
1417        .contains(local_part)
1418}
1419
1420fn normalize_profile_nip05(
1421    profile: &serde_json::Map<String, serde_json::Value>,
1422    primary_name: Option<&str>,
1423) -> Option<String> {
1424    let raw = profile.get("nip05")?.as_str()?;
1425    let local_part = raw.split('@').next()?.trim().to_lowercase();
1426    if local_part.is_empty() {
1427        return None;
1428    }
1429    let truncated: String = local_part.chars().take(PROFILE_NAME_MAX_LENGTH).collect();
1430    if truncated.is_empty() {
1431        return None;
1432    }
1433    if primary_name.is_some_and(|name| should_reject_profile_nip05(&truncated, name)) {
1434        return None;
1435    }
1436    Some(truncated)
1437}
1438
1439fn is_search_stop_word(word: &str) -> bool {
1440    matches!(
1441        word,
1442        "a" | "an"
1443            | "the"
1444            | "and"
1445            | "or"
1446            | "but"
1447            | "in"
1448            | "on"
1449            | "at"
1450            | "to"
1451            | "for"
1452            | "of"
1453            | "with"
1454            | "by"
1455            | "from"
1456            | "is"
1457            | "it"
1458            | "as"
1459            | "be"
1460            | "was"
1461            | "are"
1462            | "this"
1463            | "that"
1464            | "these"
1465            | "those"
1466            | "i"
1467            | "you"
1468            | "he"
1469            | "she"
1470            | "we"
1471            | "they"
1472            | "my"
1473            | "your"
1474            | "his"
1475            | "her"
1476            | "its"
1477            | "our"
1478            | "their"
1479            | "what"
1480            | "which"
1481            | "who"
1482            | "whom"
1483            | "how"
1484            | "when"
1485            | "where"
1486            | "why"
1487            | "will"
1488            | "would"
1489            | "could"
1490            | "should"
1491            | "can"
1492            | "may"
1493            | "might"
1494            | "must"
1495            | "have"
1496            | "has"
1497            | "had"
1498            | "do"
1499            | "does"
1500            | "did"
1501            | "been"
1502            | "being"
1503            | "get"
1504            | "got"
1505            | "just"
1506            | "now"
1507            | "then"
1508            | "so"
1509            | "if"
1510            | "not"
1511            | "no"
1512            | "yes"
1513            | "all"
1514            | "any"
1515            | "some"
1516            | "more"
1517            | "most"
1518            | "other"
1519            | "into"
1520            | "over"
1521            | "after"
1522            | "before"
1523            | "about"
1524            | "up"
1525            | "down"
1526            | "out"
1527            | "off"
1528            | "through"
1529            | "during"
1530            | "under"
1531            | "again"
1532            | "further"
1533            | "once"
1534    )
1535}
1536
1537fn is_pure_search_number(word: &str) -> bool {
1538    if !word.chars().all(|ch| ch.is_ascii_digit()) {
1539        return false;
1540    }
1541    !(word.len() == 4
1542        && word
1543            .parse::<u16>()
1544            .is_ok_and(|year| (1900..=2099).contains(&year)))
1545}
1546
1547fn split_compound_search_word(word: &str) -> Vec<String> {
1548    let mut parts = Vec::new();
1549    let mut current = String::new();
1550    let chars: Vec<char> = word.chars().collect();
1551
1552    for (index, ch) in chars.iter().copied().enumerate() {
1553        let split_before = current.chars().last().is_some_and(|prev| {
1554            (prev.is_lowercase() && ch.is_uppercase())
1555                || (prev.is_ascii_digit() && ch.is_alphabetic())
1556                || (prev.is_alphabetic() && ch.is_ascii_digit())
1557                || (prev.is_uppercase()
1558                    && ch.is_uppercase()
1559                    && chars.get(index + 1).is_some_and(|next| next.is_lowercase()))
1560        });
1561
1562        if split_before && !current.is_empty() {
1563            parts.push(std::mem::take(&mut current));
1564        }
1565
1566        current.push(ch);
1567    }
1568
1569    if !current.is_empty() {
1570        parts.push(current);
1571    }
1572
1573    parts
1574}
1575
1576fn parse_search_keywords(text: &str) -> Vec<String> {
1577    let mut keywords = Vec::new();
1578    let mut seen = HashSet::new();
1579
1580    for word in text
1581        .split(|ch: char| !ch.is_alphanumeric())
1582        .filter(|word| !word.is_empty())
1583    {
1584        let mut variants = Vec::with_capacity(1 + word.len() / 4);
1585        variants.push(word.to_lowercase());
1586        variants.extend(
1587            split_compound_search_word(word)
1588                .into_iter()
1589                .map(|part| part.to_lowercase()),
1590        );
1591
1592        for lowered in variants {
1593            if lowered.chars().count() < 2
1594                || is_search_stop_word(&lowered)
1595                || is_pure_search_number(&lowered)
1596            {
1597                continue;
1598            }
1599            if seen.insert(lowered.clone()) {
1600                keywords.push(lowered);
1601            }
1602        }
1603    }
1604
1605    keywords
1606}
1607
1608fn profile_search_terms_for_event(event: &Event) -> Vec<String> {
1609    let profile = match serde_json::from_str::<serde_json::Value>(&event.content) {
1610        Ok(serde_json::Value::Object(profile)) => profile,
1611        _ => serde_json::Map::new(),
1612    };
1613    let names = extract_profile_names(&profile);
1614    let primary_name = names.first().map(String::as_str);
1615    let mut parts = Vec::new();
1616    if let Some(name) = primary_name {
1617        parts.push(name.to_string());
1618    }
1619    if let Some(nip05) = normalize_profile_nip05(&profile, primary_name) {
1620        parts.push(nip05);
1621    }
1622    parts.push(event.pubkey.to_hex());
1623    if names.len() > 1 {
1624        parts.extend(names.into_iter().skip(1));
1625    }
1626    parse_search_keywords(&parts.join(" "))
1627}
1628
1629fn compare_nostr_events(left: &Event, right: &Event) -> std::cmp::Ordering {
1630    left.created_at
1631        .as_u64()
1632        .cmp(&right.created_at.as_u64())
1633        .then_with(|| left.id.to_hex().cmp(&right.id.to_hex()))
1634}
1635
1636fn map_event_store_error(err: NostrEventStoreError) -> anyhow::Error {
1637    anyhow::anyhow!("nostr event store error: {err}")
1638}
1639
1640fn ensure_social_graph_mapsize(db_dir: &Path, requested_bytes: u64) -> Result<()> {
1641    let requested = requested_bytes.max(DEFAULT_SOCIALGRAPH_MAP_SIZE_BYTES);
1642    let page_size = page_size_bytes() as u64;
1643    let rounded = requested
1644        .checked_add(page_size.saturating_sub(1))
1645        .map(|size| size / page_size * page_size)
1646        .unwrap_or(requested);
1647    let map_size = usize::try_from(rounded).context("social graph mapsize exceeds usize")?;
1648
1649    let env = unsafe {
1650        heed::EnvOpenOptions::new()
1651            .map_size(DEFAULT_SOCIALGRAPH_MAP_SIZE_BYTES as usize)
1652            .max_dbs(SOCIALGRAPH_MAX_DBS)
1653            .open(db_dir)
1654    }
1655    .context("open social graph LMDB env for resize")?;
1656    if env.info().map_size < map_size {
1657        unsafe { env.resize(map_size) }.context("resize social graph LMDB env")?;
1658    }
1659
1660    Ok(())
1661}
1662
1663fn page_size_bytes() -> usize {
1664    page_size::get_granularity()
1665}
1666
1667#[cfg(test)]
1668mod tests;