endpoint.rs 9.23 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
use std::{future::Future, pin::Pin, sync::Arc};
5

6
use crate::{
7
    backend::Backend,
8
    engines::StreamingEngineAdapter,
9
    model_type::ModelType,
10
    preprocessor::{BackendOutput, PreprocessedRequest},
11
    types::{
12
13
14
        openai::chat_completions::{
            NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
        },
15
16
        Annotated,
    },
17
};
18
use dynamo_runtime::engine::AsyncEngineStream;
Neelay Shah's avatar
Neelay Shah committed
19
use dynamo_runtime::pipeline::{
20
    network::Ingress, Context, ManyOut, Operator, SegmentSource, ServiceBackend, SingleIn, Source,
21
};
22
use dynamo_runtime::{protocols::Endpoint as EndpointId, DistributedRuntime};
23

24
use crate::entrypoint::EngineConfig;
25
26

pub async fn run(
27
    distributed_runtime: DistributedRuntime,
28
29
30
    path: String,
    engine_config: EngineConfig,
) -> anyhow::Result<()> {
31
    let cancel_token = distributed_runtime.primary_token().clone();
32
    let endpoint_id: EndpointId = path.parse()?;
33

34
35
36
37
38
39
40
41
42
    let component = distributed_runtime
        .namespace(&endpoint_id.namespace)?
        .component(&endpoint_id.component)?;
    let endpoint = component
        .service_builder()
        .create()
        .await?
        .endpoint(&endpoint_id.name);

43
44
    let (rt_fut, card): (Pin<Box<dyn Future<Output = _> + Send + 'static>>, _) = match engine_config
    {
45
46
47
48
49
        EngineConfig::StaticFull {
            engine,
            mut model,
            is_static,
        } => {
50
            let engine = Arc::new(StreamingEngineAdapter::new(engine));
51
52
53
54
55
            let ingress_chat = Ingress::<
                Context<NvCreateChatCompletionRequest>,
                Pin<Box<dyn AsyncEngineStream<Annotated<NvCreateChatCompletionStreamResponse>>>>,
            >::for_engine(engine)?;

56
57
58
            if !is_static {
                model.attach(&endpoint, ModelType::Chat).await?;
            }
59
60
            let fut_chat = endpoint.endpoint_builder().handler(ingress_chat).start();

61
            (Box::pin(fut_chat), Some(model.card().clone()))
62
        }
63
64
        EngineConfig::StaticCore {
            engine: inner_engine,
65
            mut model,
66
            is_static,
67
        } => {
68
            // Pre-processing is done ingress-side, so it should be already done.
69
70
71
72
            let frontend = SegmentSource::<
                SingleIn<PreprocessedRequest>,
                ManyOut<Annotated<BackendOutput>>,
            >::new();
73
74
75
            let backend = Backend::from_mdc(model.card().clone())
                .await?
                .into_operator();
76
77
78
79
80
81
            let engine = ServiceBackend::from_engine(inner_engine);
            let pipeline = frontend
                .link(backend.forward_edge())?
                .link(engine)?
                .link(backend.backward_edge())?
                .link(frontend)?;
82
            let ingress = Ingress::for_pipeline(pipeline)?;
83

84
85
86
            if !is_static {
                model.attach(&endpoint, ModelType::Backend).await?;
            }
87
88
            let fut = endpoint.endpoint_builder().handler(ingress).start();

89
            (Box::pin(fut), Some(model.card().clone()))
90
        }
91
92
93
        EngineConfig::StaticRemote(_) => {
            panic!("StaticRemote definitions are only for the frontend end node.");
        }
94
        EngineConfig::Dynamic(_) => {
95
            unreachable!("An endpoint input will never have a Dynamic engine");
96
        }
97
98
    };

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    // Capture the actual error from rt_fut when it completes
    // Note: We must return rt_result to propagate the actual error back to the user.
    // If we don't return the specific error, the programmer/user won't know what actually
    // caused the endpoint service to fail, making debugging much more difficult.
    let result = tokio::select! {
        rt_result = rt_fut => {
            tracing::debug!("Endpoint service completed");
            match rt_result {
                Ok(_) => {
                    tracing::warn!("Endpoint service completed unexpectedly for endpoint: {}", path);
                    Err(anyhow::anyhow!("Endpoint service completed unexpectedly for endpoint: {}", path))
                }
                Err(e) => {
                    tracing::error!(%e, "Endpoint service failed for endpoint: {} - Error: {}", path, e);
                    Err(anyhow::anyhow!("Endpoint service failed for endpoint: {} - Error: {}", path, e))
                }
            }
116
117
        }
        _ = cancel_token.cancelled() => {
118
119
            tracing::debug!("Endpoint service cancelled");
            Ok(())
120
        }
121
122
123
124
    };

    // If we got an error, return it
    result?;
125
126

    // Cleanup on shutdown
127
128
129
130
131
132
133
    if let Some(mut card) = card {
        if let Err(err) = card
            .delete_from_nats(distributed_runtime.nats_client())
            .await
        {
            tracing::error!(%err, "delete_from_nats error on shutdown");
        }
134
135
136
137
    }

    Ok(())
}
138
139
140
141
142
143
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
180
181
182
183
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
213
214
215
216
217
218
219
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

#[cfg(test)]
#[cfg(feature = "integration")]
mod integration_tests {
    use super::*;
    use dynamo_runtime::protocols::Endpoint as EndpointId;

    async fn create_test_environment() -> anyhow::Result<(DistributedRuntime, EngineConfig)> {
        // Create a minimal distributed runtime and engine config for testing
        let runtime = dynamo_runtime::Runtime::from_settings()
            .map_err(|e| anyhow::anyhow!("Failed to create runtime: {}", e))?;

        let distributed_runtime = dynamo_runtime::DistributedRuntime::from_settings(runtime)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to create distributed runtime: {}", e))?;

        let engine_config = EngineConfig::StaticCore {
            engine: crate::engines::make_engine_core(),
            model: Box::new(
                crate::local_model::LocalModelBuilder::default()
                    .model_name(Some("test-model".to_string()))
                    .build()
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to build LocalModel: {}", e))?,
            ),
        };

        Ok((distributed_runtime, engine_config))
    }

    #[tokio::test]
    async fn test_run_function_valid_endpoint() {
        // Test that run() works correctly with valid endpoints

        let (runtime, engine_config) = match create_test_environment().await {
            Ok(env) => env,
            Err(e) => {
                eprintln!("Skipping test: {}", e);
                return;
            }
        };

        // Test with valid endpoint - start the service and then connect to it
        let valid_path = "dyn://valid-endpoint.mocker.generate";
        let valid_endpoint: EndpointId = valid_path.parse().expect("Valid endpoint should parse");

        let runtime_clone = runtime.clone();
        let engine_config_clone = engine_config.clone();
        let valid_path_clone = valid_path.to_string();

        let service_handle =
            tokio::spawn(
                async move { run(runtime_clone, valid_path_clone, engine_config_clone).await },
            );

        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let client_result = async {
            let namespace = runtime.namespace(&valid_endpoint.namespace)?;
            let component = namespace.component(&valid_endpoint.component)?;
            let client = component.endpoint(&valid_endpoint.name).client().await?;
            client.wait_for_instances().await?;
            Ok::<_, anyhow::Error>(client)
        }
        .await;

        match client_result {
            Ok(_client) => {
                println!("Valid endpoint: Successfully connected to service");
                service_handle.abort(); // Abort the service since we've verified it works
            }
            Err(e) => {
                println!("Valid endpoint: Failed to connect to service: {}", e);
                service_handle.abort(); // Abort the service since the test failed
                panic!(
                    "Valid endpoint should allow client connections, but failed: {}",
                    e
                );
            }
        }
    }

    #[tokio::test]
    #[ignore = "DistributedRuntime drop issue persists - test logic validates error propagation correctly"]
    async fn test_run_function_invalid_endpoint() {
        // Test that invalid endpoints fail validation during run()
        let invalid_path = "dyn://@@@123.mocker.generate";

        // Create test environment
        let (runtime, engine_config) = create_test_environment()
            .await
            .expect("Failed to create test environment");

        // Call run() directly - it should fail quickly for invalid endpoints
        let result = run(runtime, invalid_path.to_string(), engine_config).await;

        // Should return an error for invalid endpoints
        assert!(
            result.is_err(),
            "run() should fail for invalid endpoint: {:?}",
            result
        );

        // Check that the error message contains validation-related keywords
        let error_msg = result.unwrap_err().to_string().to_lowercase();
        assert!(
            error_msg.contains("invalid")
                || error_msg.contains("namespace")
                || error_msg.contains("validation")
                || error_msg.contains("failed"),
            "Error message should contain validation keywords, got: {}",
            error_msg
        );
    }
}