streaming_tests.rs 10.1 KB
Newer Older
1
2
mod common;

3
4
use std::sync::Arc;

5
use common::mock_worker::{HealthStatus, MockWorker, MockWorkerConfig, WorkerType};
6
use futures_util::StreamExt;
7
8
use reqwest::Client;
use serde_json::json;
9
10
11
12
use sglang_router_rs::{
    config::{RouterConfig, RoutingMode},
    routers::{RouterFactory, RouterTrait},
};
13

14
15
/// Test context that manages mock workers
struct TestContext {
16
    workers: Vec<MockWorker>,
17
18
    _router: Arc<dyn RouterTrait>,
    worker_urls: Vec<String>,
19
20
}

21
impl TestContext {
22
    async fn new(worker_configs: Vec<MockWorkerConfig>) -> Self {
23
24
25
26
27
28
        let mut config = RouterConfig::builder()
            .regular_mode(vec![])
            .port(3004)
            .worker_startup_timeout_secs(1)
            .worker_startup_check_interval_secs(1)
            .build_unchecked();
29

30
31
        let mut workers = Vec::new();
        let mut worker_urls = Vec::new();
32

33
34
35
36
37
38
        for worker_config in worker_configs {
            let mut worker = MockWorker::new(worker_config);
            let url = worker.start().await.unwrap();
            worker_urls.push(url);
            workers.push(worker);
        }
39

40
41
        if !workers.is_empty() {
            tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
42
43
        }

44
45
46
47
48
49
        config.mode = RoutingMode::Regular {
            worker_urls: worker_urls.clone(),
        };

        let app_context = common::create_test_context(config.clone());

50
        let router = RouterFactory::create_router(&app_context).await.unwrap();
51
        let router = Arc::from(router);
52

53
54
55
56
        if !workers.is_empty() {
            tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
        }

57
58
59
60
61
        Self {
            workers,
            _router: router,
            worker_urls: worker_urls.clone(),
        }
62
63
64
    }

    async fn shutdown(mut self) {
65
66
67
        // Small delay to ensure any pending operations complete
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

68
69
70
71
        for worker in &mut self.workers {
            worker.stop().await;
        }

72
73
74
        // Another small delay to ensure cleanup completes
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }
75

76
77
78
79
80
81
82
    async fn make_streaming_request(
        &self,
        endpoint: &str,
        body: serde_json::Value,
    ) -> Result<Vec<String>, String> {
        let client = Client::new();

83
84
85
86
87
        // Use the first worker URL from the context
        let worker_url = self
            .worker_urls
            .first()
            .ok_or_else(|| "No workers available".to_string())?;
88

89
        let response = client
90
            .post(format!("{}{}", worker_url, endpoint))
91
92
93
94
            .json(&body)
            .send()
            .await
            .map_err(|e| format!("Request failed: {}", e))?;
95

96
97
98
        if !response.status().is_success() {
            return Err(format!("Request failed with status: {}", response.status()));
        }
99

100
101
102
103
104
105
        // Check if it's a streaming response
        let content_type = response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
106

107
108
109
        if !content_type.contains("text/event-stream") {
            return Err("Response is not a stream".to_string());
        }
110

111
112
        let mut stream = response.bytes_stream();
        let mut events = Vec::new();
113

114
115
116
117
        while let Some(chunk) = stream.next().await {
            if let Ok(bytes) = chunk {
                let text = String::from_utf8_lossy(&bytes);
                for line in text.lines() {
118
119
                    if let Some(stripped) = line.strip_prefix("data: ") {
                        events.push(stripped.to_string());
120
121
122
123
                    }
                }
            }
        }
124

125
        Ok(events)
126
    }
127
}
128

129
130
131
#[cfg(test)]
mod streaming_tests {
    use super::*;
132

133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    #[tokio::test]
    async fn test_generate_streaming() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20001,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 10,
            fail_rate: 0.0,
        }])
        .await;

        let payload = json!({
            "text": "Stream test",
            "stream": true,
            "sampling_params": {
                "temperature": 0.7,
                "max_new_tokens": 10
            }
151
152
        });

153
154
        let result = ctx.make_streaming_request("/generate", payload).await;
        assert!(result.is_ok());
155

156
157
158
159
        let events = result.unwrap();
        // Should have at least one data chunk and [DONE]
        assert!(events.len() >= 2);
        assert_eq!(events.last().unwrap(), "[DONE]");
160

161
162
        ctx.shutdown().await;
    }
163

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    #[tokio::test]
    async fn test_v1_chat_completions_streaming() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20002,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 10,
            fail_rate: 0.0,
        }])
        .await;

        let payload = json!({
            "model": "test-model",
            "messages": [
                {"role": "user", "content": "Count to 3"}
            ],
            "stream": true,
            "max_tokens": 20
182
183
        });

