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 self.store.is_pool_audit_read_only() {
328            tracing::warn!(
329                "Pool audit-serving read-only mode: embedded crawler, mirror, and sync remain stopped"
330            );
331            return Ok(runtime.status());
332        }
333
334        if !config.server.mode.background_services_enabled() {
335            return Ok(runtime.status());
336        }
337
338        let active_relays = config.nostr.active_relays();
339
340        if config.nostr.enabled
341            && config.nostr.social_graph_crawl_depth > 0
342            && !active_relays.is_empty()
343        {
344            runtime.crawler = Some(socialgraph::crawler::spawn_social_graph_tasks(
345                self.graph_store.clone(),
346                self.keys.clone(),
347                active_relays.clone(),
348                config.nostr.social_graph_crawl_depth,
349                self.spambox.clone(),
350                self.data_dir.clone(),
351            ));
352
353            let service = Arc::new(
354                crate::nostr_mirror::BackgroundNostrMirror::new(
355                    Self::nostr_mirror_config(config, &active_relays),
356                    self.store.clone(),
357                    self.graph_store_concrete.clone(),
358                    Some(
359                        nostr_sdk::Keys::parse(&self.keys.secret_key().to_bech32()?)
360                            .context("Failed to parse keys for background nostr mirror")?,
361                    ),
362                )
363                .await
364                .context("Failed to create background nostr mirror")?,
365            );
366            let service_for_task = service.clone();
367            let join = tokio::task::spawn_blocking(move || {
368                let runtime = tokio::runtime::Builder::new_current_thread()
369                    .enable_all()
370                    .build()
371                    .expect("build background nostr mirror runtime");
372                runtime.block_on(async {
373                    if let Err(err) = service_for_task.run().await {
374                        tracing::error!("Background nostr mirror error: {:#}", err);
375                    }
376                });
377            });
378            runtime.mirror = Some(BackgroundMirrorRuntime {
379                service,
380                join: Some(join),
381            });
382        }
383
384        if config.sync.enabled && !active_relays.is_empty() {
385            let has_pinned_refs = self
386                .store
387                .list_pinned_refs()
388                .map(|refs| !refs.is_empty())
389                .unwrap_or(false);
390            let has_tracked_authors = self
391                .store
392                .list_tracked_authors()
393                .map(|authors| !authors.is_empty())
394                .unwrap_or(false);
395            let should_sync = config.sync.sync_own
396                || config.sync.sync_followed
397                || has_pinned_refs
398                || has_tracked_authors;
399            if !should_sync {
400                return Ok(runtime.status());
401            }
402
403            let sync_config = crate::sync::SyncConfig {
404                sync_own: config.sync.sync_own,
405                sync_followed: config.sync.sync_followed,
406                relays: active_relays,
407                max_concurrent: config.sync.max_concurrent,
408                blossom_timeout_ms: config.sync.blossom_timeout_ms,
409            };
410
411            let sync_keys = nostr_sdk::Keys::parse(&self.keys.secret_key().to_bech32()?)
412                .context("Failed to parse keys for sync")?;
413            let service = Arc::new(
414                crate::sync::BackgroundSync::new(sync_config, self.store.clone(), sync_keys)
415                    .await
416                    .context("Failed to create background sync service")?,
417            );
418            let contacts_file = self.data_dir.join("contacts.json");
419            let service_for_task = service.clone();
420            let join = tokio::spawn(async move {
421                if let Err(err) = service_for_task.run(contacts_file).await {
422                    tracing::error!("Background sync error: {}", err);
423                }
424            });
425            runtime.sync = Some(BackgroundSyncRuntime {
426                service,
427                join: Some(join),
428            });
429        }
430
431        Ok(runtime.status())
432    }
433}
434
435pub struct EmbeddedDaemonController {
436    server_controller: Arc<EmbeddedServerController>,
437    fips_handle: Option<Arc<crate::fips_transport::DaemonFipsHandle>>,
438    #[cfg(feature = "experimental-decentralized-pubsub")]
439    nostr_pubsub_handle: Option<Arc<crate::fips_transport::DaemonNostrPubsubHandle>>,
440    background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
441}
442
443impl EmbeddedDaemonController {
444    pub fn new(
445        server_controller: Arc<EmbeddedServerController>,
446        fips_handle: Option<Arc<crate::fips_transport::DaemonFipsHandle>>,
447        #[cfg(feature = "experimental-decentralized-pubsub")] nostr_pubsub_handle: Option<
448            Arc<crate::fips_transport::DaemonNostrPubsubHandle>,
449        >,
450        background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
451    ) -> Self {
452        Self {
453            server_controller,
454            fips_handle,
455            #[cfg(feature = "experimental-decentralized-pubsub")]
456            nostr_pubsub_handle,
457            background_services_controller,
458        }
459    }
460
461    pub async fn shutdown(&self) {
462        self.server_controller.shutdown().await;
463        #[cfg(feature = "experimental-decentralized-pubsub")]
464        if let Some(handle) = self.nostr_pubsub_handle.as_ref() {
465            handle.shutdown();
466        }
467        if let Some(handle) = self.fips_handle.as_ref() {
468            handle.shutdown().await;
469        }
470        if let Some(controller) = self.background_services_controller.as_ref() {
471            controller.shutdown().await;
472        }
473    }
474}
475
476pub struct EmbeddedDaemonOptions {
477    pub config: Config,
478    pub data_dir: PathBuf,
479    pub config_dir: Option<PathBuf>,
480    pub bind_address: String,
481    pub relays: Option<Vec<String>>,
482    pub initial_tree_roots: Vec<(String, Cid)>,
483    pub extra_routes: Option<Router<AppState>>,
484    pub cors: Option<CorsLayer>,
485}
486
487pub struct EmbeddedDaemonInfo {
488    pub addr: String,
489    pub port: u16,
490    pub npub: String,
491    pub store: Arc<HashtreeStore>,
492    pub daemon_controller: Arc<EmbeddedDaemonController>,
493    #[allow(dead_code)]
494    pub background_services_controller: Option<Arc<EmbeddedBackgroundServicesController>>,
495}
496
497pub async fn start_embedded(opts: EmbeddedDaemonOptions) -> Result<EmbeddedDaemonInfo> {
498    let _ = rustls::crypto::ring::default_provider().install_default();
499
500    let mut config = opts.config;
501    config.server.bind_address = opts.bind_address.clone();
502    if let Some(relays) = opts.relays {
503        config.nostr.relays = relays;
504        config.nostr.enabled = embedded_nostr_enabled_after_relay_override(&config);
505    }
506
507    let max_size_bytes = config.storage.max_size_gb * 1024 * 1024 * 1024;
508    let nostr_db_max_bytes = config
509        .nostr
510        .db_max_size_gb
511        .saturating_mul(1024 * 1024 * 1024);
512    let spambox_db_max_bytes = config
513        .nostr
514        .spambox_max_size_gb
515        .saturating_mul(1024 * 1024 * 1024);
516
517    let store = Arc::new(HashtreeStore::with_embedded_options(
518        &opts.data_dir,
519        config.storage.s3.as_ref(),
520        max_size_bytes,
521    )?);
522
523    let (keys, _was_generated) = if let Some(config_dir) = opts.config_dir.as_ref() {
524        ensure_keys_in(config_dir, Some(&opts.data_dir), Some(&config))?
525    } else {
526        ensure_keys()?
527    };
528    let pk_bytes = pubkey_bytes(&keys);
529    let npub = keys
530        .public_key()
531        .to_bech32()
532        .context("Failed to encode npub")?;
533
534    let mut allowed_pubkeys: HashSet<String> = HashSet::new();
535    allowed_pubkeys.insert(hex::encode(pk_bytes));
536    for npub_str in &config.nostr.allowed_npubs {
537        if let Ok(pk) = parse_npub(npub_str) {
538            allowed_pubkeys.insert(hex::encode(pk));
539        } else {
540            tracing::warn!("Invalid npub in allowed_npubs: {}", npub_str);
541        }
542    }
543
544    let social_graph_root_bytes = if let Some(ref root_npub) = config.nostr.socialgraph_root {
545        parse_npub(root_npub).unwrap_or(pk_bytes)
546    } else {
547        pk_bytes
548    };
549    let nostr_relay_config = NostrRelayConfig {
550        spambox_db_max_bytes,
551        ..Default::default()
552    };
553    let pool_audit_read_only = store.is_pool_audit_read_only();
554    let graph_store;
555    let social_graph_store;
556    let social_graph;
557    let fips_peer_ids;
558    let nostr_relay;
559    let crawler_spambox_backend;
560    if pool_audit_read_only {
561        tracing::warn!(
562            "Pool audit-serving read-only mode: embedded social graph and durable Nostr relay writers remain unopened"
563        );
564        graph_store = None;
565        social_graph_store = None;
566        social_graph = None;
567        fips_peer_ids = Vec::new();
568        nostr_relay = config.nostr.enabled.then(|| {
569            Arc::new(NostrRelay::new_read_only(
570                opts.data_dir.clone(),
571                nostr_relay_config,
572            ))
573        });
574        crawler_spambox_backend = None;
575    } else {
576        let opened_graph_store = socialgraph::open_embedded_social_graph_store_with_storage(
577            &opts.data_dir,
578            store.store_arc(),
579            Some(nostr_db_max_bytes),
580        )
581        .context("Failed to initialize social graph store")?;
582        opened_graph_store.set_profile_index_overmute_threshold(config.nostr.overmute_threshold);
583        socialgraph::set_social_graph_root(&opened_graph_store, &social_graph_root_bytes);
584        socialgraph::sync_local_list_files_force(
585            opened_graph_store.as_ref(),
586            &opts.data_dir,
587            &keys,
588        )
589        .context("Failed to sync local social graph lists")?;
590        fips_peer_ids = crate::fips_transport::fips_peer_ids_from_pubkeys(
591            socialgraph::get_follows(opened_graph_store.as_ref(), &pk_bytes),
592        );
593        let opened_social_graph_store: Arc<dyn socialgraph::SocialGraphBackend> =
594            opened_graph_store.clone();
595        let opened_social_graph = Arc::new(socialgraph::SocialGraphAccessControl::new(
596            Arc::clone(&opened_social_graph_store),
597            config.nostr.max_write_distance,
598            allowed_pubkeys.clone(),
599        ));
600        nostr_relay = if config.nostr.enabled {
601            let mut public_event_pubkeys = HashSet::new();
602            public_event_pubkeys.insert(hex::encode(pk_bytes));
603            Some(Arc::new(
604                NostrRelay::new(
605                    Arc::clone(&opened_social_graph_store),
606                    opts.data_dir.clone(),
607                    public_event_pubkeys,
608                    Some(opened_social_graph.clone()),
609                    nostr_relay_config,
610                )
611                .map(|relay| {
612                    relay.with_historical_nostr_index(store.store_arc(), opts.data_dir.clone())
613                })
614                .context("Failed to initialize Nostr relay")?,
615            ))
616        } else {
617            None
618        };
619        let crawler_spambox = if config.nostr.enabled && spambox_db_max_bytes != 0 {
620            let spam_dir = opts.data_dir.join("socialgraph_spambox");
621            match socialgraph::open_embedded_social_graph_store_at_path(
622                &spam_dir,
623                Some(spambox_db_max_bytes),
624            ) {
625                Ok(store) => Some(store),
626                Err(err) => {
627                    tracing::warn!("Failed to open social graph spambox for crawler: {}", err);
628                    None
629                }
630            }
631        } else {
632            None
633        };
634        crawler_spambox_backend =
635            crawler_spambox.map(|store| store as Arc<dyn socialgraph::SocialGraphBackend>);
636        graph_store = Some(opened_graph_store);
637        social_graph_store = Some(opened_social_graph_store);
638        social_graph = Some(opened_social_graph);
639    }
640    let background_services_controller = match (graph_store, social_graph_store.as_ref()) {
641        (Some(graph_store), Some(social_graph_store)) => {
642            Some(Arc::new(EmbeddedBackgroundServicesController::new(
643                keys.clone(),
644                opts.data_dir.clone(),
645                Arc::clone(&store),
646                graph_store,
647                Arc::clone(social_graph_store),
648                crawler_spambox_backend,
649            )))
650        }
651        _ => None,
652    };
653
654    let upstream_blossom = config.blossom.upstream_read_servers(&opts.bind_address);
655    let blossom_replica_queue_bytes = crate::server::bounded_upload_queue_bytes(
656        config
657            .blossom
658            .replicate_queue_mb
659            .saturating_mul(1024 * 1024),
660    );
661    let active_nostr_relays = config.nostr.active_relays();
662    let fips_handle = crate::fips_transport::start_daemon_fips_transport(
663        &config,
664        &keys,
665        Arc::clone(&store),
666        fips_peer_ids,
667    )
668    .await?
669    .map(Arc::new);
670    let nostr_cache = crate::fips_transport::new_daemon_nostr_cache(store.store_arc());
671    let nostr_provider = crate::fips_transport::start_daemon_nostr_provider(
672        &config,
673        fips_handle.as_deref(),
674        Some(Arc::clone(&nostr_cache)),
675    )
676    .await?;
677    #[cfg(feature = "experimental-decentralized-pubsub")]
678    let nostr_pubsub_handle = crate::fips_transport::start_daemon_nostr_pubsub(
679        &config,
680        fips_handle.as_deref(),
681        nostr_relay.clone(),
682        nostr_cache,
683    )
684    .await?;
685
686    let mut server = HashtreeServer::new(Arc::clone(&store), opts.bind_address.clone())
687        .with_server_mode(config.server.mode)
688        .with_hash_get_enabled(config.server.mode.hash_get_enabled())
689        .with_fetch_from_fips_peers(config.server.fetch_from_fips_peers)
690        .with_allowed_pubkeys(allowed_pubkeys.clone())
691        .with_max_upload_bytes((config.blossom.max_upload_mb as usize) * 1024 * 1024)
692        .with_public_writes(config.server.public_writes)
693        .with_public_plaintext_reads(config.server.public_plaintext_reads)
694        .with_require_random_untrusted_ingest(config.blossom.require_random_untrusted_ingest)
695        .with_optimistic_blossom_uploads(config.blossom.optimistic_uploads)
696        .with_upstream_blossom(upstream_blossom)
697        .with_blossom_upload_replicas(
698            config.blossom.replicate_servers.clone(),
699            blossom_replica_queue_bytes,
700            keys.clone(),
701        )
702        .with_nostr_relay_urls(active_nostr_relays)
703        .with_cached_tree_roots(opts.initial_tree_roots);
704    if let Some(social_graph) = social_graph {
705        server = server.with_social_graph(social_graph);
706    }
707    if let Some(social_graph_store) = social_graph_store.as_ref() {
708        server = server.with_socialgraph_snapshot(
709            Arc::clone(social_graph_store),
710            social_graph_root_bytes,
711            config.server.socialgraph_snapshot_public,
712        );
713    }
714    if let Some(nostr_relay) = nostr_relay {
715        server = server.with_nostr_relay(nostr_relay);
716    }
717    if let Some(provider) = nostr_provider {
718        server = server.with_nostr_provider(provider);
719    }
720
721    if let Some(ref fips_handle) = fips_handle {
722        server = server
723            .with_fips_endpoint(fips_handle.endpoint.clone())
724            .with_fips_blob_resolver(fips_handle.blob_resolver.clone());
725    }
726
727    if let Some(extra) = opts.extra_routes {
728        server = server.with_extra_routes(extra);
729    }
730    if let Some(cors) = opts.cors {
731        server = server.with_cors(cors);
732    }
733
734    if store.is_pool_audit_read_only() {
735        tracing::warn!(
736            "Pool audit-serving read-only mode: embedded background eviction remains stopped"
737        );
738    } else {
739        spawn_background_eviction_task(
740            Arc::clone(&store),
741            BACKGROUND_EVICTION_INTERVAL,
742            "embedded daemon",
743        );
744    }
745
746    let listener = TcpListener::bind(&opts.bind_address).await?;
747    let local_addr = listener.local_addr()?;
748    let actual_addr = format!("{}:{}", local_addr.ip(), local_addr.port());
749
750    let server_shutdown = Arc::new(Notify::new());
751    let server_shutdown_for_task = Arc::clone(&server_shutdown);
752    let server_join = tokio::spawn(async move {
753        if let Err(e) = server
754            .run_with_listener_until(listener, async move {
755                server_shutdown_for_task.notified().await;
756            })
757            .await
758        {
759            tracing::error!("Embedded daemon server error: {}", e);
760        }
761    });
762    let server_controller = Arc::new(EmbeddedServerController::new(server_shutdown, server_join));
763    if let Some(controller) = background_services_controller.as_ref() {
764        controller.apply_config(&config).await?;
765    }
766    let daemon_controller = Arc::new(EmbeddedDaemonController::new(
767        server_controller,
768        fips_handle.clone(),
769        #[cfg(feature = "experimental-decentralized-pubsub")]
770        nostr_pubsub_handle.clone(),
771        background_services_controller.clone(),
772    ));
773
774    tracing::info!(
775        "Embedded daemon started on {}, identity {}",
776        actual_addr,
777        npub
778    );
779
780    Ok(EmbeddedDaemonInfo {
781        addr: actual_addr,
782        port: local_addr.port(),
783        npub,
784        store,
785        daemon_controller,
786        background_services_controller,
787    })
788}
789
790fn embedded_nostr_enabled_after_relay_override(config: &Config) -> bool {
791    config.nostr.decentralized_pubsub || !config.nostr.relays.is_empty()
792}
793
794#[cfg(test)]
795mod tests {
796    use super::{
797        embedded_nostr_enabled_after_relay_override, EmbeddedBackgroundServicesController,
798    };
799    use crate::config::Config;
800
801    #[test]
802    fn mirror_publish_relays_orders_known_root_publish_relays_first() {
803        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
804            &[
805                "wss://graph-relay.iris.to".to_string(),
806                "wss://relay.example".to_string(),
807                "wss://relay.primal.net".to_string(),
808                "wss://relay.damus.io".to_string(),
809                "wss://temp.iris.to".to_string(),
810                "wss://vault.iris.to".to_string(),
811                "wss://upload.iris.to/nostr".to_string(),
812            ],
813            "0.0.0.0:8080",
814        );
815        assert_eq!(
816            relays,
817            vec![
818                "wss://temp.iris.to".to_string(),
819                "wss://vault.iris.to".to_string(),
820                "wss://relay.damus.io".to_string(),
821                "wss://relay.example".to_string(),
822                "wss://relay.primal.net".to_string(),
823            ]
824        );
825    }
826
827    #[test]
828    fn mirror_publish_relays_do_not_add_non_active_publish_targets() {
829        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
830            &[
831                "wss://graph-relay.iris.to".to_string(),
832                "wss://relay.example".to_string(),
833            ],
834            "0.0.0.0:8080",
835        );
836        assert_eq!(relays, vec!["wss://relay.example".to_string()]);
837    }
838
839    #[test]
840    fn mirror_publish_relays_falls_back_to_active_relays_when_all_are_blocklisted() {
841        let relays = EmbeddedBackgroundServicesController::mirror_publish_relays(
842            &[
843                "wss://graph-relay.iris.to".to_string(),
844                "wss://upload.iris.to/nostr".to_string(),
845            ],
846            "0.0.0.0:8080",
847        );
848        assert_eq!(
849            relays,
850            vec![
851                "wss://graph-relay.iris.to".to_string(),
852                "wss://upload.iris.to/nostr".to_string(),
853            ]
854        );
855    }
856
857    #[test]
858    fn nostr_mirror_config_maps_legacy_and_complete_archive_settings() {
859        let mut config = Config::default();
860        config.nostr.full_text_note_history_max_relay_pages = 0;
861        config.nostr.archive_history_follow_distance = None;
862        config.nostr.archive_history_max_relay_pages = 0;
863
864        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
865            &config,
866            &["wss://relay.example".to_string()],
867        );
868
869        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 0);
870        assert_eq!(mirror_config.archive_history_follow_distance, None);
871        assert_eq!(mirror_config.archive_history_max_relay_pages, 0);
872
873        config.nostr.full_text_note_history_max_relay_pages = 64;
874        config.nostr.archive_history_follow_distance = Some(1);
875        config.nostr.archive_history_max_relay_pages = 32;
876        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
877            &config,
878            &["wss://relay.example".to_string()],
879        );
880
881        assert_eq!(mirror_config.full_text_note_history_max_relay_pages, 64);
882        assert_eq!(mirror_config.archive_history_follow_distance, Some(1));
883        assert_eq!(mirror_config.archive_history_max_relay_pages, 32);
884    }
885
886    #[test]
887    fn nostr_mirror_config_can_limit_mirror_distance_independently() {
888        let mut config = Config::default();
889        config.nostr.social_graph_crawl_depth = 6;
890        config.nostr.mirror_max_follow_distance = Some(2);
891
892        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
893            &config,
894            &["wss://relay.example".to_string()],
895        );
896
897        assert_eq!(mirror_config.max_follow_distance, 2);
898
899        config.nostr.mirror_max_follow_distance = None;
900        let mirror_config = EmbeddedBackgroundServicesController::nostr_mirror_config(
901            &config,
902            &["wss://relay.example".to_string()],
903        );
904
905        assert_eq!(mirror_config.max_follow_distance, 6);
906    }
907
908    #[test]
909    fn embedded_empty_relays_keep_nostr_enabled_for_decentralized_pubsub() {
910        let mut config = Config::default();
911        config.nostr.relays = Vec::new();
912        config.nostr.decentralized_pubsub = false;
913        assert!(!embedded_nostr_enabled_after_relay_override(&config));
914
915        config.nostr.decentralized_pubsub = true;
916        assert!(embedded_nostr_enabled_after_relay_override(&config));
917
918        config.nostr.decentralized_pubsub = false;
919        config.nostr.relays = vec!["wss://relay.example".to_string()];
920        assert!(embedded_nostr_enabled_after_relay_override(&config));
921    }
922}