manager.rs 15 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// SPDX-License-Identifier: Apache-2.0

//! Network Manager - Single Source of Truth for Network Configuration
//!
//! This module consolidates ALL network-related configuration and creation logic.
//! It is the ONLY place in the codebase that:
//! - Reads environment variables for network configuration
//! - Knows about transport-specific types (SharedHttpServer, TcpRequestClient, etc.)
//! - Performs mode selection based on RequestPlaneMode
//! - Creates servers and clients
//!
//! The rest of the codebase works exclusively with trait objects and never
//! directly accesses transport implementations or configuration.

use super::egress::unified_client::RequestPlaneClient;
17
use super::ingress::shared_tcp_endpoint::SharedTcpServer;
18
use super::ingress::unified_server::RequestPlaneServer;
19
use crate::distributed::RequestPlaneMode;
20
21
22
use anyhow::Result;
use async_once_cell::OnceCell;
use std::sync::Arc;
23
use std::sync::OnceLock;
24
25
use tokio_util::sync::CancellationToken;

26
27
28
29
/// Global storage for the actual TCP RPC port after binding.
/// Uses OnceLock since the port is set once when the server binds and never changes.
static ACTUAL_TCP_RPC_PORT: OnceLock<u16> = OnceLock::new();

30
31
32
33
34
35
36
37
38
39
40
/// Global storage for the shared TCP server instance.
///
/// When multiple workers run in the same process, they must share a single TCP server
/// to ensure all endpoints are registered on the same server. Without this, each worker
/// would create its own server on a different port, but all would publish the same port
/// (from ACTUAL_TCP_RPC_PORT) to discovery, causing "No handler found" errors.
///
/// Uses `tokio::sync::OnceCell` to support async initialization (binding the TCP socket).
static GLOBAL_TCP_SERVER: tokio::sync::OnceCell<Arc<SharedTcpServer>> =
    tokio::sync::OnceCell::const_new();

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/// Get the actual TCP RPC port that the server is listening on.
pub fn get_actual_tcp_rpc_port() -> anyhow::Result<u16> {
    ACTUAL_TCP_RPC_PORT.get().copied().ok_or_else(|| {
        tracing::error!(
            "TCP RPC port not set - request_plane_server() must be called before get_actual_tcp_rpc_port()"
        );
        anyhow::anyhow!(
            "TCP RPC port not initialized. This is not expected."
        )
    })
}

/// Set the actual TCP RPC port (called internally after server binds).
fn set_actual_tcp_rpc_port(port: u16) {
    if let Err(existing) = ACTUAL_TCP_RPC_PORT.set(port) {
        tracing::warn!(
            existing_port = existing,
            new_port = port,
            "TCP RPC port already set, ignoring new value"
        );
    }
}

64
65
66
67
68
69
70
71
72
73
/// Network configuration loaded from environment variables
#[derive(Clone)]
struct NetworkConfig {
    // HTTP server configuration
    http_host: String,
    http_port: u16,
    http_rpc_root: String,

    // TCP server configuration
    tcp_host: String,
74
75
    /// TCP port to bind to. If None, the OS will assign a free port.
    tcp_port: Option<u16>,
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

    // HTTP client configuration
    http_client_config: super::egress::http_router::Http2Config,

    // TCP client configuration
    tcp_client_config: super::egress::tcp_client::TcpRequestConfig,

    // NATS configuration (provided externally, not from env)
    nats_client: Option<async_nats::Client>,
}

impl NetworkConfig {
    /// Load configuration from environment variables
    ///
    /// This is the ONLY place where network-related environment variables are read.
    fn from_env(nats_client: Option<async_nats::Client>) -> Self {
        Self {
            // HTTP server configuration
            http_host: std::env::var("DYN_HTTP_RPC_HOST")
                .unwrap_or_else(|_| crate::utils::get_http_rpc_host_from_env()),
            http_port: std::env::var("DYN_HTTP_RPC_PORT")
                .ok()
                .and_then(|p| p.parse().ok())
                .unwrap_or(8888),
            http_rpc_root: std::env::var("DYN_HTTP_RPC_ROOT_PATH")
                .unwrap_or_else(|_| "/v1/rpc".to_string()),

            // TCP server configuration
104
            // If DYN_TCP_RPC_PORT is set, use that port; otherwise None means OS will assign a free port
105
106
107
108
            tcp_host: std::env::var("DYN_TCP_RPC_HOST")
                .unwrap_or_else(|_| crate::utils::get_tcp_rpc_host_from_env()),
            tcp_port: std::env::var("DYN_TCP_RPC_PORT")
                .ok()
109
                .and_then(|p| p.parse().ok()),
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

            // HTTP client configuration (reads DYN_HTTP2_* env vars)
            http_client_config: super::egress::http_router::Http2Config::from_env(),

            // TCP client configuration (reads DYN_TCP_* env vars)
            tcp_client_config: super::egress::tcp_client::TcpRequestConfig::from_env(),

            // NATS (external)
            nats_client,
        }
    }
}

