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