"examples/backends/sample/launch/agg.sh" did not exist on "f3b181a9b1206da2847cfcc3a2cb5fa9e3f55da7"
endpoint.rs 12.1 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3

4
5
6
7
8
use std::sync::Arc;

use anyhow::Result;
pub use async_nats::service::endpoint::Stats as EndpointStats;
use derive_builder::Builder;
Ryan Olson's avatar
Ryan Olson committed
9
use derive_getters::Dissolve;
10
use educe::Educe;
11
use tokio_util::sync::CancellationToken;
Ryan Olson's avatar
Ryan Olson committed
12

13
14
use crate::{
    component::{Endpoint, Instance, TransportType, service::EndpointStatsHandler},
15
    distributed::RequestPlaneMode,
16
17
18
19
    pipeline::network::{PushWorkHandler, ingress::push_endpoint::PushEndpoint},
    storage::key_value_store,
    traits::DistributedRuntimeProvider,
};
20

Ryan Olson's avatar
Ryan Olson committed
21
22
23
24
25
26
27
28
29
30
#[derive(Educe, Builder, Dissolve)]
#[educe(Debug)]
#[builder(pattern = "owned", build_fn(private, name = "build_internal"))]
pub struct EndpointConfig {
    #[builder(private)]
    endpoint: Endpoint,

    /// Endpoint handler
    #[educe(Debug(ignore))]
    handler: Arc<dyn PushWorkHandler>,
31
32
33
34
35

    /// Stats handler
    #[educe(Debug(ignore))]
    #[builder(default, private)]
    _stats_handler: Option<EndpointStatsHandler>,
36

37
38
39
40
    /// Additional labels for metrics
    #[builder(default, setter(into))]
    metrics_labels: Option<Vec<(String, String)>>,

41
42
43
    /// Whether to wait for inflight requests to complete during shutdown
    #[builder(default = "true")]
    graceful_shutdown: bool,
44
45
46
47
48
49
50

    /// Health check payload for this endpoint
    /// This payload will be sent to the endpoint during health checks
    /// to verify it's responding properly
    #[educe(Debug(ignore))]
    #[builder(default, setter(into, strip_option))]
    health_check_payload: Option<serde_json::Value>,
Ryan Olson's avatar
Ryan Olson committed
51
52
53
54
55
56
57
}