/// Network Manager - Central coordinator for all network resources
///
/// # Responsibilities
///
/// 1. **Configuration Management**: Reads and manages all network-related environment variables
/// 2. **Server Creation**: Creates and starts request plane servers based on mode
/// 3. **Client Creation**: Creates request plane clients on demand
/// 4. **Abstraction**: Hides all transport-specific details from the rest of the codebase
///
/// # Design Principles
///
/// - **Single Source of Truth**: All network config and creation logic lives here
/// - **Lazy Initialization**: Servers are created only when first accessed
/// - **Transport Agnostic Interface**: Exposes only trait objects to callers
/// - **No Leaky Abstractions**: Transport types never escape this module
///
/// # Example
///
/// ```ignore
/// // Create manager (typically done once in DistributedRuntime)
143
/// let manager = NetworkManager::new(cancel_token, nats_client, component_registry, request_plane_mode);
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
///
/// // Get server (lazy init, cached)
/// let server = manager.server().await?;
/// server.register_endpoint(...).await?;
///
/// // Create client (not cached, lightweight)
/// let client = manager.create_client()?;
/// client.send_request(...).await?;
/// ```
pub struct NetworkManager {
    mode: RequestPlaneMode,
    config: NetworkConfig,
    server: Arc<OnceCell<Arc<dyn RequestPlaneServer>>>,
    cancellation_token: CancellationToken,
    component_registry: crate::component::Registry,
}

impl NetworkManager {
    /// Create a new network manager
    ///
    /// This is the single constructor for NetworkManager. All configuration
    /// is loaded from environment variables internally.
    ///
    /// # Arguments
    ///
    /// * `cancellation_token` - Token for graceful shutdown of servers
    /// * `nats_client` - Optional NATS client (required only for NATS mode)
    /// * `component_registry` - Component registry to get NATS service groups from
    ///
    /// # Returns
    ///
    /// Returns an Arc-wrapped NetworkManager ready to create servers and clients.
    pub fn new(
        cancellation_token: CancellationToken,
        nats_client: Option<async_nats::Client>,
        component_registry: crate::component::Registry,
180
        mode: RequestPlaneMode,
181
    ) -> Self {
182
183
        let config = NetworkConfig::from_env(nats_client);

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        match mode {
            RequestPlaneMode::Http => {
                tracing::info!(
                    %mode,
                    host = %config.http_host,
                    port = config.http_port,
                    rpc_root = %config.http_rpc_root,
                    "Initializing NetworkManager with HTTP request plane"
                );
            }
            RequestPlaneMode::Tcp => {
                let port_display = config
                    .tcp_port
                    .map(|p| p.to_string())
                    .unwrap_or_else(|| "OS-assigned".to_string());
                tracing::info!(
                    %mode,
                    host = %config.tcp_host,
                    port = %port_display,
                    "Initializing NetworkManager with TCP request plane"
                );
            }
            RequestPlaneMode::Nats => {
                tracing::info!(
                    %mode,
                    "Initializing NetworkManager with NATS request plane"
                );
            }
        }
213

214
        Self {
215
216
217
218
219
            mode,
            config,
            server: Arc::new(OnceCell::new()),
            cancellation_token,
            component_registry,
220
        }
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    }

    /// Get or create the request plane server
    ///
    /// The server is created lazily on first access and cached for subsequent calls.
    /// The server is automatically started in the background.
    ///
    /// # Returns
    ///
    /// Returns a trait object that abstracts over HTTP/TCP/NATS implementations.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Server creation fails (e.g., port already in use)
    /// - NATS mode is selected but NATS client is not available
    /// - Configuration is invalid (e.g., malformed bind address)
    pub async fn server(&self) -> Result<Arc<dyn RequestPlaneServer>> {
        let server = self
            .server
            .get_or_try_init(async { self.create_server().await })
            .await?;

        Ok(server.clone())
    }

    /// Create a new request plane client
    ///
    /// Clients are lightweight and not cached. Each call creates a new client instance.
    ///
    /// # Returns
    ///
    /// Returns a trait object that abstracts over HTTP/TCP/NATS implementations.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Client creation fails (e.g., invalid configuration)
    /// - NATS mode is selected but NATS client is not available
    pub fn create_client(&self) -> Result<Arc<dyn RequestPlaneClient>> {
        match self.mode {
            RequestPlaneMode::Http => self.create_http_client(),
            RequestPlaneMode::Tcp => self.create_tcp_client(),
            RequestPlaneMode::Nats => self.create_nats_client(),
        }
    }

