mock_worker.rs 17.7 KB
Newer Older
1
2
3
// Mock worker for testing - these functions are used by integration tests
#![allow(dead_code)]

4
5
6
7
8
9
10
11
12
use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::sse::{Event, KeepAlive},
    response::{IntoResponse, Response, Sse},
    routing::{get, post},
    Router,
};
use futures_util::stream::{self, StreamExt};
13
use serde_json::json;
14
use std::convert::Infallible;
15
16
17
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
18
use uuid::Uuid;
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

/// Configuration for mock worker behavior
#[derive(Clone)]
pub struct MockWorkerConfig {
    pub port: u16,
    pub worker_type: WorkerType,
    pub health_status: HealthStatus,
    pub response_delay_ms: u64,
    pub fail_rate: f32,
}

#[derive(Clone, Debug)]
pub enum WorkerType {
    Regular,
    Prefill,
    Decode,
}

#[derive(Clone, Debug)]
pub enum HealthStatus {
    Healthy,
    Unhealthy,
    Degraded,
}

/// Mock worker server for testing
pub struct MockWorker {
    config: Arc<RwLock<MockWorkerConfig>>,
47
48
    shutdown_handle: Option<tokio::task::JoinHandle<()>>,
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
49
50
51
52
53
54
}

impl MockWorker {
    pub fn new(config: MockWorkerConfig) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
55
56
            shutdown_handle: None,
            shutdown_tx: None,
57
58
59
60
61
62
63
64
        }
    }

    /// Start the mock worker server
    pub async fn start(&mut self) -> Result<String, Box<dyn std::error::Error>> {
        let config = self.config.clone();
        let port = config.read().await.port;

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        // If port is 0, find an available port
        let port = if port == 0 {
            let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
            let port = listener.local_addr()?.port();
            drop(listener);
            config.write().await.port = port;
            port
        } else {
            port
        };

        let app = Router::new()
            .route("/health", get(health_handler))
            .route("/health_generate", get(health_generate_handler))
            .route("/get_server_info", get(server_info_handler))
            .route("/get_model_info", get(model_info_handler))
            .route("/generate", post(generate_handler))
            .route("/v1/chat/completions", post(chat_completions_handler))
            .route("/v1/completions", post(completions_handler))
            .route("/flush_cache", post(flush_cache_handler))
            .route("/v1/models", get(v1_models_handler))
            .with_state(config);

        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
        self.shutdown_tx = Some(shutdown_tx);

        // Spawn the server in a separate task
        let handle = tokio::spawn(async move {
            let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await {
                Ok(l) => l,
                Err(e) => {
                    eprintln!("Failed to bind to port {}: {}", port, e);
                    return;
                }
            };
100

101
102
103
104
105
106
107
108
            let server = axum::serve(listener, app).with_graceful_shutdown(async move {
                let _ = shutdown_rx.await;
            });

            if let Err(e) = server.await {
                eprintln!("Server error: {}", e);
            }
        });
109

110
        self.shutdown_handle = Some(handle);
111

112
113
114
115
116
        // Wait for the server to start
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        let url = format!("http://127.0.0.1:{}", port);
        Ok(url)
117
118
119
120
    }

    /// Stop the mock worker server
    pub async fn stop(&mut self) {
121
122
123
124
125
126
127
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }

        if let Some(handle) = self.shutdown_handle.take() {
            // Wait for the server to shut down
            let _ = tokio::time::timeout(tokio::time::Duration::from_secs(5), handle).await;
128
129
        }
    }
130
}
131

132
133
134
135
136
137
impl Drop for MockWorker {
    fn drop(&mut self) {
        // Clean shutdown when dropped
        if let Some(shutdown_tx) = self.shutdown_tx.take() {
            let _ = shutdown_tx.send(());
        }
138
139
140
141
142
    }
}

// Handler implementations

143
144
145
146
147
/// Check if request should fail based on configured fail_rate
async fn should_fail(config: &MockWorkerConfig) -> bool {
    rand::random::<f32>() < config.fail_rate
}