184
185
        let result = ctx
            .make_streaming_request("/v1/chat/completions", payload)
186
            .await;
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        assert!(result.is_ok());

        let events = result.unwrap();
        assert!(events.len() >= 2); // At least one chunk + [DONE]

        for event in &events {
            if event != "[DONE]" {
                let parsed: Result<serde_json::Value, _> = serde_json::from_str(event);
                assert!(parsed.is_ok(), "Invalid JSON in SSE event: {}", event);

                let json = parsed.unwrap();
                assert_eq!(
                    json.get("object").and_then(|v| v.as_str()),
                    Some("chat.completion.chunk")
                );
            }
        }
204

205
        ctx.shutdown().await;
206
207
    }

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
    #[tokio::test]
    async fn test_v1_completions_streaming() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20003,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 10,
            fail_rate: 0.0,
        }])
        .await;

        let payload = json!({
            "model": "test-model",
            "prompt": "Once upon a time",
            "stream": true,
            "max_tokens": 15
224
225
        });

226
227
        let result = ctx.make_streaming_request("/v1/completions", payload).await;
        assert!(result.is_ok());
228

229
230
        let events = result.unwrap();
        assert!(events.len() >= 2); // At least one chunk + [DONE]
231

232
233
        ctx.shutdown().await;
    }
234

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    #[tokio::test]
    async fn test_streaming_with_error() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20004,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 0,
            fail_rate: 1.0, // Always fail
        }])
        .await;

        let payload = json!({
            "text": "This should fail",
            "stream": true
        });
250

251
252
253
        let result = ctx.make_streaming_request("/generate", payload).await;
        // With fail_rate: 1.0, the request should fail
        assert!(result.is_err());
254

255
256
        ctx.shutdown().await;
    }
257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    #[tokio::test]
    async fn test_streaming_timeouts() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20005,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 100, // Slow response
            fail_rate: 0.0,
        }])
        .await;

        let payload = json!({
            "text": "Slow stream",
            "stream": true,
            "sampling_params": {
                "max_new_tokens": 5
274
275
276
            }
        });

277
278
279
        let start = std::time::Instant::now();
        let result = ctx.make_streaming_request("/generate", payload).await;
        let elapsed = start.elapsed();
280

281
282
        assert!(result.is_ok());
        let events = result.unwrap();
283

284
285
286
        // Should have received multiple chunks over time
        assert!(!events.is_empty());
        assert!(elapsed.as_millis() >= 100); // At least one delay
287

288
        ctx.shutdown().await;
289
290
    }

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    #[tokio::test]
    async fn test_batch_streaming() {
        let ctx = TestContext::new(vec![MockWorkerConfig {
            port: 20006,
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 10,
            fail_rate: 0.0,
        }])
        .await;

        // Batch request with streaming
        let payload = json!({
            "text": ["First", "Second", "Third"],
            "stream": true,
            "sampling_params": {
                "max_new_tokens": 5
            }
309
310
        });

311
312
        let result = ctx.make_streaming_request("/generate", payload).await;
        assert!(result.is_ok());
313

314
315
316
        let events = result.unwrap();
        // Should have multiple events for batch
        assert!(events.len() >= 4); // At least 3 responses + [DONE]
317

318
        ctx.shutdown().await;
319
320
    }

321
322
323
324
325
326
327
328
329
    #[tokio::test]
    async fn test_sse_format_parsing() {
        let parse_sse_chunk = |chunk: &[u8]| -> Vec<String> {
            let text = String::from_utf8_lossy(chunk);
            text.lines()
                .filter(|line| line.starts_with("data: "))
                .map(|line| line[6..].to_string())
                .collect()
        };
330

331
332
333
        let sse_data =
            b"data: {\"text\":\"Hello\"}\n\ndata: {\"text\":\" world\"}\n\ndata: [DONE]\n\n";
        let events = parse_sse_chunk(sse_data);
334

335
336
337
338
        assert_eq!(events.len(), 3);
        assert_eq!(events[0], "{\"text\":\"Hello\"}");
        assert_eq!(events[1], "{\"text\":\" world\"}");
        assert_eq!(events[2], "[DONE]");
339

340
341
        let mixed = b"event: message\ndata: {\"test\":true}\n\n: comment\ndata: [DONE]\n\n";
        let events = parse_sse_chunk(mixed);
342

343
344
345
        assert_eq!(events.len(), 2);
        assert_eq!(events[0], "{\"test\":true}");
        assert_eq!(events[1], "[DONE]");
346
347
    }
}