impl EndpointConfigBuilder {
    pub(crate) fn from_endpoint(endpoint: Endpoint) -> Self {
        Self::default().endpoint(endpoint)
    }

58
59
    pub fn stats_handler<F>(self, handler: F) -> Self
    where
60
        F: FnMut(EndpointStats) -> serde_json::Value + Send + Sync + 'static,
61
62
63
64
    {
        self._stats_handler(Some(Box::new(handler)))
    }

Ryan Olson's avatar
Ryan Olson committed
65
    pub async fn start(self) -> Result<()> {
66
67
68
69
70
71
72
73
        let (
            endpoint,
            handler,
            stats_handler,
            metrics_labels,
            graceful_shutdown,
            health_check_payload,
        ) = self.build_internal()?.dissolve();
74
        let connection_id = endpoint.drt().connection_id();
Ryan Olson's avatar
Ryan Olson committed
75

76
77
        tracing::debug!(
            "Starting endpoint: {}",
78
            endpoint.etcd_path_with_lease_id(connection_id)
79
        );
Ryan Olson's avatar
Ryan Olson committed
80

81
82
        let service_name = endpoint.component.service_name();

83
84
85
        let metrics_labels: Option<Vec<(&str, &str)>> = metrics_labels
            .as_ref()
            .map(|v| v.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect());
86
        // Add metrics to the handler. The endpoint provides additional information to the handler.
87
        handler.add_metrics(&endpoint, metrics_labels.as_deref())?;
88

89
90
        let registry = endpoint.drt().component_registry().inner.lock().await;

91
92
93
        // Note: NATS service group is no longer needed here as the NetworkManager
        // handles all transport-specific initialization internally
        let _group = registry
Ryan Olson's avatar
Ryan Olson committed
94
            .services
95
            .get(&service_name)
Ryan Olson's avatar
Ryan Olson committed
96
            .map(|service| service.group(endpoint.component.service_name()))
97
            .ok_or(anyhow::anyhow!("Service not found"))?;
Ryan Olson's avatar
Ryan Olson committed
98

99
100
101
102
103
104
105
106
107
108
109
110
111
        // get the stats handler map
        let handler_map = registry
            .stats_handlers
            .get(&service_name)
            .cloned()
            .expect("no stats handler registry; this is unexpected");

        drop(registry);

        // insert the stats handler
        if let Some(stats_handler) = stats_handler {
            handler_map
                .lock()
112
                .insert(endpoint.subject_to(connection_id), stats_handler);
113
        }
Ryan Olson's avatar
Ryan Olson committed
114

115
        // Determine request plane mode
116
        let request_plane_mode = endpoint.drt().request_plane();
117
118
119
120
        tracing::info!(
            "Endpoint starting with request plane mode: {:?}",
            request_plane_mode
        );
Ryan Olson's avatar
Ryan Olson committed
121

122
123
124
        // This creates a child token of the runtime's endpoint_shutdown_token. That token is
        // cancelled first as part of graceful shutdown. See Runtime::shutdown.
        let endpoint_shutdown_token = endpoint.drt().child_token();
125
126
127
128
129

        // Extract all values needed from endpoint before any spawns
        let namespace_name = endpoint.component.namespace.name.clone();
        let component_name = endpoint.component.name.clone();
        let endpoint_name = endpoint.name.clone();
130
        let system_health = endpoint.drt().system_health();
131
        let subject = endpoint.subject_to(connection_id);
132

133
134
        // Register health check target in SystemHealth if provided
        if let Some(health_check_payload) = &health_check_payload {
135
136
137
138
139
140
141
142
            // Build transport based on request plane mode
            let transport = build_transport_type(
                request_plane_mode,
                &endpoint_name,
                &subject,
                TransportContext::HealthCheck,
            );

143
144
145
146
            let instance = Instance {
                component: component_name.clone(),
                endpoint: endpoint_name.clone(),
                namespace: namespace_name.clone(),
147
                instance_id: connection_id,
148
                transport,
149
            };
150
            tracing::debug!(endpoint_name = %endpoint_name, "Registering endpoint health check target");
151
            let guard = system_health.lock();
152
153
154
155
156
157
            guard.register_health_check_target(
                &endpoint_name,
                instance,
                health_check_payload.clone(),
            );
            if let Some(notifier) = guard.get_endpoint_health_check_notifier(&endpoint_name) {
158
159
160
161
                handler.set_endpoint_health_check_notifier(notifier)?;
            }
        }

162
163
164
165
166
167
168
169
170
171
172
        // Register with graceful shutdown tracker if needed
        if graceful_shutdown {
            tracing::debug!(
                "Registering endpoint '{}' with graceful shutdown tracker",
                endpoint.name
            );
            let tracker = endpoint.drt().graceful_shutdown_tracker();
            tracker.register_endpoint();
        } else {
            tracing::debug!("Endpoint '{}' has graceful_shutdown=false", endpoint.name);
        }
Ryan Olson's avatar
Ryan Olson committed
173

174
        // Launch endpoint based on request plane mode
175
176
177
178
179
180
181
182
183
184
185
        let tracker_clone = if graceful_shutdown {
            Some(endpoint.drt().graceful_shutdown_tracker())
        } else {
            None
        };

        // Create clones for the async closure
        let namespace_name_for_task = namespace_name.clone();
        let component_name_for_task = component_name.clone();
        let endpoint_name_for_task = endpoint_name.clone();

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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        // Get the unified request plane server (works for all transport types)
        let server = endpoint.drt().request_plane_server().await?;

        tracing::info!(
            endpoint = %endpoint_name_for_task,
            transport = server.transport_name(),
            "Registering endpoint with request plane server"
        );

        // Register endpoint with the server (unified interface)
        server
            .register_endpoint(
                endpoint_name_for_task.clone(),
                handler,
                connection_id,
                namespace_name_for_task.clone(),
                component_name_for_task.clone(),
                system_health.clone(),
            )
            .await?;

        // Create cleanup task that unregisters on cancellation
        let endpoint_name_for_cleanup = endpoint_name_for_task.clone();
        let server_for_cleanup = server.clone();
        let cancel_token_for_cleanup = endpoint_shutdown_token.clone();

        let task: tokio::task::JoinHandle<anyhow::Result<()>> = tokio::spawn(async move {
            cancel_token_for_cleanup.cancelled().await;

            tracing::debug!(
                endpoint = %endpoint_name_for_cleanup,
                "Unregistering endpoint from request plane server"
            );

            // Unregister from server
            if let Err(e) = server_for_cleanup
                .unregister_endpoint(&endpoint_name_for_cleanup)
                .await
            {
                tracing::warn!(
                    endpoint = %endpoint_name_for_cleanup,
                    error = %e,
                    "Failed to unregister endpoint"
                );
            }
231
232
233

            // Unregister from graceful shutdown tracker
            if let Some(tracker) = tracker_clone {
234
                tracing::debug!("Unregister endpoint from graceful shutdown tracker");
235
236
237
                tracker.unregister_endpoint();
            }

238
            anyhow::Ok(())
239
        });
Ryan Olson's avatar
Ryan Olson committed
240

241
242
243
244
245
        // Register this endpoint instance in the discovery plane
        // The discovery interface abstracts storage backend (etcd, k8s, etc) and provides
        // consistent registration/discovery across the system.
        let discovery = endpoint.drt().discovery();

246
247
248
249
250
251
252
253
        // Build transport for discovery service based on request plane mode
        let transport = build_transport_type(
            request_plane_mode,
            &endpoint_name,
            &subject,
            TransportContext::Discovery,
        );

254
255
        let discovery_spec = crate::discovery::DiscoverySpec::Endpoint {
            namespace: namespace_name.clone(),
256
257
            component: component_name.clone(),
            endpoint: endpoint_name.clone(),
258
            transport,
Ryan Olson's avatar
Ryan Olson committed
259
260
        };

261
        if let Err(e) = discovery.register(discovery_spec).await {
262
263
264
            tracing::error!(
                component_name,
                endpoint_name,
265
                error = %e,
266
267
                "Unable to register service for discovery"
            );
268
            endpoint_shutdown_token.cancel();
269
            anyhow::bail!(
270
                "Unable to register service for discovery. Check discovery service status"
271
            );
Ryan Olson's avatar
Ryan Olson committed
272
        }
273

Ryan Olson's avatar
Ryan Olson committed
274
275
276
277
278
        task.await??;

        Ok(())
    }
}
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341