148
async fn health_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
149
150
151
    let config = config.read().await;

    match config.health_status {
152
        HealthStatus::Healthy => Json(json!({
153
154
155
            "status": "healthy",
            "timestamp": SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
            "worker_type": format!("{:?}", config.worker_type),
156
157
158
159
160
161
162
163
164
165
166
        }))
        .into_response(),
        HealthStatus::Unhealthy => (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({
                "status": "unhealthy",
                "error": "Worker is not responding"
            })),
        )
            .into_response(),
        HealthStatus::Degraded => Json(json!({
167
168
            "status": "degraded",
            "warning": "High load detected"
169
170
        }))
        .into_response(),
171
172
173
    }
}

174
async fn health_generate_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
175
176
    let config = config.read().await;

177
    if should_fail(&config).await {
178
179
180
181
182
183
184
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Random failure for testing"
            })),
        )
            .into_response();
185
186
    }

187
    if matches!(config.health_status, HealthStatus::Healthy) {
188
        Json(json!({
189
190
191
192
            "status": "ok",
            "queue_length": 0,
            "processing_time_ms": config.response_delay_ms
        }))
193
        .into_response()
194
    } else {
195
196
197
198
199
200
201
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({
                "error": "Generation service unavailable"
            })),
        )
            .into_response()
202
203
204
    }
}

205
async fn server_info_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
206
207
    let config = config.read().await;

208
    if should_fail(&config).await {
209
210
211
212
213
214
215
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Random failure for testing"
            })),
        )
            .into_response();
216
217
    }

218
    Json(json!({
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
253
        "model_path": "mock-model-path",
        "tokenizer_path": "mock-tokenizer-path",
        "port": config.port,
        "host": "127.0.0.1",
        "max_num_batched_tokens": 32768,
        "max_prefill_tokens": 16384,
        "mem_fraction_static": 0.88,
        "tp_size": 1,
        "dp_size": 1,
        "stream_interval": 8,
        "dtype": "float16",
        "device": "cuda",
        "enable_flashinfer": true,
        "enable_p2p_check": true,
        "context_length": 32768,
        "chat_template": null,
        "disable_radix_cache": false,
        "enable_torch_compile": false,
        "trust_remote_code": false,
        "show_time_cost": false,
        "waiting_queue_size": 0,
        "running_queue_size": 0,
        "req_to_token_ratio": 1.2,
        "min_running_requests": 0,
        "max_running_requests": 2048,
        "max_req_num": 8192,
        "max_batch_tokens": 32768,
        "schedule_policy": "lpm",
        "schedule_conservativeness": 1.0,
        "version": "0.3.0",
        "internal_states": [{
            "waiting_queue_size": 0,
            "running_queue_size": 0
        }]
    }))
254
    .into_response()
255
256
}

257
async fn model_info_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
258
259
260
    let config = config.read().await;

    if should_fail(&config).await {
261
262
263
264
265
266
267
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Random failure for testing"
            })),
        )
            .into_response();
268
269
    }

270
    Json(json!({
271
272
273
274
275
276
277
278
279
280
        "model_path": "mock-model-path",
        "tokenizer_path": "mock-tokenizer-path",
        "is_generation": true,
        "preferred_sampling_params": {
            "temperature": 0.7,
            "top_p": 0.9,
            "top_k": 40,
            "max_tokens": 2048
        }
    }))
281
    .into_response()
282
283
284
}

async fn generate_handler(
285
286
287
    State(config): State<Arc<RwLock<MockWorkerConfig>>>,
    Json(payload): Json<serde_json::Value>,
) -> Response {
288
289
    let config = config.read().await;

290
    if should_fail(&config).await {
291
292
293
294
295
296
297
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Random failure for testing"
            })),
        )
            .into_response();
