Skip to main content

hashtree_cli/
daemon.rs

1use anyhow::{Context, Result};
2use axum::Router;
3use hashtree_core::Cid;
4use nostr::nips::nip19::ToBech32;
5use nostr::Keys;
6use std::collections::HashSet;
7use std::path::PathBuf;
8use std::sync::Arc;
9use tokio::net::TcpListener;
10use tokio::sync::{Mutex, Notify};
11use tokio::task::JoinHandle;
12use tower_http::cors::CorsLayer;
13
14use crate::config::{ensure_keys, ensure_keys_in, parse_npub, pubkey_bytes, Config};
15use crate::eviction::{spawn_background_eviction_task, BACKGROUND_EVICTION_INTERVAL};
16use crate::nostr_relay::{NostrRelay, NostrRelayConfig};
17use crate::server::{AppState, HashtreeServer};
18use crate::socialgraph;
19use crate::storage::HashtreeStore;
20
21struct BackgroundSyncRuntime {
22    service: Arc<crate::sync::BackgroundSync>,
23    join: Option<JoinHandle<()>>,
24}
25
26impl Drop for BackgroundSyncRuntime {
27    fn drop(&mut self) {
28        self.service.shutdown();
29        if let Some(join) = self.join.take() {
30            join.abort();
31        }
32    }
33}
34
35struct BackgroundMirrorRuntime {
36    service: Arc<crate::nostr_mirror::BackgroundNostrMirror>,
37    join: Option<JoinHandle<()>>,
38}
39
40impl Drop for BackgroundMirrorRuntime {
41    fn drop(&mut self) {
42        self.service.shutdown();
43        if let Some(join) = self.join.take() {
44            join.abort();
45        }
46    }
47}
48
49struct BackgroundServicesRuntime {
50    crawler: Option<socialgraph::crawler::SocialGraphTaskHandles>,
51    mirror: Option<BackgroundMirrorRuntime>,
52    sync: Option<BackgroundSyncRuntime>,
53}
54
55impl Drop for BackgroundServicesRuntime {
56    fn drop(&mut self) {
57        if let Some(handles) = self.crawler.as_ref() {
58            let _ = handles.shutdown_tx.send(true);
59        }
60        if let Some(runtime) = self.mirror.as_ref() {
61            runtime.service.shutdown();
62        }
63        if let Some(runtime) = self.sync.as_ref() {
64            runtime.service.shutdown();
65        }
66    }
67}
68
69impl BackgroundServicesRuntime {
70    fn status(&self) -> EmbeddedBackgroundServicesStatus {
71        EmbeddedBackgroundServicesStatus {
72            crawler_active: self.crawler.is_some(),
73            mirror_active: self.mirror.is_some(),
74            sync_active: self.sync.is_some(),
75        }
76    }
77}
78
79struct EmbeddedServerRuntime {
80    shutdown: Arc<Notify>,
81    join: Option<JoinHandle<()>>,
82}
83
84pub struct EmbeddedServerController {
85    runtime: Mutex<Option<EmbeddedServerRuntime>>,
86}
87
88impl EmbeddedServerController {
89    pub fn new(shutdown: Arc<Notify>, join: JoinHandle<()>) -> Self {
90        Self {
91            runtime: Mutex::new(Some(EmbeddedServerRuntime {
92                shutdown,
93                join: Some(join),
94            })),
95        }
96    }
97
98    pub async fn shutdown(&self) {
99        let mut runtime = self.runtime.lock().await;
100        let Some(mut runtime) = runtime.take() else {
101            return;
102        };
103
104        runtime.shutdown.notify_waiters();
105        if let Some(mut join) = runtime.join.take() {
106            match tokio::time::timeout(std::time::Duration::from_secs(3), &mut join).await {
107                Ok(Ok(())) => {}
108                Ok(Err(err)) => {
109                    tracing::warn!("Embedded server task ended with join error: {}", err)
110                }
111                Err(_) => {
112                    tracing::warn!("Timed out waiting for embedded server shutdown");
113                    join.abort();
114                }
115            }
116        }
117    }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub struct EmbeddedBackgroundServicesStatus {
122    pub crawler_active: bool,
123    pub mirror_active: bool,
124    pub sync_active: bool,
125}
126
127pub struct EmbeddedBackgroundServicesController {
128    keys: Keys,
129    data_dir: PathBuf,
130    store: Arc<HashtreeStore>,
131    graph_store_concrete: Arc<socialgraph::SocialGraphStore>,
132    graph_store: Arc<dyn socialgraph::SocialGraphBackend>,
133    spambox: Option<Arc<dyn socialgraph::SocialGraphBackend>>,
134    runtime: Mutex<BackgroundServicesRuntime>,
135}
136
137impl EmbeddedBackgroundServicesController {
138    const MIRROR_PUBLISH_RELAY_PRIORITY: &[&str] = &[
139        "wss://nos.lol",
140        "wss://temp.iris.to",
141        "wss://vault.iris.to",
142        "wss://relay.damus.io",
143    ];
144    const MIRROR_PUBLISH_RELAY_BLOCKLIST: &[&str] =
145        &["wss://graph-relay.iris.to", "wss://upload.iris.to/nostr"];
146
147    fn mirror_publish_relays(active_relays: &[String], _bind_address: &str) -> Vec<String> {
148        let mut seen = HashSet::new();
149        let active_relays = active_relays
150            .iter()
151            .filter(|relay| seen.insert((*relay).clone()))
152            .cloned()
153            .collect::<Vec<_>>();
154        if active_relays.is_empty() {
155            return Vec::new();
156        }
157        let filtered = active_relays
158            .iter()
159            .filter(|relay| !Self::MIRROR_PUBLISH_RELAY_BLOCKLIST.contains(&relay.as_str()))
160            .cloned()
161            .collect::<Vec<_>>();
162        if filtered.is_empty() {
163            return active_relays;
164        }
165
166        let mut selected = Vec::new();
167        let mut selected_set = HashSet::new();
168        for relay in Self::MIRROR_PUBLISH_RELAY_PRIORITY {
169            if filtered.iter().any(|active| active == relay) {
170                selected.push((*relay).to_string());
171                selected_set.insert((*relay).to_string());
172            }
173        }
174        for relay in filtered {
175            if selected_set.insert(relay.clone()) {
176                selected.push(relay);
177            }
178        }
179
180        selected
181    }
182
183    pub fn new(
184        keys: Keys,
185        data_dir: PathBuf,
186        store: Arc<HashtreeStore>,
187        graph_store_concrete: Arc<socialgraph::SocialGraphStore>,
188        graph_store: Arc<dyn socialgraph::SocialGraphBackend>,
189        spambox: Option<Arc<dyn socialgraph::SocialGraphBackend>>,
190    ) -> Self {
191        Self {
192            keys,
193            data_dir,
194            store,
195            graph_store_concrete,
196            graph_store,
197            spambox,
198            runtime: Mutex::new(BackgroundServicesRuntime {
199                crawler: None,
200                mirror: None,
201                sync: None,
202            }),
203        }
204    }
205
206    pub async fn status(&self) -> EmbeddedBackgroundServicesStatus {
207        self.runtime.lock().await.status()
208    }
209
210    pub async fn shutdown(&self) {
211        let mut runtime = self.runtime.lock().await;
212        Self::shutdown_crawler(&mut runtime.crawler).await;
213        Self::shutdown_mirror(&mut runtime.mirror).await;
214        Self::shutdown_sync(&mut runtime.sync).await;
215    }
216
217    async fn shutdown_crawler(crawler: &mut Option<socialgraph::crawler::SocialGraphTaskHandles>) {
218        let Some(handles) = crawler.take() else {
219            return;
220        };
221
222        let _ = handles.shutdown_tx.send(true);
223
224        let mut crawl_handle = handles.crawl_handle;
225        match tokio::time::timeout(std::time::Duration::from_secs(3), &mut crawl_handle).await {
226            Ok(Ok(())) => {}
227            Ok(Err(err)) => tracing::warn!("Crawler task ended with join error: {}", err),
228            Err(_) => {
229                tracing::warn!("Timed out waiting for crawler task shutdown");
230                crawl_handle.abort();
231            }
232        }
233
234        let mut local_list_handle = handles.local_list_handle;
235        match tokio::time::timeout(std::time::Duration::from_secs(3), &mut local_list_handle).await
236        {
237            Ok(Ok(())) => {}
238            Ok(Err(err)) => tracing::warn!("Local list task ended with join error: {}", err),
239            Err(_) => {
240                tracing::warn!("Timed out waiting for local list task shutdown");
241                local_list_handle.abort();
242            }
243        }
244    }
245
246    async fn shutdown_sync(sync: &mut Option<BackgroundSyncRuntime>) {
247        let Some(mut runtime) = sync.take() else {
248            return;
249        };
250
251        runtime.service.shutdown();
252        if let Some(mut join) = runtime.join.take() {
253            match tokio::time::timeout(std::time::Duration::from_secs(3), &mut join).await {
254                Ok(Ok(())) => {}
255                Ok(Err(err)) => {
256                    tracing::warn!("Background sync task ended with join error: {}", err)
257                }
258                Err(_) => {
259                    tracing::warn!("Timed out waiting for background sync shutdown");
260                    join.abort();
261                }
262            }
263        }
264    }
265
266    async fn shutdown_mirror(mirror: &mut Option<BackgroundMirrorRuntime>) {
267        let Some(mut runtime) = mirror.take() else {
268            return;
269        };
270
271        runtime.service.shutdown();
272        if let Some(mut join) = runtime.join.take() {
273            match tokio::time::timeout(std::time::Duration::from_secs(3), &mut join).await {
274                Ok(Ok(())) => {}
275                Ok(Err(err)) => {
276                    tracing::warn!("Background mirror task ended with join error: {}", err)
277                }
278                Err(_) => {
279                    tracing::warn!("Timed out waiting for background mirror shutdown");
280                    join.abort();
281                }
282            }
283        }
284    }
285
286    fn nostr_mirror_config(
287        config: &Config,
288        active_relays: &[String],
289    ) -> crate::nostr_mirror::NostrMirrorConfig {
290        crate::nostr_mirror::NostrMirrorConfig {
291            relays: active_relays.to_vec(),
292            publish_relays: Self::mirror_publish_relays(active_relays, &config.server.bind_address),
293            blossom_write_servers: config.blossom.all_write_servers(),
294            max_follow_distance: config
295                .nostr
296                .mirror_max_follow_distance
297                .unwrap_or(config.nostr.social_graph_crawl_depth),
298            overmute_threshold: config.nostr.overmute_threshold,
299            require_negentropy: config.nostr.negentropy_only,
300            kinds: config.nostr.mirror_kinds.clone(),
301            history_sync_author_chunk_size: config.nostr.history_sync_author_chunk_size.max(1),
302            history_sync_per_author_event_limit: config
303                .nostr
304                .history_sync_per_author_event_limit
305                .max(1),
306            missing_profile_backfill_batch_size: config.nostr.history_sync_author_chunk_size.max(1),
307            history_sync_on_reconnect: config.nostr.history_sync_on_reconnect,
308            full_text_note_history_follow_distance: config
309                .nostr
310                .full_text_note_history_follow_distance,
311            full_text_note_history_max_relay_pages: config
312                .nostr
313                .full_text_note_history_max_relay_pages,
314            archive_history_follow_distance: config.nostr.archive_history_follow_distance,
315            archive_history_max_relay_pages: config.nostr.archive_history_max_relay_pages,
316            ..crate::nostr_mirror::NostrMirrorConfig::default()
317        }
318    }
319
320    pub async fn apply_config(&self, config: &Config) -> Result<EmbeddedBackgroundServicesStatus> {
321        let mut runtime = self.runtime.lock().await;
322
323        Self::shutdown_crawler(&mut runtime.crawler).await;
324        Self::shutdown_mirror(&mut runtime.mirror).await;
325        Self::shutdown_sync(&mut runtime.sync).await;
326
327        if !config.server.mode.background_services_enabled() {
328            return Ok(runtime.status());
329        }
330
331        let active_relays = config.nostr.active_relays();
332
333        if config.nostr.enabled
334            && config.nostr.social_graph_crawl_depth > 0
335            && !active_relays.is_empty()
336        {
337            runtime.crawler = Some(socialgraph::crawler::spawn_social_graph_tasks(
338                self.graph_store.clone(),
339                self.keys.clone(),
340                active_relays.clone(),
341                config.nostr.social_graph_crawl_depth,
342                self.spambox.clone(),
343                self.data_dir.clone(),
344            ));
345
346            let service = Arc::new(
347                crate::nostr_mirror::BackgroundNostrMirror::new(
348                    Self::nostr_mirror_config(config, &active_relays),
349                    self.store.clone(),
350                    self.graph_store_concrete.clone(),
351                    Some(
352                        nostr_sdk::Keys::parse(&self.keys.secret_key().to_bech32()?)
353                            .context("Failed to parse keys for background nostr mirror")?,
354                    ),
355                )
356                .await
357                .context("Failed to create background nostr mirror")?,
358            );
359            let service_for_task = service.clone();
360            let join = tokio::task::spawn_blocking(move || {
361                let runtime = tokio::runtime::Builder::new_current_thread()
362                    .enable_all()
363                    .build()
364                    .expect("build background nostr mirror runtime");
365                runtime.block_on(async {
366                    if let Err(err) = service_for_task.run().await {
367                        tracing::error!("Background nostr mirror error: {:#}", err);
368                    }
369                });
370            });
371            runtime.mirror = Some(BackgroundMirrorRuntime {
372                service,
373                join: Some(join),
374            });
375        }
376
377        if config.sync.enabled && !active_relays.is_empty() {
378            let has_pinned_refs = self
379                .store
380                .list_pinned_refs()
381                .map(|refs| !refs.is_empty())
382                .unwrap_or(false);
383            let has_tracked_authors = self
384                .store
385                .list_tracked_authors()
386                .map(|authors| !authors.is_empty())
387                .unwrap_or(false);
388            let should_sync = config.sync.sync_own
389                || config.sync.sync_followed
390                || has_pinned_refs
391                || has_tracked_authors;
392            if !should_sync {
393                return Ok(runtime.status());
394            }
395
396            let sync_config = crate::sync::SyncConfig {
397                sync_own: config.sync.sync_own,
398                sync_followed: config.sync.sync_followed,
399                relays: active_relays,
400                max_concurrent: config.sync.max_concurrent,
401                blossom_timeout_ms: config.sync.blossom_timeout_ms,
402            };
403
404            let sync_keys = nostr_sdk::Keys::parse(&self.keys.secret_key().to_bech32()?)
405                .context("Failed to parse keys for sync")?;
406            let service = Arc::new(
407                crate::sync::BackgroundSync::new(sync_config, self.store.clone(), sync_keys)
408                    .await
409                    .context("Failed to create background sync service")?,
410            );
411            let contacts_file = self.data_dir.join("contacts.json");
412            let service_for_task = service.clone();
413            let join = tokio::spawn(async move {
414                if let Err(err) = service_for_task.run(contacts_file).await {
415                    tracing::error!("Background sync error: {}", err);
416                }
417            });
418            runtime.sync = Some(BackgroundSyncRuntime {
419                service,
420                join: Some(join),
421            });
422        }
423
424        Ok(runtime.status())
425    }
426}
427
428pub struct EmbeddedDaemonController {
429    server_controller: Arc<EmbeddedServerController>,
430    fips_handle: Option<Arc<crate::fips_transport::DaemonFipsHandle>>,
431    #[cfg(feature = "experimental-decentralized-pubsub")]
432    nostr_pubsub_handle: Option<Arc<crate::fips_transport::DaemonNostrPubsubHandle>>,
433    background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
434}
435
436impl EmbeddedDaemonController {
437    pub fn new(
438        server_controller: Arc<EmbeddedServerController>,
439        fips_handle: Option<Arc<crate::fips_transport::DaemonFipsHandle>>,
440        #[cfg(feature = "experimental-decentralized-pubsub")] nostr_pubsub_handle: Option<
441            Arc<crate::fips_transport::DaemonNostrPubsubHandle>,
442        >,
443        background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
444    ) -> Self {
445        Self {
446            server_controller,
447            fips_handle,
448            #[cfg(feature = "experimental-decentralized-pubsub")]
449            nostr_pubsub_handle,
450            background_services_controller,
451        }
452    }
453
454    pub async fn shutdown(&self) {
455        self.server_controller.shutdown().await;
456        #[cfg(feature = "experimental-decentralized-pubsub")]
457        if let Some(handle) = self.nostr_pubsub_handle.as_ref() {
458            handle.shutdown();
459        }
460        if let Some(handle) = self.fips_handle.as_ref() {
461            handle.shutdown().await;
462        }
463        if let Some(controller) = self.background_services_controller.as_ref() {
464            controller.shutdown().await;
465        }
466    }
467}
468
469pub struct EmbeddedDaemonOptions {
470    pub config: Config,
471    pub data_dir: PathBuf,
472    pub config_dir: Option<PathBuf>,
473    pub bind_address: String,
474    pub relays: Option<Vec<String>>,
475    pub initial_tree_roots: Vec<(String, Cid)>,
476    pub extra_routes: Option<Router<AppState>>,
477    pub cors: Option<CorsLayer>,
478}
479
480pub struct EmbeddedDaemonInfo {
481    pub addr: String,
482    pub port: u16,
483    pub npub: String,
484    pub store: Arc<HashtreeStore>,
485    pub daemon_controller: Arc<EmbeddedDaemonController>,
486    #[allow(dead_code)]
487    pub background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
488}
489
490pub async fn start_embedded(opts: EmbeddedDaemonOptions) -> Result<EmbeddedDaemonInfo> {
491    let _ = rustls::crypto::ring::default_provider().install_default();
492
493    let mut config = opts.config;
494    config.server.bind_address = opts.bind_address.clone();
495    if let Some(relays) = opts.relays {
496        config.nostr.relays = relays;
497        config.nostr.enabled = embedded_nostr_enabled_after_relay_override(&config);
498    }
499
500    let max_size_bytes = config.storage.max_size_gb * 1024 * 1024 * 1024;
501    let nostr_db_max_bytes = config
502        .nostr
503        .db_max_size_gb
504        .saturating_mul(1024 * 1024 * 1024);
505    let spambox_db_max_bytes = config
506        .nostr
507        .spambox_max_size_gb
508        .saturating_mul(1024 * 1024 * 1024);
509
510    let store = Arc::new(HashtreeStore::with_embedded_options(
511        &opts.data_dir,
512        config.storage.s3.as_ref(),
513        max_size_bytes,
514    )?);
515
516    let (keys, _was_generated) = if let Some(config_dir) = opts.config_dir.as_ref() {
517        ensure_keys_in(config_dir, Some(&opts.data_dir), Some(&config))?
518    } else {
519        ensure_keys()?
520    };
521    let pk_bytes = pubkey_bytes(&keys);
522    let npub = keys
523        .public_key()
524        .to_bech32()
525        .context("Failed to encode npub")?;
526
527    let mut allowed_pubkeys: HashSet<String> = HashSet::new();
528    allowed_pubkeys.insert(hex::encode(pk_bytes));
529    for npub_str in &config.nostr.allowed_npubs {
530        if let Ok(pk) = parse_npub(npub_str) {
531            allowed_pubkeys.insert(hex::encode(pk));
532        } else {
533            tracing::warn!("Invalid npub in allowed_npubs: {}", npub_str);
534        }
535    }
536
537    let graph_store = socialgraph::open_embedded_social_graph_store_with_storage(
538        &opts.data_dir,
539        store.store_arc(),
540        Some(nostr_db_max_bytes),
541    )
542    .context("Failed to initialize social graph store")?;
543    graph_store.set_profile_index_overmute_threshold(config.nostr.overmute_threshold);
544
545    let social_graph_root_bytes = if let Some(ref root_npub) = config.nostr.socialgraph_root {
546        parse_npub(root_npub).unwrap_or(pk_bytes)
547    } else {
548        pk_bytes
549    };
550    socialgraph::set_social_graph_root(&graph_store, &social_graph_root_bytes);
551    socialgraph::sync_local_list_files_force(graph_store.as_ref(), &opts.data_dir, &keys)
552        .context("Failed to sync local social graph lists")?;
553    let fips_peer_ids = crate::fips_transport::fips_peer_ids_from_pubkeys(
554        socialgraph::get_follows(graph_store.as_ref(), &pk_bytes),
555    );
556    let social_graph_store: Arc<dyn socialgraph::SocialGraphBackend> = graph_store.clone();
557
558    let social_graph = Arc::new(socialgraph::SocialGraphAccessControl::new(
559        Arc::clone(&social_graph_store),
560        config.nostr.max_write_distance,
561        allowed_pubkeys.clone(),
562    ));
563
564    let nostr_relay_config = NostrRelayConfig {
565        spambox_db_max_bytes,
566        ..Default::default()
567    };
568    let nostr_relay = if config.nostr.enabled {
569        let mut public_event_pubkeys = HashSet::new();
570        public_event_pubkeys.insert(hex::encode(pk_bytes));
571        Some(Arc::new(
572            NostrRelay::new(
573                Arc::clone(&social_graph_store),
574                opts.data_dir.clone(),
575                public_event_pubkeys,
576                Some(social_graph.clone()),
577                nostr_relay_config,
578            )
579            .map(|relay| {
580                relay.with_historical_nostr_index(store.store_arc(), opts.data_dir.clone())
581            })
582            .context("Failed to initialize Nostr relay")?,
583        ))
584    } else {
585        None
586    };
587
588    let crawler_spambox = if config.nostr.enabled && spambox_db_max_bytes != 0 {
589        let spam_dir = opts.data_dir.join("socialgraph_spambox");
590        match socialgraph::open_embedded_social_graph_store_at_path(
591            &spam_dir,
592            Some(spambox_db_max_bytes),
593        ) {
594            Ok(store) => Some(store),
595            Err(err) => {
596                tracing::warn!("Failed to open social graph spambox for crawler: {}", err);
597                None
598            }
599        }
600    } else {
601        None
602    };
603    let crawler_spambox_backend = crawler_spambox
604        .clone()
605        .map(|store| store as Arc<dyn socialgraph::SocialGraphBackend>);
606
607    let background_services_controller = Arc::new(EmbeddedBackgroundServicesController::new(
608        keys.clone(),
609        opts.data_dir.clone(),
610        Arc::clone(&store),
611        graph_store.clone(),
612        Arc::clone(&social_graph_store),
613        crawler_spambox_backend,
614    ));
615
616    let upstream_blossom = config.blossom.upstream_read_servers(&opts.bind_address);
617    let blossom_replica_queue_bytes = crate::server::bounded_upload_queue_bytes(
618        config
619            .blossom
620            .replicate_queue_mb
621            .saturating_mul(1024 * 1024),
622    );
623    let active_nostr_relays = config.nostr.active_relays();
624    let fips_handle = crate::fips_transport::start_daemon_fips_transport(
625        &config,
626        &keys,
627        Arc::clone(&store),
628        fips_peer_ids,
629    )
630    .await?
631    .map(Arc::new);
632    let nostr_provider =
633        crate::fips_transport::start_daemon_nostr_provider(&config, fips_handle.as_deref()).await?;
634    #[cfg(feature = "experimental-decentralized-pubsub")]
635    let nostr_pubsub_handle = crate::fips_transport::start_daemon_nostr_pubsub(
636        &config,
637        fips_handle.as_deref(),
638        nostr_relay.clone(),
639    )
640    .await?;
641
642    let mut server = HashtreeServer::new(Arc::clone(&store), opts.bind_address.clone())
643        .with_server_mode(config.server.mode)
644        .with_hash_get_enabled(config.server.mode.hash_get_enabled())
645        .with_fetch_from_fips_peers(config.server.fetch_from_fips_peers)
646        .with_allowed_pubkeys(allowed_pubkeys.clone())
647        .with_max_upload_bytes((config.blossom.max_upload_mb as usize) * 1024 * 1024)
648        .with_public_writes(config.server.public_writes)
649        .with_public_plaintext_reads(config.server.public_plaintext_reads)
650        .with_require_random_untrusted_ingest(config.blossom.require_random_untrusted_ingest)
651        .with_optimistic_blossom_uploads(config.blossom.optimistic_uploads)
652        .with_upstream_blossom(upstream_blossom)
653        .with_blossom_upload_replicas(
654            config.blossom.replicate_servers.clone(),
655            blossom_replica_queue_bytes,
656            keys.clone(),
657        )
658        .with_nostr_relay_urls(active_nostr_relays)
659        .with_cached_tree_roots(opts.initial_tree_roots)
660        .with_social_graph(social_graph)
661        .with_socialgraph_snapshot(
662            Arc::clone(&social_graph_store),
663            social_graph_root_bytes,
664            config.server.socialgraph_snapshot_public,
665        );
666    if let Some(nostr_relay) = nostr_relay {
667        server = server.with_nostr_relay(nostr_relay);
668    }
669    if let Some(provider) = nostr_provider {
670        server = server.with_nostr_provider(provider);
671    }
672
673    if let Some(ref fips_handle) = fips_handle {
674        server = server
675            .with_fips_endpoint(fips_handle.endpoint.clone())
676            .with_fips_blob_resolver(fips_handle.blob_resolver.clone());
677    }
678
679    if let Some(extra) = opts.extra_routes {
680        server = server.with_extra_routes(extra);
681    }
682    if let Some(cors) = opts.cors {
683        server = server.with_cors(cors);
684    }
685
686    spawn_background_eviction_task(
687        Arc::clone(&store),
688        BACKGROUND_EVICTION_INTERVAL,
689        "embedded daemon",
690    );
691
692    let listener = TcpListener::bind(&opts.bind_address).await?;
693    let local_addr = listener.local_addr()?;
694    let actual_addr = format!("{}:{}", local_addr.ip(), local_addr.port());
695
696    let server_shutdown = Arc::new(Notify::new());
697    let server_shutdown_for_task = Arc::clone(&server_shutdown);
698    let server_join = tokio::spawn(async move {
699        if let Err(e) = server
700            .run_with_listener_until(listener, async move {
701                server_shutdown_for_task.notified().await;
702            })
703            .await
704        {
705            tracing::error!("Embedded daemon server error: {}", e);
706        }
707    });
708    let server_controller = Arc::new(EmbeddedServerController::new(server_shutdown, server_join));
709    background_services_controller.apply_config(&config).await?;
710    let daemon_controller = Arc::new(EmbeddedDaemonController::new(
711        server_controller,
712        fips_handle.clone(),
713        #[cfg(feature = "experimental-decentralized-pubsub")]
714        nostr_pubsub_handle.clone(),
715        Some(background_services_controller.clone()),
716    ));
717
718    tracing::info!(
719        "Embedded daemon started on {}, identity {}",
720        actual_addr,
721        npub
722    );
723
724    Ok(EmbeddedDaemonInfo {
725        addr: actual_addr,
726        port: local_addr.port(),
727        npub,
728        store,
729        daemon_controller,
730        background_services_controller: Some(background_services_controller),
731    })
732}
733
734fn embedded_nostr_enabled_after_relay_override(config: &Config) -> bool {
735    config.nostr.decentralized_pubsub || !config.nostr.relays.is_empty()
736}
737
738#[cfg(test)]
739mod tests {
740    use super::{
741        embedded_nostr_enabled_after_relay_override, EmbeddedBackgroundServicesController,
742    };
743    use crate::config::Config;
744
745    #[test]
746    fn mirror_publish_relays_orders_known_root_publish_relays_first() {
747        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
748            &[
749                "wss://graph-relay.iris.to".to_string(),
750                "wss://relay.example".to_string(),
751                "wss://relay.primal.net".to_string(),
752                "wss://relay.damus.io".to_string(),
753                "wss://temp.iris.to".to_string(),
754                "wss://vault.iris.to".to_string(),
755                "wss://upload.iris.to/nostr".to_string(),
756            ],
757            "0.0.0.0:8080",
758        );
759        assert_eq!(
760            relays,
761            vec![
762                "wss://temp.iris.to".to_string(),
763                "wss://vault.iris.to".to_string(),
764                "wss://relay.damus.io".to_string(),
765                "wss://relay.example".to_string(),
766                "wss://relay.primal.net".to_string(),
767            ]
768        );
769    }
770
771    #[test]
772    fn mirror_publish_relays_do_not_add_non_active_publish_targets() {
773        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
774            &[
775                "wss://graph-relay.iris.to".to_string(),
776                "wss://relay.example".to_string(),
777            ],
778            "0.0.0.0:8080",
779        );
780        assert_eq!(relays, vec!["wss://relay.example".to_string()]);
781    }
782
783    #[test]
784    fn mirror_publish_relays_falls_back_to_active_relays_when_all_are_blocklisted() {
785        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
786            &[
787                "wss://graph-relay.iris.to".to_string(),
788                "wss://upload.iris.to/nostr".to_string(),
789            ],
790            "0.0.0.0:8080",
791        );
792        assert_eq!(
793            relays,
794            vec![
795                "wss://graph-relay.iris.to".to_string(),
796                "wss://upload.iris.to/nostr".to_string(),
797            ]
798        );
799    }
800
801    #[test]
802    fn nostr_mirror_config_maps_legacy_and_complete_archive_settings() {
803        let mut config = Config::default();
804        config.nostr.full_text_note_history_max_relay_pages = 0;
805        config.nostr.archive_history_follow_distance = None;
806        config.nostr.archive_history_max_relay_pages = 0;
807
808        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
809            &config,
810            &["wss://relay.example".to_string()],
811        );
812
813        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 0);
814        assert_eq!(mirror_config.archive_history_follow_distance, None);
815        assert_eq!(mirror_config.archive_history_max_relay_pages, 0);
816
817        config.nostr.full_text_note_history_max_relay_pages = 64;
818        config.nostr.archive_history_follow_distance = Some(1);
819        config.nostr.archive_history_max_relay_pages = 32;
820        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
821            &config,
822            &["wss://relay.example".to_string()],
823        );
824
825        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 64);
826        assert_eq!(mirror_config.archive_history_follow_distance, Some(1));
827        assert_eq!(mirror_config.archive_history_max_relay_pages, 32);
828    }
829
830    #[test]
831    fn nostr_mirror_config_can_limit_mirror_distance_independently() {
832        let mut config = Config::default();
833        config.nostr.social_graph_crawl_depth = 6;
834        config.nostr.mirror_max_follow_distance = Some(2);
835
836        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
837            &config,
838            &["wss://relay.example".to_string()],
839        );
840
841        assert_eq!(mirror_config.max_follow_distance, 2);
842
843        config.nostr.mirror_max_follow_distance = None;
844        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
845            &config,
846            &["wss://relay.example".to_string()],
847        );
848
849        assert_eq!(mirror_config.max_follow_distance, 6);
850    }
851
852    #[test]
853    fn embedded_empty_relays_keep_nostr_enabled_for_decentralized_pubsub() {
854        let mut config = Config::default();
855        config.nostr.relays = Vec::new();
856        config.nostr.decentralized_pubsub = false;
857        assert!(!embedded_nostr_enabled_after_relay_override(&config));
858
859        config.nostr.decentralized_pubsub = true;
860        assert!(embedded_nostr_enabled_after_relay_override(&config));
861
862        config.nostr.decentralized_pubsub = false;
863        config.nostr.relays = vec!["wss://relay.example".to_string()];
864        assert!(embedded_nostr_enabled_after_relay_override(&config));
865    }
866}