/// Context for building transport type - determines port and formatting differences
enum TransportContext {
    /// For health check targets
    HealthCheck,
    /// For discovery service registration
    Discovery,
}

/// Build transport type based on request plane mode and context
///
/// This unified function handles both health check and discovery transport building,
/// with context-specific differences:
/// - HTTP: Both use the same port (default 8888, configurable via DYN_HTTP_RPC_PORT)
/// - TCP: Health check omits endpoint suffix, discovery includes it for routing
/// - NATS: Identical for both contexts
fn build_transport_type(
    mode: RequestPlaneMode,
    endpoint_name: &str,
    subject: &str,
    context: TransportContext,
) -> TransportType {
    match mode {
        RequestPlaneMode::Http => {
            let http_host = crate::utils::get_http_rpc_host_from_env();
            // Both health check and discovery use the same port (8888) where the HTTP server binds
            let http_port = std::env::var("DYN_HTTP_RPC_PORT")
                .ok()
                .and_then(|p| p.parse::<u16>().ok())
                .unwrap_or(8888);
            let rpc_root =
                std::env::var("DYN_HTTP_RPC_ROOT_PATH").unwrap_or_else(|_| "/v1/rpc".to_string());

            let http_endpoint = format!(
                "http://{}:{}{}/{}",
                http_host, http_port, rpc_root, endpoint_name
            );

            TransportType::Http(http_endpoint)
        }
        RequestPlaneMode::Tcp => {
            let tcp_host = crate::utils::get_tcp_rpc_host_from_env();
            let tcp_port = std::env::var("DYN_TCP_RPC_PORT")
                .ok()
                .and_then(|p| p.parse::<u16>().ok())
                .unwrap_or(9999);

            let tcp_endpoint = match context {
                TransportContext::HealthCheck => {
                    // Health check uses simple host:port format
                    format!("{}:{}", tcp_host, tcp_port)
                }
                TransportContext::Discovery => {
                    // Discovery includes endpoint name for routing
                    format!("{}:{}/{}", tcp_host, tcp_port, endpoint_name)
                }
            };

            TransportType::Tcp(tcp_endpoint)
        }
        RequestPlaneMode::Nats => TransportType::Nats(subject.to_string()),
    }
}