298
299
300
301
302
303
304
305
306
307
308
309
310
311
    }

    if config.response_delay_ms > 0 {
        tokio::time::sleep(tokio::time::Duration::from_millis(config.response_delay_ms)).await;
    }

    let is_stream = payload
        .get("stream")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    if is_stream {
        let stream_delay = config.response_delay_ms;

312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        // Check if it's a batch request
        let is_batch = payload.get("text").and_then(|t| t.as_array()).is_some();

        let batch_size = if is_batch {
            payload
                .get("text")
                .and_then(|t| t.as_array())
                .map(|arr| arr.len())
                .unwrap_or(1)
        } else {
            1
        };

        let mut events = Vec::new();

        // Generate events for each item in batch
        for i in 0..batch_size {
329
330
331
332
            let timestamp_start = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs_f64();
333

334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
            let data = json!({
                "text": format!("Mock response {}", i + 1),
                "meta_info": {
                    "prompt_tokens": 10,
                    "completion_tokens": 5,
                    "completion_tokens_wo_jump_forward": 5,
                    "input_token_logprobs": null,
                    "output_token_logprobs": null,
                    "first_token_latency": stream_delay as f64 / 1000.0,
                    "time_to_first_token": stream_delay as f64 / 1000.0,
                    "time_per_output_token": 0.01,
                    "end_time": timestamp_start + (stream_delay as f64 / 1000.0),
                    "start_time": timestamp_start,
                    "finish_reason": {
                        "type": "stop",
                        "reason": "length"
350
                    }
351
352
353
                },
                "stage": "mid"
            });
354

355
356
            events.push(Ok::<_, Infallible>(Event::default().data(data.to_string())));
        }
357

358
359
        // Add [DONE] event
        events.push(Ok(Event::default().data("[DONE]")));
360

361
        let stream = stream::iter(events);
362

363
364
365
        Sse::new(stream)
            .keep_alive(KeepAlive::default())
            .into_response()
366
    } else {
367
368
        Json(json!({
            "text": "This is a mock response.",
369
            "meta_info": {
370
371
372
373
374
375
376
377
                "prompt_tokens": 10,
                "completion_tokens": 5,
                "completion_tokens_wo_jump_forward": 5,
                "input_token_logprobs": null,
                "output_token_logprobs": null,
                "first_token_latency": config.response_delay_ms as f64 / 1000.0,
                "time_to_first_token": config.response_delay_ms as f64 / 1000.0,
                "time_per_output_token": 0.01,
378
379
                "finish_reason": {
                    "type": "stop",
380
381
                    "reason": "length"
                }
382
383
            }
        }))
384
        .into_response()
385
386
387
388
    }
}

async fn chat_completions_handler(
389
390
391
    State(config): State<Arc<RwLock<MockWorkerConfig>>>,
    Json(payload): Json<serde_json::Value>,
) -> Response {
392
393
    let config = config.read().await;

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
    if should_fail(&config).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": {
                    "message": "Random failure for testing",
                    "type": "internal_error",
                    "code": "internal_error"
                }
            })),
        )
            .into_response();
    }

    if config.response_delay_ms > 0 {
        tokio::time::sleep(tokio::time::Duration::from_millis(config.response_delay_ms)).await;
410
411
412
413
414
415
416
    }

    let is_stream = payload
        .get("stream")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

417
418
419
420
421
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

422
    if is_stream {
423
        let request_id = format!("chatcmpl-{}", Uuid::new_v4());
424

425
426
427
        let stream = stream::once(async move {
            let chunk = json!({
                "id": request_id,
428
429
                "object": "chat.completion.chunk",
                "created": timestamp,
430
                "model": "mock-model",
431
432
433
                "choices": [{
                    "index": 0,
                    "delta": {
434
                        "content": "This is a mock chat response."
435
436
437
438
439
                    },
                    "finish_reason": null
                }]
            });

440
441
442
            Ok::<_, Infallible>(Event::default().data(chunk.to_string()))
        })
        .chain(stream::once(async { Ok(Event::default().data("[DONE]")) }));
443

444
445
446
        Sse::new(stream)
            .keep_alive(KeepAlive::default())
            .into_response()
447
    } else {
448
449
        Json(json!({
            "id": format!("chatcmpl-{}", Uuid::new_v4()),
450
            "object": "chat.completion",
451
452
            "created": timestamp,
            "model": "mock-model",
453
454
455
456
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
457
                    "content": "This is a mock chat response."
458
                },
459
                "finish_reason": "stop"
460
461
462
            }],
            "usage": {
                "prompt_tokens": 10,
463
464
                "completion_tokens": 5,
                "total_tokens": 15
465
466
            }
        }))
