iroh_dns_server/
server.rs

1//! The main server which combines the DNS and HTTP(S) servers.
2use std::sync::Arc;
3#[cfg(test)]
4use std::{net::SocketAddr, path::Path};
5
6use iroh_metrics::service::start_metrics_server;
7use n0_error::{Result, StdResultExt};
8use tracing::info;
9#[cfg(test)]
10use url::Url;
11
12#[cfg(test)]
13use crate::http::HttpsConfig;
14use crate::{
15    config::Config,
16    dns::{DnsHandler, DnsServer},
17    http::HttpServer,
18    metrics::Metrics,
19    state::AppState,
20    store::ZoneStore,
21};
22
23/// Spawn the server and run until the `Ctrl-C` signal is received, then shutdown.
24pub async fn run_with_config_until_ctrl_c(config: Config) -> Result<()> {
25    let metrics = Arc::new(Metrics::default());
26    let zone_store_options = config.zone_store.clone().unwrap_or_default();
27    let mut store = ZoneStore::persistent(
28        config.signed_packet_store_path()?,
29        zone_store_options.into(),
30        metrics.clone(),
31    )?;
32    if let Some(bootstrap) = config.mainline_enabled() {
33        info!("mainline fallback enabled");
34        store = store.with_mainline_fallback(bootstrap);
35    };
36    let server = Server::spawn(config, store, metrics).await?;
37    tokio::signal::ctrl_c().await.anyerr()?;
38    info!("shutdown");
39    server.shutdown().await?;
40    Ok(())
41}
42
43/// The iroh-dns server.
44pub struct Server {
45    http_server: HttpServer,
46    dns_server: DnsServer,
47    metrics_task: tokio::task::JoinHandle<Result<()>>,
48}
49
50impl Server {
51    /// Spawn the server.
52    ///
53    /// This will spawn several background tasks:
54    /// * A DNS server task
55    /// * A HTTP server task, if `config.http` is not empty
56    /// * A HTTPS server task, if `config.https` is not empty
57    pub async fn spawn(config: Config, store: ZoneStore, metrics: Arc<Metrics>) -> Result<Self> {
58        let cert_cache_dir = config.data_dir()?.join("cert_cache");
59        let dns_handler = DnsHandler::new(store.clone(), &config.dns, metrics.clone())?;
60
61        let state = AppState {
62            store,
63            dns_handler,
64            metrics: metrics.clone(),
65        };
66
67        let metrics_addr = config.metrics_addr();
68        let metrics_task = tokio::task::spawn(async move {
69            if let Some(addr) = metrics_addr {
70                let mut registry = iroh_metrics::Registry::default();
71                registry.register(metrics);
72                start_metrics_server(addr, Arc::new(registry))
73                    .await
74                    .anyerr()?;
75            }
76            Ok(())
77        });
78        let http_server = HttpServer::spawn(
79            config.http,
80            config.https,
81            config.pkarr_put_rate_limit,
82            state.clone(),
83            cert_cache_dir,
84        )
85        .await?;
86        let dns_server = DnsServer::spawn(config.dns, state.dns_handler.clone()).await?;
87        Ok(Self {
88            http_server,
89            dns_server,
90            metrics_task,
91        })
92    }
93
94    /// Cancel the server tasks and wait for all tasks to complete.
95    pub async fn shutdown(self) -> Result<()> {
96        self.metrics_task.abort();
97        let (res1, res2) = tokio::join!(self.dns_server.shutdown(), self.http_server.shutdown(),);
98        res1?;
99        res2?;
100        Ok(())
101    }
102
103    /// Wait for all tasks to complete.
104    ///
105    /// This will run forever unless all tasks close with an error, or `Self::cancel` is called.
106    pub async fn run_until_error(self) -> Result<()> {
107        tokio::select! {
108            res = self.dns_server.run_until_done() => res?,
109            res = self.http_server.run_until_done() => res?,
110        }
111        self.metrics_task.abort();
112        Ok(())
113    }
114
115    /// Spawn a server suitable for testing.
116    ///
117    /// This will run the DNS and HTTP servers, but not the HTTPS server.
118    ///
119    /// It returns the server handle, the [`SocketAddr`] of the DNS server and the [`Url`] of the
120    /// HTTP server.
121    #[cfg(test)]
122    pub async fn spawn_for_tests(dir: impl AsRef<Path>) -> Result<Self> {
123        Self::spawn_for_tests_with_options(dir, None, None, None).await
124    }
125
126    /// Spawn a server suitable for testing, while optionally enabling mainline with custom
127    /// bootstrap addresses.
128    #[cfg(test)]
129    pub async fn spawn_for_tests_with_options(
130        dir: impl AsRef<Path>,
131        mainline: Option<crate::config::BootstrapOption>,
132        options: Option<crate::store::ZoneStoreOptions>,
133        https: Option<HttpsConfig>,
134    ) -> Result<Self> {
135        use std::net::{IpAddr, Ipv4Addr};
136
137        use crate::config::MetricsConfig;
138
139        let mut config = Config::default();
140        config.dns.port = 0;
141        config.dns.bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
142        config.http.as_mut().unwrap().port = 0;
143        config.http.as_mut().unwrap().bind_addr = Some(IpAddr::V4(Ipv4Addr::LOCALHOST));
144        config.https = https;
145        config.metrics = Some(MetricsConfig::disabled());
146        config.data_dir = Some(dir.as_ref().to_owned());
147
148        let mut store = ZoneStore::in_memory(options.unwrap_or_default(), Default::default())?;
149        if let Some(bootstrap) = mainline {
150            info!("mainline fallback enabled");
151            store = store.with_mainline_fallback(bootstrap);
152        }
153        let server = Self::spawn(config, store, Default::default()).await?;
154        Ok(server)
155    }
156
157    #[cfg(test)]
158    pub(crate) fn dns_addr(&self) -> SocketAddr {
159        self.dns_server.local_addr()
160    }
161
162    #[cfg(test)]
163    pub(crate) fn http_url(&self) -> Option<Url> {
164        let http_addr = self.http_server.http_addr()?;
165        Some(
166            format!("http://{http_addr}")
167                .parse::<url::Url>()
168                .expect("valid url"),
169        )
170    }
171
172    #[cfg(test)]
173    pub(crate) fn https_url(&self) -> Option<Url> {
174        let https_addr = self.https_addr()?;
175        Some(
176            format!("https://{https_addr}")
177                .parse::<url::Url>()
178                .expect("valid url"),
179        )
180    }
181
182    #[cfg(test)]
183    pub(crate) fn https_addr(&self) -> Option<SocketAddr> {
184        self.http_server.https_addr()
185    }
186}