Skip to main content

dynamo_runtime/
distributed.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::component::{
5    self, Component, ComponentBuilder, Endpoint, EndpointDiscoverySource, Instance, Namespace,
6};
7use crate::config::environment_names::tcp_response_stream;
8use crate::pipeline::PipelineError;
9use crate::pipeline::network::ResponsePlaneMode;
10use crate::pipeline::network::manager::NetworkManager;
11use crate::service::{ServiceClient, ServiceSet};
12use crate::storage::kv;
13use crate::{discovery, system_status_server, transports};
14use crate::{
15    discovery::{Discovery, DiscoverySpec, EndpointRegistrationLease, EndpointRegistrationManager},
16    metrics::PrometheusUpdateCallback,
17    metrics::{MetricsHierarchy, MetricsRegistry},
18    transports::{etcd, nats, tcp},
19};
20
21use super::utils::GracefulShutdownTracker;
22use crate::SystemHealth;
23use crate::routing_policy::RoutingOccupancyState;
24use crate::runtime::Runtime;
25
26// Used instead of std::cell::OnceCell because get_or_try_init there is nightly
27use async_once_cell::OnceCell;
28
29use std::fmt;
30use std::sync::{Arc, OnceLock, Weak};
31use std::time::Duration;
32use tokio::sync::watch::Receiver;
33
34use anyhow::Result;
35use derive_getters::Dissolve;
36use figment::error;
37use std::collections::HashMap;
38use tokio::sync::Mutex;
39use tokio_util::sync::CancellationToken;
40
41type EndpointDiscoverySourceMap = HashMap<Endpoint, Weak<EndpointDiscoverySource>>;
42type RoutingOccupancyMap = HashMap<Endpoint, Weak<RoutingOccupancyState>>;
43
44fn parse_tcp_response_stream_port(value: Option<&str>) -> Result<u16, PipelineError> {
45    let Some(port) = value.map(str::trim).filter(|value| !value.is_empty()) else {
46        return Ok(0);
47    };
48
49    port.parse::<u16>().map_err(|_| {
50        PipelineError::Generic(format!(
51            "invalid {}: '{}' is not a valid port number",
52            tcp_response_stream::DYN_TCP_RESPONSE_STREAM_PORT,
53            port
54        ))
55    })
56}
57
58#[cfg(test)]
59mod unit_tests {
60    use super::parse_tcp_response_stream_port;
61    use crate::pipeline::PipelineError;
62
63    #[tokio::test]
64    async fn completed_runtime_initialization_rejects_shutdown_before_http_bind() {
65        if crate::test_utils::run_isolated(
66            concat!(
67                module_path!(),
68                "::completed_runtime_initialization_rejects_shutdown_before_http_bind"
69            ),
70            &[],
71        ) {
72            return;
73        }
74
75        use super::{DistributedConfig, DistributedRuntime, Runtime};
76        use crate::system_status_server::SystemProbePolicy;
77
78        temp_env::async_with_vars(
79            [
80                ("DYN_SYSTEM_HOST", Some("127.0.0.1")),
81                ("DYN_SYSTEM_PORT", Some("0")),
82            ],
83            async {
84                let runtime = Runtime::from_current().unwrap();
85                runtime.mark_shutting_down();
86                // Exercise the final bind guard directly: the public constructor
87                // would reject shutdown before polling build at all.
88                let result = DistributedRuntime::build(
89                    runtime.clone(),
90                    DistributedConfig::process_local(),
91                    SystemProbePolicy::RuntimeOnly,
92                )
93                .await;
94                assert!(
95                    result
96                        .unwrap_err()
97                        .to_string()
98                        .contains("runtime shut down during initialization")
99                );
100                runtime.shutdown();
101            },
102        )
103        .await;
104    }
105
106    #[test]
107    fn response_stream_port_trims_and_treats_empty_as_unset() {
108        for value in [None, Some(""), Some(" \t ")] {
109            assert_eq!(parse_tcp_response_stream_port(value).unwrap(), 0);
110        }
111        assert_eq!(
112            parse_tcp_response_stream_port(Some(" 8080 ")).unwrap(),
113            8080
114        );
115    }
116
117    #[test]
118    fn response_stream_port_rejects_invalid_values() {
119        let error = parse_tcp_response_stream_port(Some(" 65536 ")).unwrap_err();
120        assert!(matches!(
121            error,
122            PipelineError::Generic(message)
123                if message
124                    == "invalid DYN_TCP_RESPONSE_STREAM_PORT: '65536' is not a valid port number"
125        ));
126    }
127}
128
129/// Distributed [Runtime] providing cluster-wide communication, transport, and discovery resources.
130///
131/// `DistributedRuntime` is not a process singleton. Calling [`DistributedRuntime::new`] more than
132/// once creates independent DRT instances with distinct discovery connection IDs, even when they
133/// share a process. Cloning a DRT continues to share the original instance and connection ID.
134///
135/// Production services should normally treat one DRT per service replica/process as a soft
136/// invariant. Multiple DRTs in one process are primarily supported for single-process test
137/// topologies and for the mocker, which models multiple isolated workers in one process.
138#[derive(Clone)]
139pub struct DistributedRuntime {
140    // local runtime
141    runtime: Runtime,
142
143    nats_client: Option<transports::nats::Client>,
144    network_manager: Arc<NetworkManager>,
145    tcp_server: Arc<OnceCell<Arc<transports::tcp::server::TcpStreamServer>>>,
146    quic_response_server:
147        Arc<OnceCell<Arc<crate::pipeline::network::quic_response::QuicResponseServer>>>,
148    system_status_server: Arc<OnceLock<Arc<system_status_server::SystemStatusServerInfo>>>,
149    request_plane: RequestPlaneMode,
150    response_plane: ResponsePlaneMode,
151
152    // Service discovery client
153    discovery_client: Arc<dyn discovery::Discovery>,
154    endpoint_registrations: Arc<EndpointRegistrationManager>,
155
156    // Discovery metadata (only used for Kubernetes backend)
157    // Shared with system status server to expose via /metadata endpoint
158    discovery_metadata: Option<Arc<tokio::sync::RwLock<discovery::DiscoveryMetadata>>>,
159
160    // local registry for components
161    // the registry allows us to use share runtime resources across instances of the same component object.
162    // take for example two instances of a client to the same remote component. The registry allows us to use
163    // a single endpoint watcher for both clients, this keeps the number background tasking watching specific
164    // paths in etcd to a minimum.
165    component_registry: component::Registry,
166
167    endpoint_discovery_sources: Arc<tokio::sync::Mutex<EndpointDiscoverySourceMap>>,
168    routing_occupancy_states: Arc<tokio::sync::Mutex<RoutingOccupancyMap>>,
169
170    // Health Status
171    system_health: Arc<parking_lot::Mutex<SystemHealth>>,
172
173    // Local endpoint registry for in-process calls
174    local_endpoint_registry: crate::local_endpoint_registry::LocalEndpointRegistry,
175
176    // This hierarchy's own metrics registry
177    metrics_registry: MetricsRegistry,
178
179    // Registry for /engine/* route callbacks
180    engine_routes: crate::engine_routes::EngineRouteRegistry,
181
182    // Backs `/v1/metadata/{model_slug}/{model_suffix}/{filename}`.
183    metadata_artifacts: crate::metadata_registry::MetadataArtifactRegistry,
184
185    // Resolved event transport kind — set once at construction time from
186    // DYN_EVENT_PLANE + discovery backend; returned by default_event_transport_kind().
187    event_transport_kind: crate::discovery::EventTransportKind,
188}
189
190impl MetricsHierarchy for DistributedRuntime {
191    fn basename(&self) -> String {
192        "".to_string() // drt has no basename. Basename only begins with the Namespace.
193    }
194
195    fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
196        vec![] // drt is the root, so no parent hierarchies
197    }
198
199    fn get_metrics_registry(&self) -> &MetricsRegistry {
200        &self.metrics_registry
201    }
202
203    fn connection_id(&self) -> Option<u64> {
204        Some(self.discovery_client.instance_id())
205    }
206}
207
208impl std::fmt::Debug for DistributedRuntime {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        write!(f, "DistributedRuntime")
211    }
212}
213
214impl DistributedRuntime {
215    pub async fn new(runtime: Runtime, config: DistributedConfig) -> Result<Self> {
216        Self::new_with_probe_policy(
217            runtime,
218            config,
219            system_status_server::SystemProbePolicy::Worker,
220        )
221        .await
222    }
223
224    /// Initialize runtime dependencies, then bind HTTP with the selected probe policy.
225    /// Shutdown cancels pending initialization; no listener exists until it completes.
226    pub async fn new_with_probe_policy(
227        runtime: Runtime,
228        config: DistributedConfig,
229        policy: system_status_server::SystemProbePolicy,
230    ) -> Result<Self> {
231        let shutdown = runtime.shutdown_started_token();
232        tokio::select! {
233            biased;
234            _ = shutdown.cancelled() => anyhow::bail!("runtime shut down during initialization"),
235            result = Self::build(runtime, config, policy) => result,
236        }
237    }
238
239    async fn build(
240        runtime: Runtime,
241        config: DistributedConfig,
242        policy: system_status_server::SystemProbePolicy,
243    ) -> Result<Self> {
244        let (discovery_backend, nats_config, request_plane, response_plane, event_transport_kind) =
245            config.dissolve();
246        let response_plane = match response_plane {
247            Some(mode) => mode,
248            None => ResponsePlaneMode::configured()?,
249        };
250
251        let config = crate::config::RuntimeConfig::from_settings()?;
252        let nats_client = match nats_config {
253            Some(nc) => Some(
254                nc.connect_with_cancellation(runtime.primary_token())
255                    .await?,
256            ),
257            None => None,
258        };
259
260        // Initialize discovery client based on backend configuration
261        let (discovery_client, discovery_metadata) = match discovery_backend {
262            DiscoveryBackend::Kubernetes => {
263                tracing::info!("Initializing Kubernetes discovery backend");
264                let metadata = Arc::new(tokio::sync::RwLock::new(
265                    crate::discovery::DiscoveryMetadata::new(),
266                ));
267                let client = crate::discovery::KubeDiscoveryClient::new(
268                    metadata.clone(),
269                    runtime.primary_token(),
270                )
271                .await
272                .inspect_err(
273                    |err| tracing::error!(%err, "Failed to initialize Kubernetes discovery client"),
274                )?;
275                (Arc::new(client) as Arc<dyn Discovery>, Some(metadata))
276            }
277            DiscoveryBackend::KvStore(kv_selector) => {
278                tracing::info!("Initializing KV store discovery backend: {kv_selector}");
279                let runtime_clone = runtime.clone();
280                let store = match kv_selector {
281                    kv::Selector::Etcd(etcd_config) => {
282                        let etcd_client = etcd::Client::new(*etcd_config, runtime_clone).await.inspect_err(|err|
283                            tracing::error!(%err, "Could not connect to etcd. Pass `--discovery-backend ..` to use a different backend or start etcd."))?;
284                        kv::Manager::etcd(etcd_client)
285                    }
286                    kv::Selector::File(root) => kv::Manager::file(runtime.primary_token(), root),
287                    kv::Selector::Memory => kv::Manager::memory(),
288                };
289                use crate::discovery::KVStoreDiscovery;
290                (
291                    Arc::new(KVStoreDiscovery::new(store, runtime.primary_token()))
292                        as Arc<dyn Discovery>,
293                    None,
294                )
295            }
296        };
297
298        let starting_health_status = config.starting_health_status.clone();
299        let use_endpoint_health_status = config.use_endpoint_health_status.clone();
300        let health_endpoint_path = config.system_health_path.clone();
301        let live_endpoint_path = config.system_live_path.clone();
302        let system_health = Arc::new(parking_lot::Mutex::new(SystemHealth::new(
303            starting_health_status,
304            use_endpoint_health_status,
305            config.health_check_enabled,
306            health_endpoint_path,
307            live_endpoint_path,
308        )));
309
310        let component_registry = component::Registry::new();
311
312        // NetworkManager for request plane
313        let network_manager = NetworkManager::new(
314            runtime.child_token(),
315            nats_client.clone().map(|c| c.client().clone()),
316            component_registry.clone(),
317            request_plane,
318        );
319
320        let endpoint_registrations = EndpointRegistrationManager::new(
321            discovery_client.clone(),
322            runtime.secondary(),
323            runtime.primary_token(),
324        );
325        let distributed_runtime = Self {
326            runtime,
327            network_manager: Arc::new(network_manager),
328            nats_client,
329            tcp_server: Arc::new(OnceCell::new()),
330            quic_response_server: Arc::new(OnceCell::new()),
331            system_status_server: Arc::new(OnceLock::new()),
332            discovery_client,
333            endpoint_registrations,
334            discovery_metadata,
335            component_registry,
336            endpoint_discovery_sources: Arc::new(Mutex::new(HashMap::new())),
337            routing_occupancy_states: Arc::new(Mutex::new(HashMap::new())),
338            metrics_registry: crate::MetricsRegistry::new(),
339            system_health,
340            request_plane,
341            response_plane,
342            local_endpoint_registry: crate::local_endpoint_registry::LocalEndpointRegistry::new(),
343            engine_routes: crate::engine_routes::EngineRouteRegistry::new(),
344            metadata_artifacts: crate::metadata_registry::MetadataArtifactRegistry::new(),
345            event_transport_kind,
346        };
347
348        if response_plane == ResponsePlaneMode::Quic {
349            crate::metrics::quic_response::ensure_registered(
350                distributed_runtime.get_metrics_registry(),
351            );
352        }
353        if response_plane == ResponsePlaneMode::Velo {
354            distributed_runtime.velo_response_service().await?;
355            crate::pipeline::network::velo_response::register_metrics(
356                distributed_runtime.get_metrics_registry(),
357            );
358        }
359
360        // Initialize the uptime gauge in SystemHealth
361        distributed_runtime
362            .system_health
363            .lock()
364            .initialize_uptime_gauge(&distributed_runtime)?;
365
366        // Register an update callback so the uptime gauge is refreshed before
367        // every Prometheus scrape (both system status server and frontend).
368        {
369            let system_health = distributed_runtime.system_health.clone();
370            distributed_runtime
371                .metrics_registry
372                .add_update_callback(std::sync::Arc::new(move || {
373                    system_health.lock().update_uptime_gauge();
374                    Ok(())
375                }));
376        }
377
378        // Opt-in OTLP metrics export. Deliberately not tied to the system
379        // status server: that server is disabled by default
380        // (DYN_SYSTEM_PORT=-1), and gating export on it would make
381        // OTEL_METRICS_EXPORTER=otlp a silent no-op in the default
382        // configuration. Traces and logs are set up in logging::init() for the
383        // same reason -- an OTEL_* variable should mean the same thing for
384        // every signal. Metrics cannot join them there because the exporter
385        // needs the registry, which only exists once the runtime does.
386        match crate::metrics::otlp_export::ExportConfig::from_env() {
387            Ok(Some(export_config)) => {
388                tracing::info!(
389                    endpoint = %export_config.endpoint,
390                    interval_ms = export_config.interval.as_millis(),
391                    "exporting metrics over OTLP"
392                );
393                // Hold a graceful-shutdown guard for the task's life so the
394                // final export is not abandoned mid-RPC. `child_token()`
395                // derives from the endpoint shutdown token, which Phase 1
396                // cancels *before* the Phase 2 wait, so the exporter is told to
397                // stop and then waited for -- it cannot deadlock the wait on a
398                // token that only fires in Phase 3.
399                let shutdown_guard = distributed_runtime
400                    .runtime
401                    .graceful_shutdown_tracker()
402                    .register_task();
403                let registry = distributed_runtime.metrics_registry.clone();
404                let cancel = distributed_runtime.runtime.child_token();
405                tokio::spawn(async move {
406                    crate::metrics::otlp_export::run(registry, export_config, cancel).await;
407                    drop(shutdown_guard);
408                });
409            }
410            Ok(None) => {}
411            Err(error) => {
412                tracing::error!(%error, "OTLP metrics export is misconfigured; not exporting");
413            }
414        }
415
416        // Start health check manager if enabled
417        if config.health_check_enabled {
418            let health_check_config = crate::health_check::HealthCheckConfig {
419                canary_wait_time: std::time::Duration::from_secs(config.canary_wait_time_secs),
420                request_timeout: std::time::Duration::from_secs(
421                    config.health_check_request_timeout_secs,
422                ),
423            };
424
425            // Start the health check manager (spawns per-endpoint monitoring tasks)
426            match crate::health_check::start_health_check_manager(
427                distributed_runtime.clone(),
428                Some(health_check_config),
429            )
430            .await
431            {
432                Ok(()) => tracing::info!(
433                    "Health check manager started (canary_wait_time: {}s, request_timeout: {}s)",
434                    config.canary_wait_time_secs,
435                    config.health_check_request_timeout_secs
436                ),
437                Err(e) => tracing::error!("Health check manager failed to start: {e}"),
438            }
439        }
440
441        anyhow::ensure!(
442            !distributed_runtime.runtime.is_shutting_down(),
443            "runtime shut down during initialization"
444        );
445        if config.system_server_enabled() {
446            // Keep sidecar probes alive through unregister/drain. Ordinary workers
447            // retain their existing endpoint-shutdown lifetime.
448            let stop = match policy {
449                system_status_server::SystemProbePolicy::Worker => {
450                    distributed_runtime.runtime.child_token()
451                }
452                system_status_server::SystemProbePolicy::RuntimeOnly => {
453                    distributed_runtime.runtime.primary_token().child_token()
454                }
455            };
456            match system_status_server::spawn_system_status_server(
457                &config.system_host,
458                config.system_port as u16,
459                stop,
460                Arc::new(distributed_runtime.clone()),
461                distributed_runtime.discovery_metadata.clone(),
462                policy,
463            )
464            .await
465            {
466                Ok((address, handle)) => {
467                    distributed_runtime
468                        .system_status_server
469                        .set(Arc::new(system_status_server::SystemStatusServerInfo::new(
470                            address,
471                            Some(handle),
472                        )))
473                        .expect("System status server info should only be set once");
474                    tracing::info!(%address, ?policy, "System HTTP listener started");
475                }
476                // Preserve ordinary workers' optional-HTTP failure behavior.
477                Err(error) if policy == system_status_server::SystemProbePolicy::Worker => {
478                    tracing::error!(%error, "System status server startup failed");
479                }
480                Err(error) => return Err(error),
481            }
482        }
483        Ok(distributed_runtime)
484    }
485
486    pub async fn from_settings(runtime: Runtime) -> Result<Self> {
487        let config = DistributedConfig::try_from_settings()?;
488        Self::new(runtime, config).await
489    }
490
491    /// Check configured runtime dependencies, independently of model registration.
492    /// The HTTP caller bounds this operation; it never performs inference.
493    pub(crate) async fn check_dependencies(&self) -> Result<()> {
494        anyhow::ensure!(!self.runtime.is_shutting_down(), "runtime is shutting down");
495        if let Some(client) = &self.nats_client {
496            anyhow::ensure!(
497                client.client().connection_state() == async_nats::connection::State::Connected,
498                "NATS is disconnected"
499            );
500        }
501        self.discovery_client.check_connection().await?;
502        anyhow::ensure!(!self.runtime.is_shutting_down(), "runtime is shutting down");
503        Ok(())
504    }
505
506    pub fn runtime(&self) -> &Runtime {
507        &self.runtime
508    }
509
510    pub fn primary_token(&self) -> CancellationToken {
511        self.runtime.primary_token()
512    }
513
514    // TODO: Don't hand out pointers, instead have methods to use the registry in friendly ways
515    // (without being aware of async locks and so on)
516    pub fn component_registry(&self) -> &component::Registry {
517        &self.component_registry
518    }
519
520    // TODO: Don't hand out pointers, instead provide system health related services.
521    pub fn system_health(&self) -> Arc<parking_lot::Mutex<SystemHealth>> {
522        self.system_health.clone()
523    }
524
525    /// Get the local endpoint registry for in-process endpoint calls
526    pub fn local_endpoint_registry(
527        &self,
528    ) -> &crate::local_endpoint_registry::LocalEndpointRegistry {
529        &self.local_endpoint_registry
530    }
531
532    /// Get the engine route registry for registering custom /engine/* routes
533    pub fn engine_routes(&self) -> &crate::engine_routes::EngineRouteRegistry {
534        &self.engine_routes
535    }
536
537    pub fn metadata_artifacts(&self) -> &crate::metadata_registry::MetadataArtifactRegistry {
538        &self.metadata_artifacts
539    }
540
541    /// Returns this DRT instance's discovery identity.
542    ///
543    /// This identifies the DRT, not the operating-system process. Multiple DRTs in one process
544    /// receive distinct connection IDs.
545    pub fn connection_id(&self) -> u64 {
546        self.discovery_client.instance_id()
547    }
548
549    pub fn shutdown(&self) {
550        self.runtime.shutdown();
551        self.discovery_client.shutdown();
552    }
553
554    /// Create a [`Namespace`]
555    pub fn namespace(&self, name: impl Into<String>) -> Result<Namespace> {
556        Namespace::new(self.clone(), name.into())
557    }
558
559    /// Returns the discovery interface for service registration and discovery
560    pub fn discovery(&self) -> Arc<dyn Discovery> {
561        self.discovery_client.clone()
562    }
563
564    /// Register an endpoint until the last runtime-wide owner drops its lease.
565    pub async fn register_endpoint_lease(
566        &self,
567        spec: DiscoverySpec,
568    ) -> Result<EndpointRegistrationLease> {
569        self.endpoint_registrations.register(spec).await
570    }
571
572    pub async fn tcp_server(&self) -> Result<Arc<tcp::server::TcpStreamServer>> {
573        Ok(self
574            .tcp_server
575            .get_or_try_init(async move {
576                let port_value =
577                    std::env::var(tcp_response_stream::DYN_TCP_RESPONSE_STREAM_PORT).ok();
578                let port = parse_tcp_response_stream_port(port_value.as_deref())?;
579                let host = crate::utils::ip_resolver::host_override_from_env(
580                    tcp_response_stream::DYN_TCP_RESPONSE_STREAM_HOST,
581                )
582                .map_err(|error| PipelineError::Generic(error.to_string()))?;
583
584                let host_suffix = host
585                    .as_ref()
586                    .map_or(String::new(), |h| format!(" on host {h}"));
587                if port == 0 {
588                    tracing::info!(
589                        "TCP request callback server using OS-assigned port{host_suffix}"
590                    );
591                } else {
592                    tracing::info!(
593                        "TCP request callback server using fixed port {port}{host_suffix}"
594                    );
595                }
596
597                let options = tcp::server::ServerOptions {
598                    port,
599                    interface: host,
600                };
601                let server = tcp::server::TcpStreamServer::new(options).await?;
602                Ok::<_, PipelineError>(server)
603            })
604            .await?
605            .clone())
606    }
607
608    pub async fn velo_response_service(
609        &self,
610    ) -> Result<Arc<crate::pipeline::network::velo_response::VeloResponseService>> {
611        self.runtime.velo_response_service().service().await
612    }
613
614    pub async fn quic_response_server(
615        &self,
616    ) -> Result<Arc<crate::pipeline::network::quic_response::QuicResponseServer>> {
617        anyhow::ensure!(
618            self.response_plane == ResponsePlaneMode::Quic,
619            "QUIC response server requested while response plane is {}",
620            self.response_plane.name()
621        );
622        Ok(self
623            .quic_response_server
624            .get_or_try_init(async {
625                let tcp_server = self.tcp_server().await?;
626                let tcp_address = tcp_server.local_address()?;
627                // Keep the selected interface, but let the UDP stack choose a
628                // free port. A TCP ephemeral port can already be in use by an
629                // unrelated UDP socket because the two protocols allocate
630                // ports independently.
631                let address = std::net::SocketAddr::new(tcp_address.ip(), 0);
632                crate::pipeline::network::quic_response::QuicResponseServer::new(
633                    address,
634                    address,
635                    self.runtime.child_token(),
636                )
637                .map_err(anyhow::Error::from)
638            })
639            .await?
640            .clone())
641    }
642
643    pub fn quic_response_client_pool(
644        &self,
645    ) -> Result<Arc<crate::pipeline::network::quic_response::QuicResponseClientPool>> {
646        anyhow::ensure!(
647            self.response_plane == ResponsePlaneMode::Quic,
648            "QUIC response client pool requested while response plane is {}",
649            self.response_plane.name()
650        );
651        crate::pipeline::network::quic_response::process_client_pool_from_env()
652            .map_err(anyhow::Error::from)
653    }
654
655    pub fn response_plane(&self) -> ResponsePlaneMode {
656        self.response_plane
657    }
658
659    /// Get the network manager
660    ///
661    /// The network manager consolidates all network configuration and provides
662    /// unified access to request plane servers and clients.
663    pub fn network_manager(&self) -> Arc<NetworkManager> {
664        self.network_manager.clone()
665    }
666
667    /// Get the request plane server (convenience method)
668    ///
669    /// This is a shortcut for `network_manager().await?.server().await`.
670    pub async fn request_plane_server(
671        &self,
672    ) -> Result<Arc<dyn crate::pipeline::network::ingress::unified_server::RequestPlaneServer>>
673    {
674        self.network_manager().server().await
675    }
676
677    /// Get system status server information if available
678    pub fn system_status_server_info(
679        &self,
680    ) -> Option<Arc<crate::system_status_server::SystemStatusServerInfo>> {
681        self.system_status_server.get().cloned()
682    }
683
684    /// How the frontend should talk to the backend.
685    pub fn request_plane(&self) -> RequestPlaneMode {
686        self.request_plane
687    }
688
689    /// Returns the event transport kind this runtime was configured with.
690    ///
691    /// The value is resolved once at construction time by `DiscoveryBackend::resolve_event_transport_kind`:
692    /// if `DYN_EVENT_PLANE` is set explicitly that value wins; otherwise the default is ZMQ.
693    ///
694    /// Use this instead of `EventTransportKind::from_env_or_default` wherever you have
695    /// access to a `DistributedRuntime`.
696    pub fn default_event_transport_kind(&self) -> crate::discovery::EventTransportKind {
697        self.event_transport_kind
698    }
699
700    pub fn child_token(&self) -> CancellationToken {
701        self.runtime.child_token()
702    }
703
704    pub(crate) fn graceful_shutdown_tracker(&self) -> Arc<GracefulShutdownTracker> {
705        self.runtime.graceful_shutdown_tracker()
706    }
707
708    pub(crate) fn endpoint_discovery_sources(&self) -> Arc<Mutex<EndpointDiscoverySourceMap>> {
709        self.endpoint_discovery_sources.clone()
710    }
711
712    /// Register an external long-running shutdown task with this runtime's
713    /// graceful-shutdown tracker. While the returned guard is alive,
714    /// `Runtime::shutdown` will keep waiting in Phase 2 (rather than
715    /// advancing to Phase 3 / NATS+etcd teardown). Drop the guard once
716    /// the task has finished.
717    pub fn register_graceful_task(&self) -> crate::utils::GracefulTaskGuard {
718        self.runtime.graceful_shutdown_tracker().register_task()
719    }
720
721    pub(crate) fn routing_occupancy_states(&self) -> Arc<Mutex<RoutingOccupancyMap>> {
722        self.routing_occupancy_states.clone()
723    }
724
725    /// TODO: This is a temporary KV router measure for component/component.rs EventPublisher impl for
726    /// Component, to allow it to publish to NATS. KV Router is the only user.
727    ///
728    /// When NATS is not available (e.g., running in approximate mode with --no-kv-events),
729    /// this function returns Ok(()) silently since publishing is optional in that mode.
730    pub async fn kv_router_nats_publish(
731        &self,
732        subject: String,
733        payload: bytes::Bytes,
734    ) -> anyhow::Result<()> {
735        self.kv_router_nats_publish_subject(subject.into(), payload)
736            .await
737    }
738
739    pub(crate) async fn kv_router_nats_publish_subject(
740        &self,
741        subject: async_nats::Subject,
742        payload: bytes::Bytes,
743    ) -> anyhow::Result<()> {
744        let Some(nats_client) = self.nats_client.as_ref() else {
745            // NATS not available - this is expected in approximate mode (--no-kv-events)
746            tracing::trace!("Skipping NATS publish (NATS not configured): {subject}");
747            return Ok(());
748        };
749        Ok(nats_client.client().publish(subject, payload).await?)
750    }
751
752    /// TODO: This is a temporary KV router measure for component/component.rs EventSubscriber impl for
753    /// Component, to allow it to subscribe to NATS. KV Router is the only user.
754    pub(crate) async fn kv_router_nats_subscribe(
755        &self,
756        subject: String,
757    ) -> Result<async_nats::Subscriber> {
758        let Some(nats_client) = self.nats_client.as_ref() else {
759            anyhow::bail!("KV router's EventSubscriber requires NATS");
760        };
761        Ok(nats_client.client().subscribe(subject).await?)
762    }
763
764    /// TODO (karenc): This is a temporary KV router measure for worker query requests.
765    /// Allows KV Router to perform request/reply with workers. (versus the pub/sub pattern above)
766    /// KV Router is the only user, made public for use in dynamo-llm crate
767    pub async fn kv_router_nats_request(
768        &self,
769        subject: String,
770        payload: bytes::Bytes,
771        timeout: std::time::Duration,
772    ) -> anyhow::Result<async_nats::Message> {
773        let Some(nats_client) = self.nats_client.as_ref() else {
774            anyhow::bail!("KV router's request requires NATS");
775        };
776        let response =
777            tokio::time::timeout(timeout, nats_client.client().request(subject, payload))
778                .await
779                .map_err(|_| anyhow::anyhow!("Request timed out after {:?}", timeout))??;
780        Ok(response)
781    }
782
783    /// DEPRECATED: This method exists only for NATS request plane support.
784    /// Once everything uses the TCP request plane, this can be removed along with
785    /// the NATS service registration infrastructure.
786    ///
787    /// Returns a receiver that signals when the NATS service registration is complete.
788    /// The caller should use `blocking_recv()` to wait for completion.
789    pub fn register_nats_service(
790        &self,
791        component: Component,
792    ) -> tokio::sync::mpsc::Receiver<Result<(), String>> {
793        // Create a oneshot-style channel (capacity 1) to signal completion
794        let (tx, rx) = tokio::sync::mpsc::channel::<Result<(), String>>(1);
795
796        let drt = self.clone();
797        self.runtime().secondary().spawn(async move {
798            let service_name = component.service_name();
799
800            // Pre-check to save cost of creating the service, but don't hold the lock
801            if drt
802                .component_registry()
803                .inner
804                .lock()
805                .await
806                .services
807                .contains_key(&service_name)
808            {
809                // The NATS service is per component, but it is called from `serve_endpoint`, and there
810                // are often multiple endpoints for a component (e.g. `clear_kv_blocks` and `generate`).
811                tracing::trace!("Service {service_name} already exists");
812                // Signal success - service already exists
813                let _ = tx.send(Ok(())).await;
814                return;
815            }
816
817            let Some(nats_client) = drt.nats_client.as_ref() else {
818                tracing::error!("Cannot create NATS service without NATS.");
819                let _ = tx
820                    .send(Err("Cannot create NATS service without NATS".to_string()))
821                    .await;
822                return;
823            };
824            let description = None;
825            let nats_service = match crate::component::service::build_nats_service(
826                nats_client,
827                &component,
828                description,
829            )
830            .await
831            {
832                Ok(service) => service,
833                Err(err) => {
834                    tracing::error!(error = %err, component = service_name, "Failed to build NATS service");
835                    let _ = tx.send(Err(format!("Failed to build NATS service: {err}"))).await;
836                    return;
837                }
838            };
839
840            let mut guard = drt.component_registry().inner.lock().await;
841            if !guard.services.contains_key(&service_name) {
842                // Normal case
843                guard.services.insert(service_name.clone(), nats_service);
844
845                tracing::info!("Added NATS service {service_name}");
846
847                drop(guard);
848            } else {
849                drop(guard);
850                let _ = nats_service.stop().await;
851                // The NATS service is per component, but it is called from `serve_endpoint`, and there
852                // are often multiple endpoints for a component (e.g. `clear_kv_blocks` and `generate`).
853                // TODO: Is this still true?
854            }
855
856            // Signal completion - service registered successfully
857            let _ = tx.send(Ok(())).await;
858        });
859
860        rx
861    }
862}
863
864#[cfg(test)]
865mod parser_env_tests {
866    use super::*;
867
868    #[tokio::test]
869    async fn distributed_runtime_validates_velo_at_startup() {
870        if crate::test_utils::run_isolated(
871            concat!(
872                module_path!(),
873                "::distributed_runtime_validates_velo_at_startup"
874            ),
875            &[],
876        ) {
877            return;
878        }
879        let busy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
880        let busy_port = busy.local_addr().unwrap().port().to_string();
881        // Each case sets one variable over a valid TCP configuration.
882        let mut cases = vec![
883            (
884                "DYN_VELO_RESPONSE_TRANSPORT",
885                "invalid",
886                "DYN_VELO_RESPONSE_TRANSPORT",
887            ),
888            (
889                "DYN_VELO_RESPONSE_BATCH_MS",
890                "invalid",
891                "DYN_VELO_RESPONSE_BATCH_MS",
892            ),
893            (
894                "DYN_VELO_RESPONSE_HEARTBEAT_MS",
895                "0",
896                "DYN_VELO_RESPONSE_HEARTBEAT_MS",
897            ),
898            (
899                "DYN_VELO_RESPONSE_PORT",
900                "invalid",
901                "DYN_VELO_RESPONSE_PORT",
902            ),
903            (
904                "DYN_VELO_RESPONSE_PORT",
905                busy_port.as_str(),
906                "Failed to pre-bind TCP listener",
907            ),
908            // Velo has no TLS, so TLS settings must not be silently ignored.
909            (
910                "DYN_TCP_TLS_CERT_PATH",
911                "/nonexistent/cert.pem",
912                "DYN_TCP_TLS_CERT_PATH",
913            ),
914            ("DYN_TCP_TLS_INSECURE", "true", "DYN_TCP_TLS_INSECURE"),
915        ];
916        if !cfg!(all(target_os = "linux", feature = "velo-ucx")) {
917            cases.push(("DYN_VELO_RESPONSE_TRANSPORT", "ucx", "velo-ucx"));
918        }
919        for (name, value, message) in cases {
920            let mut vars = vec![
921                ("DYN_VELO_RESPONSE_TRANSPORT", Some("tcp")),
922                ("DYN_TCP_RESPONSE_STREAM_HOST", Some("127.0.0.1")),
923            ];
924            vars.retain(|(var, _)| *var != name);
925            vars.push((name, Some(value)));
926            temp_env::async_with_vars(vars, async {
927                let runtime = Runtime::from_current().unwrap();
928                let mut config = DistributedConfig::process_local();
929                config.response_plane = Some(ResponsePlaneMode::Velo);
930                let error = DistributedRuntime::new(runtime, config)
931                    .await
932                    .expect_err("Velo configuration must fail before serving endpoints");
933                assert!(error.to_string().contains(message), "{error:#}");
934            })
935            .await;
936        }
937    }
938
939    #[tokio::test]
940    async fn distributed_runtime_rejects_invalid_parser_version() {
941        if crate::test_utils::run_isolated(
942            concat!(
943                module_path!(),
944                "::distributed_runtime_rejects_invalid_parser_version"
945            ),
946            &[(
947                crate::config::environment_names::llm::DYN_PARSER_VERSION,
948                "v3",
949            )],
950        ) {
951            return;
952        }
953
954        let runtime = Runtime::from_current().unwrap();
955        let error = DistributedRuntime::new(runtime, DistributedConfig::process_local())
956            .await
957            .expect_err("invalid parser configuration must fail runtime construction");
958        assert!(error.to_string().contains("DYN_PARSER_VERSION"));
959    }
960}
961
962/// Selects which discovery backend to use and, for KV store backends, which KV store.
963#[derive(Clone, Debug)]
964pub enum DiscoveryBackend {
965    /// Use Kubernetes API for service discovery (no KV store needed)
966    Kubernetes,
967    /// Use a KV store (etcd, file, or memory) for service discovery
968    KvStore(kv::Selector),
969}
970
971impl DiscoveryBackend {
972    /// Returns true if this backend requires no external services (file or in-memory).
973    ///
974    /// Local backends do not need etcd, NATS, or any other infrastructure daemon.
975    pub fn is_local(&self) -> bool {
976        matches!(
977            self,
978            DiscoveryBackend::KvStore(kv::Selector::File(_))
979                | DiscoveryBackend::KvStore(kv::Selector::Memory)
980        )
981    }
982
983    /// Resolve the event transport kind for this backend.
984    ///
985    /// This is the single authoritative mapping of `DYN_EVENT_PLANE` →
986    /// `EventTransportKind`. ZMQ is the default event plane for all backends
987    /// (`file`/`mem`/`etcd`/`kubernetes`); NATS is an explicit opt-in via
988    /// `DYN_EVENT_PLANE=nats`. The value is trimmed and matched case-insensitively.
989    ///
990    /// Call this once at startup and store the result; do not call it repeatedly.
991    ///
992    /// # Errors
993    /// Returns an error if `DYN_EVENT_PLANE` is set to anything other than
994    /// `nats`, `zmq`, or an empty value, so a typo cannot silently select ZMQ.
995    pub fn resolve_event_transport_kind(&self) -> Result<crate::discovery::EventTransportKind> {
996        use crate::config::environment_names::event_plane::DYN_EVENT_PLANE;
997        Self::event_transport_kind_from_env_result(std::env::var(DYN_EVENT_PLANE))
998    }
999
1000    fn event_transport_kind_from_env_result(
1001        value: std::result::Result<String, std::env::VarError>,
1002    ) -> Result<crate::discovery::EventTransportKind> {
1003        use crate::discovery::EventTransportKind;
1004        match value {
1005            // Unset or empty: ZMQ is the default for every backend.
1006            Err(std::env::VarError::NotPresent) => Ok(EventTransportKind::Zmq),
1007            Ok(raw) => match raw.trim().to_lowercase().as_str() {
1008                "nats" => Ok(EventTransportKind::Nats),
1009                "zmq" | "" => Ok(EventTransportKind::Zmq),
1010                _ => Err(anyhow::anyhow!(
1011                    "Invalid DYN_EVENT_PLANE value '{raw}'. Valid values: 'nats', 'zmq'"
1012                )),
1013            },
1014            Err(std::env::VarError::NotUnicode(raw)) => Err(anyhow::anyhow!(
1015                "Invalid DYN_EVENT_PLANE value '{}': not valid Unicode. \
1016                 Valid values: 'nats', 'zmq'",
1017                raw.to_string_lossy()
1018            )),
1019        }
1020    }
1021}
1022
1023#[derive(Dissolve)]
1024pub struct DistributedConfig {
1025    pub discovery_backend: DiscoveryBackend,
1026    pub nats_config: Option<nats::ClientOptions>,
1027    pub request_plane: RequestPlaneMode,
1028    /// Explicit response transport. `None` reads `DYN_RESPONSE_PLANE` for
1029    /// standalone Rust entry points.
1030    pub response_plane: Option<ResponsePlaneMode>,
1031    /// Resolved event transport kind — computed once at config time from
1032    /// `DYN_EVENT_PLANE` and the discovery backend, then stored on the runtime
1033    /// so callers always get the same answer regardless of which other services
1034    /// happen to be reachable.
1035    pub event_transport_kind: crate::discovery::EventTransportKind,
1036}
1037
1038impl DistributedConfig {
1039    /// Build distributed runtime configuration from environment defaults.
1040    ///
1041    /// # Panics
1042    /// Panics if a discovery or transport setting is invalid.
1043    pub fn from_settings() -> DistributedConfig {
1044        Self::try_from_settings().unwrap_or_else(|err| panic!("{err}"))
1045    }
1046
1047    pub fn try_from_settings() -> Result<DistributedConfig> {
1048        Self::from_settings_with_overrides(None, None, None)
1049    }
1050
1051    /// Resolve per-worker options before environment defaults, without mutating
1052    /// the process environment. Safe to use after the Tokio runtime has started.
1053    pub fn from_settings_with_overrides(
1054        discovery_backend: Option<&str>,
1055        request_plane: Option<&str>,
1056        event_plane: Option<&str>,
1057    ) -> Result<DistributedConfig> {
1058        let request_plane = match request_plane {
1059            Some(value) => value.parse()?,
1060            None => RequestPlaneMode::from_env()?,
1061        };
1062
1063        // Determine the discovery backend first — we need it to compute the NATS default below.
1064        // Valid values for DYN_DISCOVERY_BACKEND: "kubernetes", "etcd" (default), "file", "mem"
1065        let backend_str = discovery_backend
1066            .map(str::to_owned)
1067            .or_else(|| std::env::var("DYN_DISCOVERY_BACKEND").ok())
1068            .unwrap_or_else(|| "etcd".to_string());
1069
1070        let discovery_backend = match backend_str.as_str() {
1071            "kubernetes" => {
1072                tracing::info!("Using Kubernetes discovery backend");
1073                DiscoveryBackend::Kubernetes
1074            }
1075            other => {
1076                let selector: kv::Selector = other.parse().map_err(|_| {
1077                    anyhow::anyhow!(
1078                        "Unknown DYN_DISCOVERY_BACKEND value: '{other}'. \
1079                         Valid options: kubernetes, etcd, file, mem"
1080                    )
1081                })?;
1082                DiscoveryBackend::KvStore(selector)
1083            }
1084        };
1085
1086        // Resolve event transport kind once — the single source of truth used both to
1087        // decide whether to open a NATS connection and to answer
1088        // `DistributedRuntime::default_event_transport_kind()` later.
1089        let event_transport_kind = match event_plane {
1090            Some("nats") => crate::discovery::EventTransportKind::Nats,
1091            Some("zmq" | "") => crate::discovery::EventTransportKind::Zmq,
1092            Some(other) => {
1093                anyhow::bail!("Invalid event plane '{other}'. Valid options are: 'nats', 'zmq'")
1094            }
1095            None => discovery_backend.resolve_event_transport_kind()?,
1096        };
1097
1098        // Connect to NATS only when a plane uses it. NATS_SERVER alone says where NATS is, not
1099        // that this process needs it: the operator sets it in every pod when NATS is installed.
1100        let nats_enabled = request_plane.is_nats()
1101            || matches!(
1102                event_transport_kind,
1103                crate::discovery::EventTransportKind::Nats
1104            );
1105
1106        Ok(DistributedConfig {
1107            discovery_backend,
1108            nats_config: if nats_enabled {
1109                Some(nats::ClientOptions::default())
1110            } else {
1111                None
1112            },
1113            request_plane,
1114            response_plane: None,
1115            event_transport_kind,
1116        })
1117    }
1118
1119    pub fn for_cli() -> DistributedConfig {
1120        Self::try_for_cli().unwrap_or_else(|err| panic!("{err}"))
1121    }
1122
1123    pub fn try_for_cli() -> Result<DistributedConfig> {
1124        let etcd_config = etcd::ClientOptions {
1125            attach_lease: false,
1126            ..Default::default()
1127        };
1128        let request_plane = RequestPlaneMode::from_env()?;
1129        let discovery_backend =
1130            DiscoveryBackend::KvStore(kv::Selector::Etcd(Box::new(etcd_config)));
1131        let event_transport_kind = discovery_backend.resolve_event_transport_kind()?;
1132        let nats_enabled = request_plane.is_nats()
1133            || matches!(
1134                event_transport_kind,
1135                crate::discovery::EventTransportKind::Nats
1136            );
1137        Ok(DistributedConfig {
1138            discovery_backend,
1139            nats_config: if nats_enabled {
1140                Some(nats::ClientOptions::default())
1141            } else {
1142                None
1143            },
1144            request_plane,
1145            response_plane: None,
1146            event_transport_kind,
1147        })
1148    }
1149
1150    /// A DistributedConfig that isn't distributed, for when the frontend and backend are in the
1151    /// same process.
1152    pub fn process_local() -> DistributedConfig {
1153        DistributedConfig {
1154            discovery_backend: DiscoveryBackend::KvStore(kv::Selector::Memory),
1155            nats_config: None,
1156            // This won't be used in process local, so we likely need a "none" option to
1157            // communicate that and avoid opening the ports.
1158            request_plane: RequestPlaneMode::Tcp,
1159            response_plane: None,
1160            event_transport_kind: crate::discovery::EventTransportKind::Zmq,
1161        }
1162    }
1163}
1164
1165/// Request plane transport mode configuration
1166///
1167/// This determines how requests are distributed from routers to workers:
1168/// - `Nats`: Use NATS for request distribution (legacy)
1169/// - `Tcp`: Use raw TCP for request distribution with msgpack support (default)
1170#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1171pub enum RequestPlaneMode {
1172    /// Use NATS for request plane
1173    Nats,
1174    /// Use raw TCP for request plane with msgpack support
1175    #[default]
1176    Tcp,
1177}
1178
1179impl fmt::Display for RequestPlaneMode {
1180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181        match self {
1182            Self::Nats => write!(f, "nats"),
1183            Self::Tcp => write!(f, "tcp"),
1184        }
1185    }
1186}
1187
1188impl std::str::FromStr for RequestPlaneMode {
1189    type Err = anyhow::Error;
1190
1191    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1192        match s.to_lowercase().as_str() {
1193            "nats" => Ok(Self::Nats),
1194            "tcp" => Ok(Self::Tcp),
1195            _ => Err(anyhow::anyhow!(
1196                "Invalid request plane mode: '{}'. Valid options are: 'nats', 'tcp'",
1197                s
1198            )),
1199        }
1200    }
1201}
1202
1203impl RequestPlaneMode {
1204    fn from_env() -> Result<Self> {
1205        Self::from_env_result(std::env::var(
1206            crate::config::environment_names::request_plane::DYN_REQUEST_PLANE,
1207        ))
1208    }
1209
1210    fn from_env_result(value: std::result::Result<String, std::env::VarError>) -> Result<Self> {
1211        match value {
1212            Err(std::env::VarError::NotPresent) => Ok(Self::default()),
1213            Ok(s) => s.parse(),
1214            Err(std::env::VarError::NotUnicode(raw)) => Err(anyhow::anyhow!(
1215                "Invalid request plane mode: '{}' is not valid Unicode. \
1216                 Valid options are: 'nats', 'tcp'",
1217                raw.to_string_lossy()
1218            )),
1219        }
1220    }
1221
1222    pub fn is_nats(&self) -> bool {
1223        matches!(self, RequestPlaneMode::Nats)
1224    }
1225}
1226
1227#[cfg(test)]
1228mod request_plane_env_tests {
1229    use super::RequestPlaneMode;
1230
1231    #[test]
1232    fn absent_request_plane_defaults_to_tcp() {
1233        let mode = RequestPlaneMode::from_env_result(Err(std::env::VarError::NotPresent))
1234            .expect("an absent DYN_REQUEST_PLANE must not be an error");
1235        assert_eq!(mode, RequestPlaneMode::Tcp);
1236    }
1237
1238    #[test]
1239    fn empty_request_plane_is_an_error() {
1240        RequestPlaneMode::from_env_result(Ok(String::new()))
1241            .expect_err("an empty DYN_REQUEST_PLANE must not silently fall back to TCP");
1242    }
1243
1244    #[test]
1245    fn valid_request_plane_value_resolves() {
1246        let mode = RequestPlaneMode::from_env_result(Ok("nats".to_string()))
1247            .expect("DYN_REQUEST_PLANE=nats should resolve");
1248        assert_eq!(mode, RequestPlaneMode::Nats);
1249    }
1250
1251    #[test]
1252    fn invalid_request_plane_is_an_error_naming_value_and_options() {
1253        let err = RequestPlaneMode::from_env_result(Ok("nat".to_string()))
1254            .expect_err("a misspelled DYN_REQUEST_PLANE must not silently fall back to TCP");
1255        let message = err.to_string();
1256        assert!(
1257            message.contains("nat"),
1258            "error should name the offending value, got: {message}"
1259        );
1260        assert!(
1261            message.contains("'nats'") && message.contains("'tcp'"),
1262            "error should list the valid options, got: {message}"
1263        );
1264    }
1265
1266    #[cfg(unix)]
1267    #[test]
1268    fn non_unicode_request_plane_is_an_error_not_a_default() {
1269        use std::ffi::OsString;
1270        use std::os::unix::ffi::OsStringExt;
1271
1272        let raw = OsString::from_vec(b"nat\xff".to_vec());
1273        let err = RequestPlaneMode::from_env_result(Err(std::env::VarError::NotUnicode(raw)))
1274            .expect_err("a non-Unicode DYN_REQUEST_PLANE must not silently fall back to TCP");
1275        let message = err.to_string();
1276        assert!(
1277            message.contains("not valid Unicode"),
1278            "error should say the value was not valid Unicode, got: {message}"
1279        );
1280        assert!(
1281            message.contains("'nats'") && message.contains("'tcp'"),
1282            "error should list the valid options, got: {message}"
1283        );
1284    }
1285}
1286
1287#[cfg(test)]
1288mod event_plane_env_tests {
1289    use super::DiscoveryBackend;
1290    use crate::discovery::EventTransportKind;
1291
1292    fn resolve(
1293        value: std::result::Result<String, std::env::VarError>,
1294    ) -> anyhow::Result<EventTransportKind> {
1295        DiscoveryBackend::event_transport_kind_from_env_result(value)
1296    }
1297
1298    #[test]
1299    fn valid_event_plane_values_resolve_case_insensitively() {
1300        for (value, expected) in [
1301            ("nats", EventTransportKind::Nats),
1302            ("NATS", EventTransportKind::Nats),
1303            (" nats ", EventTransportKind::Nats),
1304            ("zmq", EventTransportKind::Zmq),
1305            ("Zmq", EventTransportKind::Zmq),
1306        ] {
1307            let kind = resolve(Ok(value.to_string()))
1308                .unwrap_or_else(|err| panic!("DYN_EVENT_PLANE={value:?} should resolve: {err}"));
1309            assert_eq!(kind, expected, "value {value:?}");
1310        }
1311    }
1312
1313    #[test]
1314    fn invalid_event_plane_is_an_error_naming_value_and_options() {
1315        for value in ["nat", "x"] {
1316            let err = resolve(Ok(value.to_string()))
1317                .expect_err("a misspelled DYN_EVENT_PLANE must not silently fall back to ZMQ");
1318            let message = err.to_string();
1319            assert!(
1320                message.contains(&format!("'{value}'")),
1321                "error should name the offending value, got: {message}"
1322            );
1323            assert!(
1324                message.contains("Valid values: 'nats', 'zmq'"),
1325                "error should list the valid values, got: {message}"
1326            );
1327        }
1328    }
1329
1330    #[cfg(unix)]
1331    #[test]
1332    fn non_unicode_event_plane_is_an_error_not_a_default() {
1333        use std::ffi::OsString;
1334        use std::os::unix::ffi::OsStringExt;
1335
1336        let raw = OsString::from_vec(b"nats\xff".to_vec());
1337        let err = resolve(Err(std::env::VarError::NotUnicode(raw)))
1338            .expect_err("a non-Unicode DYN_EVENT_PLANE must not silently fall back to ZMQ");
1339        assert!(
1340            err.to_string().contains("not valid Unicode"),
1341            "error should say the value was not valid Unicode, got: {err}"
1342        );
1343    }
1344}
1345
1346#[cfg(test)]
1347mod nats_enablement_tests {
1348    use super::DistributedConfig;
1349    use crate::config::environment_names::{event_plane::DYN_EVENT_PLANE, nats::NATS_SERVER};
1350
1351    #[test]
1352    fn ambient_nats_server_does_not_enable_nats_on_tcp_and_zmq() {
1353        if crate::test_utils::run_isolated(
1354            concat!(
1355                module_path!(),
1356                "::ambient_nats_server_does_not_enable_nats_on_tcp_and_zmq"
1357            ),
1358            &[(NATS_SERVER, "nats://127.0.0.1:9")],
1359        ) {
1360            return;
1361        }
1362
1363        temp_env::with_var_unset(DYN_EVENT_PLANE, || {
1364            let config =
1365                DistributedConfig::from_settings_with_overrides(Some("file"), Some("tcp"), None)
1366                    .unwrap();
1367            assert!(config.nats_config.is_none());
1368        });
1369    }
1370}
1371
1372pub mod distributed_test_utils {
1373    //! Common test helper functions for DistributedRuntime tests
1374
1375    /// Helper function to create a DRT instance for integration-only tests.
1376    /// Uses from_current to leverage existing tokio runtime
1377    /// Note: Settings are read from environment variables inside DistributedRuntime::from_settings
1378    #[cfg(feature = "integration")]
1379    pub async fn create_test_drt_async() -> super::DistributedRuntime {
1380        use crate::transports::nats;
1381
1382        let rt = crate::Runtime::from_current().unwrap();
1383        let config = super::DistributedConfig {
1384            discovery_backend: super::DiscoveryBackend::KvStore(
1385                crate::storage::kv::Selector::Memory,
1386            ),
1387            nats_config: Some(nats::ClientOptions::default()),
1388            request_plane: crate::distributed::RequestPlaneMode::default(),
1389            response_plane: None,
1390            event_transport_kind: crate::discovery::EventTransportKind::Nats,
1391        };
1392        super::DistributedRuntime::new(rt, config).await.unwrap()
1393    }
1394
1395    /// Helper function to create a DRT instance which points at
1396    /// a (shared) file-backed KV store and ephemeral NATS transport so that
1397    /// multiple DRT instances may observe the same registration state.
1398    /// NOTE: This gets around the fact that create_test_drt_async() is
1399    /// hardcoded to spin up a memory-backed discovery store
1400    /// which means we can't share discovery state across runtimes.
1401    pub async fn create_test_shared_drt_async(
1402        store_path: &std::path::Path,
1403    ) -> super::DistributedRuntime {
1404        use crate::transports::nats;
1405
1406        let rt = crate::Runtime::from_current().unwrap();
1407        let config = super::DistributedConfig {
1408            discovery_backend: super::DiscoveryBackend::KvStore(
1409                crate::storage::kv::Selector::File(store_path.to_path_buf()),
1410            ),
1411            nats_config: Some(nats::ClientOptions::default()),
1412            request_plane: crate::distributed::RequestPlaneMode::default(),
1413            response_plane: None,
1414            event_transport_kind: crate::discovery::EventTransportKind::Nats,
1415        };
1416        super::DistributedRuntime::new(rt, config).await.unwrap()
1417    }
1418}
1419
1420#[cfg(all(test, feature = "integration"))]
1421mod tests {
1422    use super::RequestPlaneMode;
1423    use super::distributed_test_utils::create_test_drt_async;
1424
1425    #[tokio::test]
1426    async fn test_drt_uptime_after_delay_system_disabled() {
1427        if crate::test_utils::run_isolated(
1428            concat!(
1429                module_path!(),
1430                "::test_drt_uptime_after_delay_system_disabled"
1431            ),
1432            &[],
1433        ) {
1434            return;
1435        }
1436
1437        use crate::config::environment_names::runtime::system as env_system;
1438        // Test uptime with system status server disabled
1439        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, None::<&str>)], async {
1440            // Start a DRT
1441            let drt = create_test_drt_async().await;
1442
1443            // Wait 50ms
1444            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
1445
1446            // Check that uptime is 50+ ms
1447            let uptime = drt.system_health.lock().uptime();
1448            assert!(
1449                uptime >= std::time::Duration::from_millis(50),
1450                "Expected uptime to be at least 50ms, but got {:?}",
1451                uptime
1452            );
1453
1454            println!(
1455                "✓ DRT uptime test passed (system disabled): uptime = {:?}",
1456                uptime
1457            );
1458        })
1459        .await;
1460    }
1461
1462    #[tokio::test]
1463    async fn test_drt_uptime_after_delay_system_enabled() {
1464        if crate::test_utils::run_isolated(
1465            concat!(
1466                module_path!(),
1467                "::test_drt_uptime_after_delay_system_enabled"
1468            ),
1469            &[],
1470        ) {
1471            return;
1472        }
1473
1474        use crate::config::environment_names::runtime::system as env_system;
1475        // Test uptime with system status server enabled
1476        temp_env::async_with_vars([(env_system::DYN_SYSTEM_PORT, Some("0"))], async {
1477            // Start a DRT
1478            let drt = create_test_drt_async().await;
1479
1480            // Wait 50ms
1481            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
1482
1483            // Check that uptime is 50+ ms
1484            let uptime = drt.system_health.lock().uptime();
1485            assert!(
1486                uptime >= std::time::Duration::from_millis(50),
1487                "Expected uptime to be at least 50ms, but got {:?}",
1488                uptime
1489            );
1490
1491            println!(
1492                "✓ DRT uptime test passed (system enabled): uptime = {:?}",
1493                uptime
1494            );
1495        })
1496        .await;
1497    }
1498
1499    #[test]
1500    fn test_request_plane_mode_from_str() {
1501        assert_eq!(
1502            "nats".parse::<RequestPlaneMode>().unwrap(),
1503            RequestPlaneMode::Nats
1504        );
1505        assert_eq!(
1506            "tcp".parse::<RequestPlaneMode>().unwrap(),
1507            RequestPlaneMode::Tcp
1508        );
1509        assert_eq!(
1510            "NATS".parse::<RequestPlaneMode>().unwrap(),
1511            RequestPlaneMode::Nats
1512        );
1513        assert_eq!(
1514            "TCP".parse::<RequestPlaneMode>().unwrap(),
1515            RequestPlaneMode::Tcp
1516        );
1517        assert!("invalid".parse::<RequestPlaneMode>().is_err());
1518    }
1519}