467
        .into_response()
468
469
470
471
    }
}

async fn completions_handler(
472
473
474
    State(config): State<Arc<RwLock<MockWorkerConfig>>>,
    Json(payload): Json<serde_json::Value>,
) -> Response {
475
476
    let config = config.read().await;

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
    if should_fail(&config).await {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": {
                    "message": "Random failure for testing",
                    "type": "internal_error",
                    "code": "internal_error"
                }
            })),
        )
            .into_response();
    }

    if config.response_delay_ms > 0 {
        tokio::time::sleep(tokio::time::Duration::from_millis(config.response_delay_ms)).await;
493
494
495
496
497
498
499
    }

    let is_stream = payload
        .get("stream")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

500
501
502
503
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
504
505

    if is_stream {
506
        let request_id = format!("cmpl-{}", Uuid::new_v4());
507

508
509
510
511
512
513
514
515
516
517
518
519
520
        let stream = stream::once(async move {
            let chunk = json!({
                "id": request_id,
                "object": "text_completion",
                "created": timestamp,
                "model": "mock-model",
                "choices": [{
                    "text": "This is a mock completion.",
                    "index": 0,
                    "logprobs": null,
                    "finish_reason": null
                }]
            });
521

522
523
524
            Ok::<_, Infallible>(Event::default().data(chunk.to_string()))
        })
        .chain(stream::once(async { Ok(Event::default().data("[DONE]")) }));
525

526
527
528
        Sse::new(stream)
            .keep_alive(KeepAlive::default())
            .into_response()
529
    } else {
530
531
532
533
534
535
536
537
        Json(json!({
            "id": format!("cmpl-{}", Uuid::new_v4()),
            "object": "text_completion",
            "created": timestamp,
            "model": "mock-model",
            "choices": [{
                "text": "This is a mock completion.",
                "index": 0,
538
539
                "logprobs": null,
                "finish_reason": "stop"
540
            }],
541
            "usage": {
542
543
544
                "prompt_tokens": 10,
                "completion_tokens": 5,
                "total_tokens": 15
545
546
            }
        }))
547
        .into_response()
548
549
550
    }
}

551
async fn flush_cache_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
552
553
554
    let config = config.read().await;

    if should_fail(&config).await {
555
556
557
558
559
560
561
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": "Random failure for testing"
            })),
        )
            .into_response();
562
563
    }

564
565
    Json(json!({
        "message": "Cache flushed successfully"
566
    }))
567
    .into_response()
568
569
}

570
async fn v1_models_handler(State(config): State<Arc<RwLock<MockWorkerConfig>>>) -> Response {
571
572
573
    let config = config.read().await;

    if should_fail(&config).await {
574
575
576
577
578
579
580
581
582
583
584
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({
                "error": {
                    "message": "Random failure for testing",
                    "type": "internal_error",
                    "code": "internal_error"
                }
            })),
        )
            .into_response();
585
586
    }

587
588
589
590
591
592
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    Json(json!({
593
594
        "object": "list",
        "data": [{
595
            "id": "mock-model",
596
            "object": "model",
597
598
            "created": timestamp,
            "owned_by": "organization-owner"
599
600
        }]
    }))
601
    .into_response()
602
603
}

604
605
606
607
impl Default for MockWorkerConfig {
    fn default() -> Self {
        Self {
            port: 0,
608
609
610
611
            worker_type: WorkerType::Regular,
            health_status: HealthStatus::Healthy,
            response_delay_ms: 0,
            fail_rate: 0.0,
612
        }
613
614
    }
}