    /// Get the current request plane mode
    ///
    /// This is provided primarily for logging and debugging purposes.
    /// Application logic should not branch on mode - use trait objects instead.
    pub fn mode(&self) -> RequestPlaneMode {
        self.mode
    }

    // ============================================================================
    // PRIVATE: Server Creation
    // ============================================================================

    async fn create_server(&self) -> Result<Arc<dyn RequestPlaneServer>> {
        match self.mode {
            RequestPlaneMode::Http => self.create_http_server().await,
            RequestPlaneMode::Tcp => self.create_tcp_server().await,
            RequestPlaneMode::Nats => self.create_nats_server().await,
        }
    }

    async fn create_http_server(&self) -> Result<Arc<dyn RequestPlaneServer>> {
        use super::ingress::http_endpoint::SharedHttpServer;

        let bind_addr = format!("{}:{}", self.config.http_host, self.config.http_port)
            .parse()
            .map_err(|e| anyhow::anyhow!("Invalid HTTP bind address: {}", e))?;

        tracing::info!(
            bind_addr = %bind_addr,
            rpc_root = %self.config.http_rpc_root,
            "Creating HTTP request plane server"
        );

        let server = SharedHttpServer::new(bind_addr, self.cancellation_token.clone());

        // Start server in background
        let server_clone = server.clone();
        tokio::spawn(async move {
            if let Err(e) = server_clone.start().await {
                tracing::error!("HTTP request plane server error: {}", e);
            }
        });

        Ok(server as Arc<dyn RequestPlaneServer>)
    }

    async fn create_tcp_server(&self) -> Result<Arc<dyn RequestPlaneServer>> {
315
316
317
318
319
320
321
322
323
        // Use the global TCP server to ensure all workers in the same process share
        // a single server. This is critical for correct endpoint routing.
        let server = GLOBAL_TCP_SERVER
            .get_or_try_init(|| async {
                // Use configured port if specified, otherwise use port 0 (OS assigns free port)
                let port = self.config.tcp_port.unwrap_or(0);
                let bind_addr = format!("{}:{}", self.config.tcp_host, port)
                    .parse()
                    .map_err(|e| anyhow::anyhow!("Invalid TCP bind address: {}", e))?;
324

325
326
327
328
329
                tracing::info!(
                    bind_addr = %bind_addr,
                    port_source = if self.config.tcp_port.is_some() { "DYN_TCP_RPC_PORT" } else { "OS-assigned" },
                    "Creating TCP request plane server"
                );
330

331
                let server = SharedTcpServer::new(bind_addr, self.cancellation_token.clone());
332

333
334
                // Bind and start server, getting the actual bound address
                let actual_addr = server.clone().bind_and_start().await?;
335

336
337
                // Store the actual bound port globally so build_transport_type() can access it
                set_actual_tcp_rpc_port(actual_addr.port());
338

339
340
341
342
343
                tracing::info!(
                    actual_addr = %actual_addr,
                    actual_port = actual_addr.port(),
                    "TCP request plane server started"
                );
344

345
346
347
                Ok::<_, anyhow::Error>(server)
            })
            .await?;
348

349
        Ok(server.clone() as Arc<dyn RequestPlaneServer>)
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    }

    async fn create_nats_server(&self) -> Result<Arc<dyn RequestPlaneServer>> {
        use super::ingress::nats_server::NatsMultiplexedServer;

        let nats_client = self
            .config
            .nats_client
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("NATS client required for NATS mode"))?;

        tracing::info!("Creating NATS request plane server");

        Ok(NatsMultiplexedServer::new(
            nats_client.clone(),
            self.component_registry.clone(),
            self.cancellation_token.clone(),
        ) as Arc<dyn RequestPlaneServer>)
    }

    // ============================================================================
    // PRIVATE: Client Creation
    // ============================================================================

    fn create_http_client(&self) -> Result<Arc<dyn RequestPlaneClient>> {
        use super::egress::http_router::HttpRequestClient;

        tracing::debug!("Creating HTTP request plane client with config from NetworkManager");
        Ok(Arc::new(HttpRequestClient::with_config(
            self.config.http_client_config.clone(),
        )?))
    }

    fn create_tcp_client(&self) -> Result<Arc<dyn RequestPlaneClient>> {
        use super::egress::tcp_client::TcpRequestClient;

        tracing::debug!("Creating TCP request plane client with config from NetworkManager");
        Ok(Arc::new(TcpRequestClient::with_config(
            self.config.tcp_client_config.clone(),
        )?))
    }

    fn create_nats_client(&self) -> Result<Arc<dyn RequestPlaneClient>> {
        use super::egress::nats_client::NatsRequestClient;

        let nats_client = self
            .config
            .nats_client
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("NATS client required for NATS mode"))?;

        tracing::debug!("Creating NATS request plane client");
        Ok(Arc::new(NatsRequestClient::new(nats_client.clone())))
    }
}