1use std::future::Future;
10use std::net::SocketAddr;
11use std::path::Path;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::task::Poll;
15use std::time::Duration;
16
17use anyhow::Context;
18use async_trait::async_trait;
19use rings_core::chunk::ReassemblyLimits;
20use rings_core::utils::get_epoch_ms;
21use rings_gateway::GatewayStatusHandle;
22use tokio::task::JoinError;
23use tokio::task::JoinSet;
24
25use crate::dns_relay;
26use crate::dns_relay::ServiceOffer;
27use crate::dns_relay::ServicesConfig;
28use crate::extension::protocols::relay::RelayHandle;
29use crate::measure::EvidenceCollectorIdentity;
30use crate::measure::PeriodicMeasure;
31use crate::native::api_auth::load_or_create_api_token;
32use crate::native::api_auth::ApiSecurity;
33use crate::native::bootstrap::BootstrapSupervisor;
34use crate::native::bootstrap::BootstrapTargets;
35use crate::native::config;
36use crate::native::endpoint::run_external_api;
37use crate::native::endpoint::run_internal_api_with_gateway;
38use crate::native::gateway::NativeGatewayRunner;
39use crate::native::horizon::run_signing_horizon;
40use crate::native::horizon::DelegationRenewalPaths;
41use crate::native::stores::NodeStores;
42use crate::onion::proxy::http::run_onion_http_proxy;
43use crate::onion::proxy::http::OnionHttpProxyOptions;
44use crate::prelude::StopSource;
45use crate::prelude::StopToken;
46use crate::processor::Processor;
47use crate::processor::ProcessorBuilder;
48use crate::processor::ProcessorConfig;
49use crate::provider::Provider;
50
51pub const FOREGROUND_CLEANUP_TIMEOUT: Duration = Duration::from_secs(30);
54
55#[derive(Clone, Debug)]
57pub struct NativeNodeRunOptions {
58 pub config_path: String,
60 pub config: config::Config,
62 pub storage_path: Option<String>,
64 pub storage_capacity: Option<u32>,
66 pub reassembly_limits: ReassemblyLimits,
68 pub api_token_path_override: Option<String>,
70 pub api_allowed_origins_override: Vec<String>,
72 pub allow_remote_external_api_override: bool,
74}
75
76impl NativeNodeRunOptions {
77 pub fn new(config_path: impl Into<String>, config: config::Config) -> Self {
79 Self {
80 config_path: config_path.into(),
81 config,
82 storage_path: None,
83 storage_capacity: None,
84 reassembly_limits: ReassemblyLimits::default(),
85 api_token_path_override: None,
86 api_allowed_origins_override: Vec::new(),
87 allow_remote_external_api_override: false,
88 }
89 }
90}
91
92#[async_trait]
96pub trait NativeDaemonHooks: Send + 'static {
97 fn configure_builder(&mut self, builder: ProcessorBuilder) -> anyhow::Result<ProcessorBuilder> {
100 Ok(builder)
101 }
102
103 async fn configure_provider(&mut self, _provider: &Arc<Provider>) -> anyhow::Result<()> {
106 Ok(())
107 }
108
109 async fn shutdown(&mut self) -> anyhow::Result<()> {
112 Ok(())
113 }
114}
115
116impl NativeDaemonHooks for () {}
117
118pub async fn run_foreground_node<H: NativeDaemonHooks>(
120 options: NativeNodeRunOptions,
121 mut hooks: H,
122) -> anyhow::Result<()> {
123 let mut c = options.config;
124 let pc = ProcessorConfig::try_from(c.clone())?;
125 let api_security = configure_api_security(
126 &options.config_path,
127 &mut c,
128 options.api_token_path_override,
129 options.api_allowed_origins_override,
130 options.allow_remote_external_api_override,
131 )?;
132 let onion_http_proxy = onion_http_proxy_options(&c)?;
133 let (data_storage, measure_storage) =
134 run_storage_configs(options.storage_path, options.storage_capacity, &c);
135 let service_offer = c.services.as_ref().map(ServicesConfig::offer).transpose()?;
136 let processor = build_processor(
137 &pc,
138 data_storage,
139 measure_storage,
140 options.reassembly_limits,
141 service_offer,
142 &mut hooks,
143 )
144 .await?;
145 println!("Did: {}", processor.swarm.did());
146 let provider = Arc::new(Provider::from_processor(processor.clone()));
147 hooks.configure_provider(&provider).await?;
148 let relay = RelayHandle::install(&provider.extensions())?;
151 let (services, relaying) = (c.services.as_ref(), c.dns_relay.as_ref());
152 let dns_relay = dns_relay::open(services, relaying, &processor, &relay).await?;
153 let needs_onion_runtime = processor.onion_role().registers_relay()
154 || c.enabled_gateway().is_some()
155 || onion_http_proxy.is_some();
156 let onion = needs_onion_runtime
157 .then(|| provider.onion_circuit())
158 .transpose()?;
159 let gateway_runner = match (c.enabled_gateway().cloned(), onion.as_ref()) {
160 (Some(config), Some(onion)) => Some(NativeGatewayRunner::new(
161 processor.clone(),
162 onion.clone(),
163 config,
164 )?),
165 _ => None,
166 };
167 let gateway_status = gateway_runner
168 .as_ref()
169 .map(NativeGatewayRunner::status_handle);
170 let renewal = DelegationRenewalPaths::from_config(&c)?;
173 let bootstrap_targets = BootstrapTargets::from_config(c.bootstrap, processor.did())?;
174 let bootstrap = BootstrapSupervisor::over_processor(bootstrap_targets, processor.clone());
175 let stop = StopSource::new();
176 let application = provider.application_service(
180 bootstrap.as_ref().map(BootstrapSupervisor::observer),
181 stop.token(),
182 )?;
183 let gateway_configured = gateway_runner.is_some();
184 let gateway_task = start_gateway(gateway_runner, stop.token()).await?;
185
186 let mut tasks = JoinSet::new();
187 tasks.spawn(serve_application(application, stop.token()));
188 let horizon_processor = processor.clone();
191 tasks.spawn(async move {
192 Err(
193 run_signing_horizon(horizon_processor, renewal, get_epoch_ms)
194 .await
195 .into(),
196 )
197 });
198 let processor_task = spawn_processor(processor.clone(), stop.token());
199 spawn_apis(
200 &mut tasks,
201 c.internal_api_port,
202 c.external_api_addr,
203 processor.clone(),
204 gateway_status,
205 api_security,
206 );
207 if let Some(supervisor) = bootstrap {
208 let bootstrap_stop = stop.token();
209 tasks.spawn(async move {
210 supervisor.run(bootstrap_stop).await;
212 Ok(())
213 });
214 }
215 if let Some(dns_relay) = dns_relay {
216 let dns_relay_stop = stop.token();
217 tasks.spawn(async move {
218 dns_relay
219 .run(dns_relay_stop.stopped())
220 .await
221 .context("DNS relay stopped")
222 });
223 }
224 match (onion_http_proxy, onion) {
225 (Some(proxy_options), Some(onion)) => {
226 let proxy_processor = processor.clone();
227 tasks.spawn(async move {
228 run_onion_http_proxy(proxy_options, proxy_processor, onion)
229 .await
230 .context("Onion HTTP proxy stopped")
231 });
232 }
233 (_, onion) => drop(onion),
234 }
235 drop((relay, provider));
236 await_foreground_exit(
237 stop,
238 tasks,
239 gateway_task,
240 processor_task,
241 processor,
242 gateway_configured,
243 &mut hooks,
244 )
245 .await
246}
247
248async fn serve_application(
251 service: impl Future<Output = ()>,
252 stop: StopToken,
253) -> anyhow::Result<()> {
254 service.await;
255 if stop.should_stop() {
256 Ok(())
257 } else {
258 anyhow::bail!("application inbox closed unexpectedly")
259 }
260}
261
262fn run_storage_configs(
264 storage_path: Option<String>,
265 storage_capacity: Option<u32>,
266 c: &config::Config,
267) -> (config::StorageConfig, config::StorageConfig) {
268 let Some(storage_path) = storage_path else {
269 return (c.data_storage.clone(), c.measure_storage.clone());
270 };
271 let storage_path = Path::new(&storage_path);
272 let data_path = storage_path.join("data").to_string_lossy().to_string();
273 let measure_path = storage_path.join("measure").to_string_lossy().to_string();
274 let capacity = storage_capacity.unwrap_or(config::DEFAULT_STORAGE_CAPACITY);
275 (
276 config::StorageConfig::new(&data_path, capacity),
277 config::StorageConfig::new(&measure_path, capacity),
278 )
279}
280
281async fn build_processor<H: NativeDaemonHooks>(
284 pc: &ProcessorConfig,
285 data_storage: config::StorageConfig,
286 measure_storage: config::StorageConfig,
287 reassembly_limits: ReassemblyLimits,
288 service_offer: Option<ServiceOffer>,
289 hooks: &mut H,
290) -> anyhow::Result<Arc<Processor>> {
291 let stores = NodeStores::open(&data_storage, &measure_storage).await?;
292 let collector =
293 EvidenceCollectorIdentity::new(pc.network_id(), pc.delegatee_key().delegator_did());
294 let measure = PeriodicMeasure::new_with_evidence_storage_and_clock(
295 stores.measure,
296 stores.evidence,
297 collector,
298 pc.clock().clone(),
299 )
300 .await?;
301
302 let builder = ProcessorBuilder::from_config(pc)?
303 .storage(stores.data)
304 .relay_storage(stores.relay)
305 .removal_storage(stores.removals)
306 .onion_entry_guard_storage(stores.guards)
307 .replay_storage(stores.replay)
308 .measure(measure)
309 .stores_released(stores.released)
310 .reassembly_limits(reassembly_limits);
311 let builder = match service_offer {
312 Some(offer) => builder.announce_services(offer),
313 None => builder,
314 };
315 let builder = hooks.configure_builder(builder)?;
316 Ok(Arc::new(builder.build()?))
317}
318
319fn onion_http_proxy_options(c: &config::Config) -> anyhow::Result<Option<OnionHttpProxyOptions>> {
321 let Some(addr) = c.onion_http_proxy_addr.as_deref() else {
322 return Ok(None);
323 };
324 Ok(Some(OnionHttpProxyOptions {
325 listen_addr: addr.parse::<SocketAddr>()?,
326 max_connections: c.onion_http_proxy_max_connections,
327 header_timeout: Duration::from_secs(c.onion_http_proxy_header_timeout_secs),
328 }))
329}
330
331#[doc(hidden)]
334pub struct OwnedTask<T>(JoinSet<T>);
335
336impl<T: Send + 'static> OwnedTask<T> {
337 pub fn spawn(task: impl Future<Output = T> + Send + 'static) -> Self {
340 let mut set = JoinSet::new();
341 set.spawn(task);
342 Self(set)
343 }
344
345 pub fn abort(&mut self) {
347 self.0.abort_all();
348 }
349}
350
351impl<T: 'static> Future for OwnedTask<T> {
352 type Output = Result<T, JoinError>;
353
354 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
355 match self.0.poll_join_next(cx) {
356 Poll::Ready(Some(result)) => Poll::Ready(result),
357 Poll::Ready(None) | Poll::Pending => Poll::Pending,
358 }
359 }
360}
361
362#[doc(hidden)]
364pub async fn start_gateway(
365 runner: Option<NativeGatewayRunner>,
366 stop: StopToken,
367) -> anyhow::Result<OwnedTask<anyhow::Result<()>>> {
368 let configured = runner.is_some();
369 let (started, startup) = tokio::sync::oneshot::channel();
370 let mut task = OwnedTask::spawn(async move {
371 match runner {
372 Some(runner) => runner.run_with_startup_barrier(stop, started).await,
373 None => std::future::pending::<anyhow::Result<()>>().await,
374 }
375 });
376 await_gateway_startup(configured, startup, &mut task).await?;
377 Ok(task)
378}
379
380fn spawn_apis(
382 tasks: &mut JoinSet<anyhow::Result<()>>,
383 internal: u16,
384 external: String,
385 processor: Arc<Processor>,
386 gateway_status: Option<GatewayStatusHandle>,
387 api_security: Arc<ApiSecurity>,
388) {
389 let internal_processor = processor.clone();
390 let internal_security = api_security.clone();
391 tasks.spawn(async move {
392 run_internal_api_with_gateway(
393 internal,
394 internal_processor,
395 gateway_status,
396 internal_security,
397 )
398 .await
399 .context("internal API stopped")
400 });
401 tasks.spawn(async move {
402 run_external_api(external, processor, api_security)
403 .await
404 .context("external API stopped")
405 });
406}
407
408#[doc(hidden)]
410pub fn spawn_processor(
411 processor: Arc<Processor>,
412 stop: StopToken,
413) -> OwnedTask<anyhow::Result<()>> {
414 OwnedTask::spawn(async move {
415 processor.listen_with(stop.clone()).await;
416 if stop.should_stop() {
417 Ok(())
418 } else {
419 anyhow::bail!("node processor listener stopped unexpectedly")
420 }
421 })
422}
423
424async fn await_foreground_exit<H: NativeDaemonHooks>(
428 stop: StopSource,
429 tasks: JoinSet<anyhow::Result<()>>,
430 gateway_task: OwnedTask<anyhow::Result<()>>,
431 processor_task: OwnedTask<anyhow::Result<()>>,
432 processor: Arc<Processor>,
433 gateway_configured: bool,
434 hooks: &mut H,
435) -> anyhow::Result<()> {
436 await_foreground_exit_with_signal(
437 shutdown_signal(),
438 stop,
439 tasks,
440 gateway_task,
441 processor_task,
442 processor,
443 gateway_configured,
444 hooks,
445 )
446 .await
447}
448
449#[doc(hidden)]
451#[allow(clippy::too_many_arguments)]
452pub async fn await_foreground_exit_with_signal<H: NativeDaemonHooks>(
453 shutdown: impl Future<Output = anyhow::Result<()>>,
454 stop: StopSource,
455 mut tasks: JoinSet<anyhow::Result<()>>,
456 mut gateway_task: OwnedTask<anyhow::Result<()>>,
457 mut processor_task: OwnedTask<anyhow::Result<()>>,
458 processor: Arc<Processor>,
459 gateway_configured: bool,
460 hooks: &mut H,
461) -> anyhow::Result<()> {
462 enum ForegroundExit {
463 Signal(anyhow::Result<()>),
464 Service(Option<Result<anyhow::Result<()>, JoinError>>),
465 Gateway(Result<anyhow::Result<()>, JoinError>),
466 Processor(Result<anyhow::Result<()>, JoinError>),
467 }
468 let exit = tokio::select! {
469 signal = shutdown => ForegroundExit::Signal(signal),
470 service = tasks.join_next() => ForegroundExit::Service(service),
471 gateway = &mut gateway_task => ForegroundExit::Gateway(gateway),
472 processor = &mut processor_task => ForegroundExit::Processor(processor),
473 };
474 stop.request_stop();
475 tasks.abort_all();
478 while tasks.join_next().await.is_some() {}
479
480 let (primary, gateway_finished, processor_finished) = match exit {
481 ForegroundExit::Signal(result) => (result, false, false),
482 ForegroundExit::Service(result) => (joined_service_result(result), false, false),
483 ForegroundExit::Gateway(result) => (joined_task_result(result, "gateway"), true, false),
484 ForegroundExit::Processor(result) => {
485 (joined_task_result(result, "node processor"), false, true)
486 }
487 };
488 let gateway_cleanup = if gateway_configured && !gateway_finished {
489 await_task_cleanup(&mut gateway_task, "gateway route cleanup").await
490 } else {
491 if !gateway_finished {
492 gateway_task.abort();
493 }
494 Ok(())
495 };
496 let processor_cleanup = if processor_finished {
497 Ok(())
498 } else {
499 await_task_cleanup(&mut processor_task, "node processor shutdown").await
500 };
501 let processor_close = await_processor_close(&processor).await;
502 let hooks_cleanup = hooks.shutdown().await;
503 combine_foreground_results(
504 primary,
505 gateway_cleanup,
506 processor_cleanup,
507 processor_close,
508 hooks_cleanup,
509 )
510}
511
512fn configure_api_security(
513 config_path: &str,
514 config: &mut config::Config,
515 token_path_override: Option<String>,
516 allowed_origin_overrides: Vec<String>,
517 allow_remote_override: bool,
518) -> anyhow::Result<Arc<ApiSecurity>> {
519 if let Some(token_path) = token_path_override {
520 config.api_token_path = Some(token_path);
521 }
522 if !allowed_origin_overrides.is_empty() {
523 config.api_allowed_origins = allowed_origin_overrides;
524 }
525 if allow_remote_override {
526 config.allow_remote_external_api = true;
527 }
528 let token = load_or_create_api_token(config_path, config.api_token_path.as_deref())?;
529 println!("API authentication token file initialized.");
530 ApiSecurity::new(
531 token.into_secret(),
532 &config.api_allowed_origins,
533 config.allow_remote_external_api,
534 )
535 .map(Arc::new)
536 .map_err(Into::into)
537}
538
539fn joined_service_result(
540 result: Option<Result<anyhow::Result<()>, JoinError>>,
541) -> anyhow::Result<()> {
542 match result {
543 Some(Ok(result)) => result,
544 Some(Err(error)) => Err(anyhow::anyhow!("foreground service task failed: {error}")),
545 None => Err(anyhow::anyhow!("all foreground service tasks stopped")),
546 }
547}
548
549fn joined_task_result(
550 result: Result<anyhow::Result<()>, JoinError>,
551 task: &'static str,
552) -> anyhow::Result<()> {
553 match result {
554 Ok(result) => result,
555 Err(error) => Err(anyhow::anyhow!("{task} task failed: {error}")),
556 }
557}
558
559#[doc(hidden)]
561pub async fn await_gateway_startup(
562 configured: bool,
563 startup: tokio::sync::oneshot::Receiver<()>,
564 gateway_task: &mut OwnedTask<anyhow::Result<()>>,
565) -> anyhow::Result<()> {
566 if !configured {
567 return Ok(());
568 }
569 match startup.await {
570 Ok(()) => Ok(()),
571 Err(_) => joined_task_result(gateway_task.await, "gateway startup"),
572 }
573}
574
575#[doc(hidden)]
577pub async fn await_task_cleanup(
578 task: &mut OwnedTask<anyhow::Result<()>>,
579 operation: &'static str,
580) -> anyhow::Result<()> {
581 match tokio::time::timeout(FOREGROUND_CLEANUP_TIMEOUT, &mut *task).await {
582 Ok(result) => joined_task_result(result, operation),
583 Err(_) => {
584 task.abort();
585 Err(anyhow::anyhow!(
586 "{operation} did not finish within {FOREGROUND_CLEANUP_TIMEOUT:?}"
587 ))
588 }
589 }
590}
591
592async fn await_processor_close(processor: &Processor) -> anyhow::Result<()> {
593 match tokio::time::timeout(FOREGROUND_CLEANUP_TIMEOUT, processor.close()).await {
594 Ok(result) => result.context("node processor close failed"),
595 Err(_) => Err(anyhow::anyhow!(
596 "node processor close did not finish within {FOREGROUND_CLEANUP_TIMEOUT:?}"
597 )),
598 }
599}
600
601fn combine_foreground_results(
602 primary: anyhow::Result<()>,
603 gateway_cleanup: anyhow::Result<()>,
604 processor_cleanup: anyhow::Result<()>,
605 processor_close: anyhow::Result<()>,
606 hooks_cleanup: anyhow::Result<()>,
607) -> anyhow::Result<()> {
608 let failures = [
609 primary.err().map(|error| format!("foreground: {error}")),
610 gateway_cleanup
611 .err()
612 .map(|error| format!("gateway cleanup: {error}")),
613 processor_cleanup
614 .err()
615 .map(|error| format!("processor cleanup: {error}")),
616 processor_close
617 .err()
618 .map(|error| format!("processor close: {error}")),
619 hooks_cleanup
620 .err()
621 .map(|error| format!("daemon hook shutdown: {error}")),
622 ]
623 .into_iter()
624 .flatten()
625 .collect::<Vec<_>>();
626 if failures.is_empty() {
627 Ok(())
628 } else {
629 Err(anyhow::anyhow!(failures.join("; ")))
630 }
631}
632
633async fn shutdown_signal() -> anyhow::Result<()> {
634 #[cfg(unix)]
635 {
636 let mut terminate =
637 tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
638 tokio::select! {
639 result = tokio::signal::ctrl_c() => result?,
640 _ = terminate.recv() => {}
641 }
642 }
643 #[cfg(not(unix))]
644 tokio::signal::ctrl_c().await?;
645 Ok(())
646}