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_cache = crate::fips_transport::new_daemon_nostr_cache(store.store_arc());
633    let nostr_provider = crate::fips_transport::start_daemon_nostr_provider(
634        &config,
635        fips_handle.as_deref(),
636        Some(Arc::clone(&nostr_cache)),
637    )
638    .await?;
639    #[cfg(feature = "experimental-decentralized-pubsub")]
640    let nostr_pubsub_handle = crate::fips_transport::start_daemon_nostr_pubsub(
641        &config,
642        fips_handle.as_deref(),
643        nostr_relay.clone(),
644        nostr_cache,
645    )
646    .await?;
647
648    let mut server = HashtreeServer::new(Arc::clone(&store), opts.bind_address.clone())
649        .with_server_mode(config.server.mode)
650        .with_hash_get_enabled(config.server.mode.hash_get_enabled())
651        .with_fetch_from_fips_peers(config.server.fetch_from_fips_peers)
652        .with_allowed_pubkeys(allowed_pubkeys.clone())
653        .with_max_upload_bytes((config.blossom.max_upload_mb as usize) * 1024 * 1024)
654        .with_public_writes(config.server.public_writes)
655        .with_public_plaintext_reads(config.server.public_plaintext_reads)
656        .with_require_random_untrusted_ingest(config.blossom.require_random_untrusted_ingest)
657        .with_optimistic_blossom_uploads(config.blossom.optimistic_uploads)
658        .with_upstream_blossom(upstream_blossom)
659        .with_blossom_upload_replicas(
660            config.blossom.replicate_servers.clone(),
661            blossom_replica_queue_bytes,
662            keys.clone(),
663        )
664        .with_nostr_relay_urls(active_nostr_relays)
665        .with_cached_tree_roots(opts.initial_tree_roots)
666        .with_social_graph(social_graph)
667        .with_socialgraph_snapshot(
668            Arc::clone(&social_graph_store),
669            social_graph_root_bytes,
670            config.server.socialgraph_snapshot_public,
671        );
672    if let Some(nostr_relay) = nostr_relay {
673        server = server.with_nostr_relay(nostr_relay);
674    }
675    if let Some(provider) = nostr_provider {
676        server = server.with_nostr_provider(provider);
677    }
678
679    if let Some(ref fips_handle) = fips_handle {
680        server = server
681            .with_fips_endpoint(fips_handle.endpoint.clone())
682            .with_fips_blob_resolver(fips_handle.blob_resolver.clone());
683    }
684
685    if let Some(extra) = opts.extra_routes {
686        server = server.with_extra_routes(extra);
687    }
688    if let Some(cors) = opts.cors {
689        server = server.with_cors(cors);
690    }
691
692    spawn_background_eviction_task(
693        Arc::clone(&store),
694        BACKGROUND_EVICTION_INTERVAL,
695        "embedded daemon",
696    );
697
698    let listener = TcpListener::bind(&opts.bind_address).await?;
699    let local_addr = listener.local_addr()?;
700    let actual_addr = format!("{}:{}", local_addr.ip(), local_addr.port());
701
702    let server_shutdown = Arc::new(Notify::new());
703    let server_shutdown_for_task = Arc::clone(&server_shutdown);
704    let server_join = tokio::spawn(async move {
705        if let Err(e) = server
706            .run_with_listener_until(listener, async move {
707                server_shutdown_for_task.notified().await;
708            })
709            .await
710        {
711            tracing::error!("Embedded daemon server error: {}", e);
712        }
713    });
714    let server_controller = Arc::new(EmbeddedServerController::new(server_shutdown, server_join));
715    background_services_controller.apply_config(&config).await?;
716    let daemon_controller = Arc::new(EmbeddedDaemonController::new(
717        server_controller,
718        fips_handle.clone(),
719        #[cfg(feature = "experimental-decentralized-pubsub")]
720        nostr_pubsub_handle.clone(),
721        Some(background_services_controller.clone()),
722    ));
723
724    tracing::info!(
725        "Embedded daemon started on {}, identity {}",
726        actual_addr,
727        npub
728    );
729
730    Ok(EmbeddedDaemonInfo {
731        addr: actual_addr,
732        port: local_addr.port(),
733        npub,
734        store,
735        daemon_controller,
736        background_services_controller: Some(background_services_controller),
737    })
738}
739
740fn embedded_nostr_enabled_after_relay_override(config: &Config) -> bool {
741    config.nostr.decentralized_pubsub || !config.nostr.relays.is_empty()
742}
743
744#[cfg(test)]
745mod tests {
746    use super::{
747        embedded_nostr_enabled_after_relay_override, EmbeddedBackgroundServicesController,
748    };
749    use crate::config::Config;
750
751    #[test]
752    fn mirror_publish_relays_orders_known_root_publish_relays_first() {
753        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
754            &[
755                "wss://graph-relay.iris.to".to_string(),
756                "wss://relay.example".to_string(),
757                "wss://relay.primal.net".to_string(),
758                "wss://relay.damus.io".to_string(),
759                "wss://temp.iris.to".to_string(),
760                "wss://vault.iris.to".to_string(),
761                "wss://upload.iris.to/nostr".to_string(),
762            ],
763            "0.0.0.0:8080",
764        );
765        assert_eq!(
766            relays,
767            vec![
768                "wss://temp.iris.to".to_string(),
769                "wss://vault.iris.to".to_string(),
770                "wss://relay.damus.io".to_string(),
771                "wss://relay.example".to_string(),
772                "wss://relay.primal.net".to_string(),
773            ]
774        );
775    }
776
777    #[test]
778    fn mirror_publish_relays_do_not_add_non_active_publish_targets() {
779        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
780            &[
781                "wss://graph-relay.iris.to".to_string(),
782                "wss://relay.example".to_string(),
783            ],
784            "0.0.0.0:8080",
785        );
786        assert_eq!(relays, vec!["wss://relay.example".to_string()]);
787    }
788
789    #[test]
790    fn mirror_publish_relays_falls_back_to_active_relays_when_all_are_blocklisted() {
791        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
792            &[
793                "wss://graph-relay.iris.to".to_string(),
794                "wss://upload.iris.to/nostr".to_string(),
795            ],
796            "0.0.0.0:8080",
797        );
798        assert_eq!(
799            relays,
800            vec![
801                "wss://graph-relay.iris.to".to_string(),
802                "wss://upload.iris.to/nostr".to_string(),
803            ]
804        );
805    }
806
807    #[test]
808    fn nostr_mirror_config_maps_legacy_and_complete_archive_settings() {
809        let mut config = Config::default();
810        config.nostr.full_text_note_history_max_relay_pages = 0;
811        config.nostr.archive_history_follow_distance = None;
812        config.nostr.archive_history_max_relay_pages = 0;
813
814        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
815            &config,
816            &["wss://relay.example".to_string()],
817        );
818
819        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 0);
820        assert_eq!(mirror_config.archive_history_follow_distance, None);
821        assert_eq!(mirror_config.archive_history_max_relay_pages, 0);
822
823        config.nostr.full_text_note_history_max_relay_pages = 64;
824        config.nostr.archive_history_follow_distance = Some(1);
825        config.nostr.archive_history_max_relay_pages = 32;
826        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
827            &config,
828            &["wss://relay.example".to_string()],
829        );
830
831        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 64);
832        assert_eq!(mirror_config.archive_history_follow_distance, Some(1));
833        assert_eq!(mirror_config.archive_history_max_relay_pages, 32);
834    }
835
836    #[test]
837    fn nostr_mirror_config_can_limit_mirror_distance_independently() {
838        let mut config = Config::default();
839        config.nostr.social_graph_crawl_depth = 6;
840        config.nostr.mirror_max_follow_distance = Some(2);
841
842        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
843            &config,
844            &["wss://relay.example".to_string()],
845        );
846
847        assert_eq!(mirror_config.max_follow_distance, 2);
848
849        config.nostr.mirror_max_follow_distance = None;
850        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
851            &config,
852            &["wss://relay.example".to_string()],
853        );
854
855        assert_eq!(mirror_config.max_follow_distance, 6);
856    }
857
858    #[test]
859    fn embedded_empty_relays_keep_nostr_enabled_for_decentralized_pubsub() {
860        let mut config = Config::default();
861        config.nostr.relays = Vec::new();
862        config.nostr.decentralized_pubsub = false;
863        assert!(!embedded_nostr_enabled_after_relay_override(&config));
864
865        config.nostr.decentralized_pubsub = true;
866        assert!(embedded_nostr_enabled_after_relay_override(&config));
867
868        config.nostr.decentralized_pubsub = false;
869        config.nostr.relays = vec!["wss://relay.example".to_string()];
870        assert!(embedded_nostr_enabled_after_relay_override(&config));
871    }
872}