router.rs 46.7 KB
Newer Older
1
use crate::config::types::RetryConfig;
2
use crate::core::{HealthChecker, Worker, WorkerFactory};
3
use crate::metrics::RouterMetrics;
4
use crate::openai_api_types::{ChatCompletionRequest, CompletionRequest, GenerateRequest};
5
use crate::policies::LoadBalancingPolicy;
6
7
8
9
10
11
12
13
14
use crate::routers::{RouterTrait, WorkerManagement};
use axum::{
    body::Body,
    extract::Request,
    http::{header::CONTENT_TYPE, HeaderMap, HeaderValue, StatusCode},
    response::{IntoResponse, Response},
    Json,
};
use futures_util::StreamExt;
15
use reqwest::Client;
16
17
18
19
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
20
use tokio_stream::wrappers::UnboundedReceiverStream;
21
use tracing::{debug, error, info, warn};
22
pub fn copy_request_headers(req: &Request<Body>) -> Vec<(String, String)> {
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    req.headers()
        .iter()
        .filter_map(|(name, value)| {
            value
                .to_str()
                .ok()
                .map(|v| (name.to_string(), v.to_string()))
        })
        .collect()
}

/// Regular router that uses injected load balancing policies
#[derive(Debug)]
pub struct Router {
    workers: Arc<RwLock<Vec<Box<dyn Worker>>>>,
    policy: Arc<dyn LoadBalancingPolicy>,
39
    client: Client,
40
41
    timeout_secs: u64,
    interval_secs: u64,
42
43
    dp_aware: bool,
    api_key: Option<String>,
44
    retry_config: RetryConfig,
45
46
47
48
49
50
    _worker_loads: Arc<tokio::sync::watch::Receiver<HashMap<String, isize>>>,
    _load_monitor_handle: Option<Arc<tokio::task::JoinHandle<()>>>,
    _health_checker: Option<HealthChecker>,
}

impl Router {
51
    /// Create a new router with injected policy and client
52
53
54
    pub fn new(
        worker_urls: Vec<String>,
        policy: Arc<dyn LoadBalancingPolicy>,
55
        client: Client,
56
57
        timeout_secs: u64,
        interval_secs: u64,
58
59
        dp_aware: bool,
        api_key: Option<String>,
60
        retry_config: RetryConfig,
61
62
    ) -> Result<Self, String> {
        // Update active workers gauge
63
        RouterMetrics::set_active_workers(worker_urls.len());
64
65
66
67
68
69

        // Wait for workers to be healthy (skip if empty - for service discovery mode)
        if !worker_urls.is_empty() {
            Self::wait_for_healthy_workers(&worker_urls, timeout_secs, interval_secs)?;
        }

70
71
72
73
74
75
76
77
        let worker_urls = if dp_aware {
            // worker address now in the format of "http://host:port@dp_rank"
            Self::get_dp_aware_workers(&worker_urls, &api_key)
                .map_err(|e| format!("Failed to get dp-aware workers: {}", e))?
        } else {
            worker_urls
        };

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
        // Create Worker trait objects from URLs
        let workers: Vec<Box<dyn Worker>> = worker_urls
            .iter()
            .map(|url| WorkerFactory::create_regular(url.clone()))
            .collect();

        // Initialize policy with workers if needed (e.g., for cache-aware)
        if let Some(cache_aware) = policy
            .as_any()
            .downcast_ref::<crate::policies::CacheAwarePolicy>()
        {
            cache_aware.init_workers(&workers);
        }

        let workers = Arc::new(RwLock::new(workers));
        let health_checker = crate::core::start_health_checker(Arc::clone(&workers), interval_secs);

        // Setup load monitoring for PowerOfTwo policy
        let (tx, rx) = tokio::sync::watch::channel(HashMap::new());
        let worker_loads = Arc::new(rx);

        let load_monitor_handle = if policy.name() == "power_of_two" {
            let monitor_urls = worker_urls.clone();
            let monitor_interval = interval_secs;
            let policy_clone = Arc::clone(&policy);
103
            let client_clone = client.clone();
104
105

            Some(Arc::new(tokio::spawn(async move {
106
107
108
109
110
111
112
113
                Self::monitor_worker_loads(
                    monitor_urls,
                    tx,
                    monitor_interval,
                    policy_clone,
                    client_clone,
                )
                .await;
114
115
116
117
118
119
120
121
            })))
        } else {
            None
        };

        Ok(Router {
            workers,
            policy,
122
            client,
123
124
            timeout_secs,
            interval_secs,
125
126
            dp_aware,
            api_key,
127
            retry_config,
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
            _worker_loads: worker_loads,
            _load_monitor_handle: load_monitor_handle,
            _health_checker: Some(health_checker),
        })
    }

    /// Get the current list of worker URLs
    pub fn get_worker_urls(&self) -> Vec<String> {
        self.workers
            .read()
            .unwrap()
            .iter()
            .map(|w| w.url().to_string())
            .collect()
    }

    pub fn wait_for_healthy_workers(
        worker_urls: &[String],
        timeout_secs: u64,
        interval_secs: u64,
    ) -> Result<(), String> {
149
150
151
152
153
154
        if worker_urls.is_empty() {
            return Err(
                "Timeout waiting for workers to become healthy: no workers provided".to_string(),
            );
        }

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
        let start_time = std::time::Instant::now();
        let sync_client = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(timeout_secs))
            .build()
            .map_err(|e| format!("Failed to create HTTP client: {}", e))?;

        loop {
            if start_time.elapsed() > Duration::from_secs(timeout_secs) {
                error!(
                    "Timeout {}s waiting for workers {:?} to become healthy. Please set --router-worker-startup-timeout-secs (sglang_router.launch_server) or --worker-startup-timeout-secs (sglang_worker.router) to a larger value",
                    timeout_secs, worker_urls
                );
                return Err(format!(
                    "Timeout {}s waiting for workers {:?} to become healthy. Please set --router-worker-startup-timeout-secs (sglang_router.launch_server) or --worker-startup-timeout-secs (sglang_worker.router) to a larger value",
                    timeout_secs, worker_urls
                ));
            }

            let mut all_healthy = true;
            let mut unhealthy_workers = Vec::new();

            for url in worker_urls {
                match sync_client.get(&format!("{}/health", url)).send() {
                    Ok(res) => {
                        if !res.status().is_success() {
                            all_healthy = false;
181
                            unhealthy_workers.push((url, format!("status: {}", res.status())));
182
183
184
185
                        }
                    }
                    Err(_) => {
                        all_healthy = false;
186
                        unhealthy_workers.push((url, "not ready".to_string()));
187
188
189
190
191
                    }
                }
            }

            if all_healthy {
192
                info!("All {} workers are healthy", worker_urls.len());
193
194
                return Ok(());
            } else {
195
196
197
198
199
                debug!(
                    "Waiting for {} workers to become healthy ({} unhealthy)",
                    worker_urls.len(),
                    unhealthy_workers.len()
                );
200
201
202
203
204
                thread::sleep(Duration::from_secs(interval_secs));
            }
        }
    }

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
253
254
255
256
257
258
259
260
    fn get_worker_dp_size(worker_url: &str, api_key: &Option<String>) -> Result<usize, String> {
        let sync_client = reqwest::blocking::Client::new();
        let mut req_builder = sync_client.get(&format!("{}/get_server_info", worker_url));
        if let Some(key) = api_key {
            req_builder = req_builder.bearer_auth(key);
        }

        match req_builder.send() {
            Ok(res) => {
                if res.status().is_success() {
                    let server_info = res
                        .text()
                        .map_err(|e| format!("failed to read text from response: {}", e))?;

                    let server_info: serde_json::Value = serde_json::from_str(&server_info)
                        .map_err(|e| format!("failed to decode JSON: {}", e))?;

                    let dp_size = server_info
                        .get("dp_size")
                        .and_then(|v| v.as_u64())
                        .ok_or_else(|| String::from("dp_size not found or not an u64"))?;

                    Ok(if dp_size > usize::MAX as u64 {
                        return Err(format!("dp_size is too large: {}", dp_size));
                    } else {
                        dp_size as usize
                    })
                } else {
                    Err(format!("unexpected status code: {}", res.status()))
                }
            }
            Err(e) => Err(format!("error response: {}", e)),
        }
    }

    // Given a list of workers, return a list of workers with dp_rank as suffix
    fn get_dp_aware_workers(
        worker_urls: &[String],
        api_key: &Option<String>,
    ) -> Result<Vec<String>, String> {
        let mut dp_aware_workers: Vec<String> = Vec::new();

        for url in worker_urls {
            match Self::get_worker_dp_size(url, api_key) {
                Ok(dp_size) => {
                    for i in 0..dp_size {
                        dp_aware_workers.push(format!("{}@{}", url, i));
                    }
                }
                Err(e) => return Err(format!("Failed to get DP size for {}: {}", url, e)),
            }
        }

        Ok(dp_aware_workers)
    }

261
262
263
264
265
266
267
268
269
    fn select_first_worker(&self) -> Result<String, String> {
        let workers_guard = self.workers.read().unwrap();
        if workers_guard.is_empty() {
            Err("No workers are available".to_string())
        } else {
            Ok(workers_guard[0].url().to_string())
        }
    }

270
    pub async fn send_health_check(&self, worker_url: &str) -> Response {
271
        let health_url = if self.dp_aware {
272
            // Need to extract the URL from "http://host:port@dp_rank"
273
274
            match Self::extract_dp_rank(worker_url) {
                Ok((worker_url_prefix, _dp_rank)) => worker_url_prefix,
275
                Err(e) => {
276
277
278
279
280
281
                    error!("Failed to extract dp_rank for health check: {}", e);
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to extract dp_rank: {}", e),
                    )
                        .into_response();
282
                }
283
            }
284
285
286
287
        } else {
            worker_url
        };

288
        let request_builder = self.client.get(format!("{}/health", health_url));
289
290
291

        let response = match request_builder.send().await {
            Ok(res) => {
292
293
                let status = StatusCode::from_u16(res.status().as_u16())
                    .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
294
295

                match res.bytes().await {
296
                    Ok(body) => (status, body).into_response(),
297
298
                    Err(e) => {
                        error!(
299
                            worker_url = %health_url,
300
                            error = %e,
301
                            "Failed to read health response body"
302
                        );
303
304
305
306
307
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to read response body: {}", e),
                        )
                            .into_response()
308
                    }
309
310
                }
            }
311
312
            Err(e) => {
                error!(
313
                    worker_url = %health_url,
314
                    error = %e,
315
                    "Failed to send health request to worker"
316
                );
317
318
319
320
321
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to send request to worker {}: {}", health_url, e),
                )
                    .into_response()
322
            }
323
324
        };

325
        // Don't record metrics for health checks
326
327
328
        response
    }

329
    // Helper method to proxy GET requests to the first available worker
330
    async fn proxy_get_request(&self, req: Request<Body>, endpoint: &str) -> Response {
331
332
333
334
        let headers = copy_request_headers(&req);

        match self.select_first_worker() {
            Ok(worker_url) => {
335
                let mut request_builder = self.client.get(format!("{}/{}", worker_url, endpoint));
336
337
338
339
340
341
342
                for (name, value) in headers {
                    if name.to_lowercase() != "content-type"
                        && name.to_lowercase() != "content-length"
                    {
                        request_builder = request_builder.header(name, value);
                    }
                }
343

344
345
346
347
348
349
350
351
352
353
354
                match request_builder.send().await {
                    Ok(res) => {
                        let status = StatusCode::from_u16(res.status().as_u16())
                            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                        match res.bytes().await {
                            Ok(body) => (status, body).into_response(),
                            Err(e) => (
                                StatusCode::INTERNAL_SERVER_ERROR,
                                format!("Failed to read response: {}", e),
                            )
                                .into_response(),
355
356
                        }
                    }
357
358
359
360
361
                    Err(e) => (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Request failed: {}", e),
                    )
                        .into_response(),
362
363
                }
            }
364
            Err(e) => (StatusCode::SERVICE_UNAVAILABLE, e).into_response(),
365
366
367
368
369
370
371
372
        }
    }

    // New method to route typed requests directly
    pub async fn route_typed_request<
        T: crate::openai_api_types::GenerationRequest + serde::Serialize + Clone,
    >(
        &self,
373
        headers: Option<&HeaderMap>,
374
375
        typed_req: &T,
        route: &str,
376
    ) -> Response {
377
378
        // Handle retries like the original implementation
        let start = Instant::now();
379
380
381
382
        // Use retry config for per-worker retries
        let max_request_retries = self.retry_config.max_retries;
        // Total retries across all workers (2x to allow trying multiple workers)
        let max_total_retries = self.retry_config.max_retries * 2;
383
384
        let mut total_retries = 0;

385
        while total_retries < max_total_retries {
386
387
388
389
390
391
392
393
394
            // Extract routing text directly from typed request
            let text = typed_req.extract_text_for_routing();
            let is_stream = typed_req.is_stream();

            // Select worker based on text
            let worker_url = self.select_generate_worker_from_text(&text);
            let mut request_retries = 0;

            // Try the same worker multiple times
395
            while request_retries < max_request_retries {
396
397
                if total_retries >= 1 {
                    info!("Retrying request after {} failed attempts", total_retries);
398
                    RouterMetrics::record_retry(route);
399
400
401
402
403
404
405
                }

                // Increment load before request if using RAII load tracking
                let load_incremented = if self.policy.name() == "cache_aware" {
                    let workers_guard = self.workers.read().unwrap();
                    if let Some(worker) = workers_guard.iter().find(|w| w.url() == &worker_url) {
                        worker.increment_load();
406
                        RouterMetrics::set_running_requests(&worker_url, worker.load());
407
408
409
410
411
412
413
414
415
416
417
                        true
                    } else {
                        false
                    }
                } else {
                    false
                };

                // Send typed request directly
                let response = self
                    .send_typed_request(
418
                        headers,
419
420
421
422
423
424
425
426
427
428
                        typed_req,
                        route,
                        &worker_url,
                        is_stream,
                        load_incremented,
                    )
                    .await;

                if response.status().is_success() {
                    let duration = start.elapsed();
429
                    RouterMetrics::record_generate_duration(duration);
430
431
432
                    return response;
                } else {
                    // if the worker is healthy, it means the request is bad, so return the error response
433
                    let health_response = self.send_health_check(&worker_url).await;
434
                    if health_response.status().is_success() {
435
                        RouterMetrics::record_request_error(route, "request_failed");
436
437
438
439
440
                        return response;
                    }
                }

                warn!(
441
                    "Generate request failed route={} worker_url={} attempt={} max_attempts={}",
442
443
444
                    route,
                    worker_url,
                    request_retries + 1,
445
                    max_request_retries
446
447
448
449
450
                );

                request_retries += 1;
                total_retries += 1;

451
                if request_retries == max_request_retries {
452
                    warn!(
453
454
                        "Removing failed worker after typed request failures worker_url={}",
                        worker_url
455
                    );
456
                    self.remove_worker(&worker_url);
457
458
459
460
461
                    break;
                }
            }
        }

462
        RouterMetrics::record_request_error(route, "request_failed");
463
464
465
466
467
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "All retry attempts failed",
        )
            .into_response()
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
    }

    // Helper method to select worker from text using the policy
    fn select_generate_worker_from_text(&self, text: &str) -> String {
        let workers = self.workers.read().unwrap();

        match self.policy.select_worker(&workers, Some(text)) {
            Some(idx) => workers[idx].url().to_string(),
            None => {
                warn!("No healthy workers available");
                String::new()
            }
        }
    }

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    // TODO (rui): Better accommodate to the Worker abstraction
    fn extract_dp_rank(worker_url: &str) -> Result<(&str, usize), String> {
        let parts: Vec<&str> = worker_url.split('@').collect();
        if parts.len() != 2 {
            return Err(format!("invalid worker_url format: {}", worker_url));
        }

        // Parse the second part (dp_rank) into an integer
        match parts[1].parse::<usize>() {
            Ok(dp_rank) => Ok((parts[0], dp_rank)),
            Err(_) => Err(format!(
                "failed to parse dp_rank from worker_url: {}",
                worker_url
            )),
        }
    }

500
501
502
    // Send typed request directly without conversion
    async fn send_typed_request<T: serde::Serialize>(
        &self,
503
        headers: Option<&HeaderMap>,
504
505
506
507
508
        typed_req: &T,
        route: &str,
        worker_url: &str,
        is_stream: bool,
        load_incremented: bool, // Whether load was incremented for this request
509
    ) -> Response {
510
511
        let start = Instant::now();

512
513
514
515
516
        let mut request_builder = if self.dp_aware {
            let (worker_url_prefix, dp_rank) = match Self::extract_dp_rank(worker_url) {
                Ok(tup) => tup,
                Err(e) => {
                    error!("Failed to extract dp_rank: {}", e);
517
518
519
520
521
                    return (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        format!("Failed to extract dp_rank: {}", e),
                    )
                        .into_response();
522
523
524
525
526
527
528
                }
            };

            // Parse the request body
            let mut json_val = match serde_json::to_value(typed_req) {
                Ok(j) => j,
                Err(e) => {
529
530
531
532
533
                    return (
                        StatusCode::BAD_REQUEST,
                        format!("Convert into serde_json::Value failed: {}", e),
                    )
                        .into_response();
534
535
536
537
538
539
540
541
542
543
544
545
546
547
                }
            };

            // Insert the data_parallel_rank field
            if let Some(map) = json_val.as_object_mut() {
                map.insert(
                    String::from("data_parallel_rank"),
                    serde_json::json!(dp_rank),
                );
                debug!(
                    "Modified request body: {}",
                    serde_json::to_string(&json_val).unwrap_or(String::from("ERR"))
                );
            } else {
548
549
550
551
552
                return (
                    StatusCode::BAD_REQUEST,
                    "Failed to insert the data_parallel_rank field into the request body",
                )
                    .into_response();
553
554
            }

555
            self.client
556
557
558
                .post(format!("{}{}", worker_url_prefix, route))
                .json(&json_val)
        } else {
559
            self.client
560
561
562
                .post(format!("{}{}", worker_url, route))
                .json(typed_req) // Use json() directly with typed request
        };
563

564
565
566
567
568
569
570
571
572
        // Copy all headers from original request if provided
        if let Some(headers) = headers {
            for (name, value) in headers {
                // Skip Content-Type and Content-Length as .json() sets them
                if name.to_string().to_lowercase() != "content-type"
                    && name.to_string().to_lowercase() != "content-length"
                {
                    request_builder = request_builder.header(name, value);
                }
573
574
575
576
577
578
            }
        }

        let res = match request_builder.send().await {
            Ok(res) => res,
            Err(e) => {
579
580
581
582
                error!(
                    "Failed to send typed request worker_url={} route={} error={}",
                    worker_url, route, e
                );
583
584
585
586
587
588

                // Decrement load on error if it was incremented
                if load_incremented {
                    if let Ok(workers_guard) = self.workers.read() {
                        if let Some(worker) = workers_guard.iter().find(|w| w.url() == worker_url) {
                            worker.decrement_load();
589
                            RouterMetrics::set_running_requests(&worker_url, worker.load());
590
591
592
593
                        }
                    }
                }

594
595
596
597
598
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Request failed: {}", e),
                )
                    .into_response();
599
600
601
            }
        };

602
603
        let status = StatusCode::from_u16(res.status().as_u16())
            .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
604
605
606
607

        if !is_stream {
            // For non-streaming requests, get response first
            let response = match res.bytes().await {
608
                Ok(body) => (status, body).into_response(),
609
610
                Err(e) => {
                    let error_msg = format!("Failed to get response body: {}", e);
611
                    (StatusCode::INTERNAL_SERVER_ERROR, error_msg).into_response()
612
613
614
615
616
617
618
619
                }
            };

            // Decrement load counter for non-streaming requests if it was incremented
            if load_incremented && !is_stream {
                if let Ok(workers_guard) = self.workers.read() {
                    if let Some(worker) = workers_guard.iter().find(|w| w.url() == worker_url) {
                        worker.decrement_load();
620
                        RouterMetrics::set_running_requests(&worker_url, worker.load());
621
622
623
624
625
626
                    }
                }
            }

            // Record metrics
            let duration = start.elapsed();
627
628
            RouterMetrics::record_generate_duration(duration);
            RouterMetrics::record_request(route);
629
630
631
632
633
634
635

            response
        } else if load_incremented {
            // For streaming with load tracking, we need to manually decrement when done
            let workers = Arc::clone(&self.workers);
            let worker_url = worker_url.to_string();

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
            let stream = res.bytes_stream();
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

            // Spawn task to forward stream and detect completion
            tokio::spawn(async move {
                let mut stream = stream;
                while let Some(chunk) = stream.next().await {
                    match chunk {
                        Ok(bytes) => {
                            // Check for stream end marker
                            if bytes
                                .as_ref()
                                .windows(12)
                                .any(|window| window == b"data: [DONE]")
                            {
                                if let Ok(workers_guard) = workers.read() {
                                    if let Some(worker) =
                                        workers_guard.iter().find(|w| w.url() == &worker_url)
                                    {
                                        worker.decrement_load();
                                        RouterMetrics::set_running_requests(
                                            &worker_url,
                                            worker.load(),
                                        );
660
661
662
                                    }
                                }
                            }
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
                            if tx.send(Ok(bytes)).is_err() {
                                break;
                            }
                        }
                        Err(e) => {
                            let _ = tx.send(Err(format!("Stream error: {}", e)));
                            break;
                        }
                    }
                }
            });

            let stream = UnboundedReceiverStream::new(rx);
            let body = Body::from_stream(stream);

            let mut response = Response::new(body);
            *response.status_mut() = status;
            response
                .headers_mut()
                .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
            response
684
685
        } else {
            // For requests without load tracking, just stream
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
            let stream = res.bytes_stream();
            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

            // Spawn task to forward stream
            tokio::spawn(async move {
                let mut stream = stream;
                while let Some(chunk) = stream.next().await {
                    match chunk {
                        Ok(bytes) => {
                            if tx.send(Ok(bytes)).is_err() {
                                break;
                            }
                        }
                        Err(e) => {
                            let _ = tx.send(Err(format!("Stream error: {}", e)));
                            break;
                        }
                    }
                }
            });

            let stream = UnboundedReceiverStream::new(rx);
            let body = Body::from_stream(stream);

            let mut response = Response::new(body);
            *response.status_mut() = status;
            response
                .headers_mut()
                .insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
            response
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
        }
    }

    pub async fn add_worker(&self, worker_url: &str) -> Result<String, String> {
        let start_time = std::time::Instant::now();
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(self.timeout_secs))
            .build()
            .map_err(|e| format!("Failed to create HTTP client: {}", e))?;

        loop {
            if start_time.elapsed() > Duration::from_secs(self.timeout_secs) {
                error!(
                    "Timeout {}s waiting for worker {} to become healthy. Please set --router-worker-startup-timeout-secs (sglang_router.launch_server) or --worker-startup-timeout-secs (sglang_worker.router) to a larger value",
                    self.timeout_secs, worker_url
                );
                return Err(format!(
                    "Timeout {}s waiting for worker {} to become healthy. Please set --router-worker-startup-timeout-secs (sglang_router.launch_server) or --worker-startup-timeout-secs (sglang_worker.router) to a larger value",
                    self.timeout_secs, worker_url
                ));
            }

            match client.get(&format!("{}/health", worker_url)).send().await {
                Ok(res) => {
                    if res.status().is_success() {
                        let mut workers_guard = self.workers.write().unwrap();
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
                        if self.dp_aware {
                            // Need to contact the worker to extract the dp_size,
                            // and add them as multiple workers
                            let url_vec = vec![String::from(worker_url)];
                            let dp_url_vec = Self::get_dp_aware_workers(&url_vec, &self.api_key)
                                .map_err(|e| format!("Failed to get dp-aware workers: {}", e))?;
                            let mut worker_added: bool = false;
                            for dp_url in &dp_url_vec {
                                if workers_guard.iter().any(|w| w.url() == dp_url) {
                                    warn!("Worker {} already exists", dp_url);
                                    continue;
                                }
                                info!("Added worker: {}", dp_url);
                                let new_worker = WorkerFactory::create_regular(dp_url.to_string());
                                workers_guard.push(new_worker);
                                worker_added = true;
                            }
                            if !worker_added {
                                return Err(format!("No worker added for {}", worker_url));
                            }
                        } else {
                            if workers_guard.iter().any(|w| w.url() == worker_url) {
                                return Err(format!("Worker {} already exists", worker_url));
                            }
                            info!("Added worker: {}", worker_url);
                            let new_worker = WorkerFactory::create_regular(worker_url.to_string());
                            workers_guard.push(new_worker);
769
                        }
770

771
                        RouterMetrics::set_active_workers(workers_guard.len());
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786

                        // If cache aware policy, initialize the worker in the tree
                        if let Some(cache_aware) =
                            self.policy
                                .as_any()
                                .downcast_ref::<crate::policies::CacheAwarePolicy>()
                        {
                            // Get updated workers after adding
                            drop(workers_guard);
                            let workers_guard = self.workers.read().unwrap();
                            cache_aware.init_workers(&workers_guard);
                        }

                        return Ok(format!("Successfully added worker: {}", worker_url));
                    } else {
787
788
                        debug!(
                            "Worker {} health check pending - status: {}",
789
790
791
792
793
794
795
796
797
798
799
800
801
802
                            worker_url,
                            res.status()
                        );
                        // if the url does not have http or https prefix, warn users
                        if !worker_url.starts_with("http://") && !worker_url.starts_with("https://")
                        {
                            warn!("The worker url {} does not have http or https prefix. Please add the prefix to the url.", worker_url);
                        }

                        tokio::time::sleep(Duration::from_secs(self.interval_secs)).await;
                        continue;
                    }
                }
                Err(e) => {
803
                    debug!("Worker {} health check pending - error: {}", worker_url, e);
804
805
806
807
808
809
810
811
812
813
814
815
816
817

                    // if the url does not have http or https prefix, warn users
                    if !worker_url.starts_with("http://") && !worker_url.starts_with("https://") {
                        warn!("The worker url {} does not have http or https prefix. Please add the prefix to the url.", worker_url);
                    }

                    tokio::time::sleep(Duration::from_secs(self.interval_secs)).await;
                    continue;
                }
            }
        }
    }

    pub fn remove_worker(&self, worker_url: &str) {
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
        if self.dp_aware {
            // remove dp-aware workers in a prefix-matching fashion
            // without contacting the remote worker
            let mut candidate_workers: Vec<String> = Vec::new();
            let mut removed_workers: Vec<String> = Vec::new();
            let worker_url_prefix = format!("{}@", worker_url);

            {
                // find the candidate workers to be removed
                let workers_guard = self.workers.read().unwrap();
                for w in workers_guard.iter() {
                    if w.url().starts_with(&worker_url_prefix) {
                        candidate_workers.push(w.url().to_string());
                    }
                }
            }

            {
                // do the removing on the worker_urls
                let mut workers_guard = self.workers.write().unwrap();
                for dp_url in candidate_workers.iter() {
                    if let Some(index) = workers_guard.iter().position(|w| w.url() == dp_url) {
                        workers_guard.remove(index);
                        info!("Removed worker: {}", dp_url);
                        removed_workers.push(dp_url.to_string());
                    } else {
                        warn!("Worker {} not found, skipping removal", dp_url);
                        continue;
                    }
                }
                RouterMetrics::set_active_workers(workers_guard.len());
            }

            // If cache aware policy, remove the workers from the tree
            if let Some(cache_aware) = self
                .policy
                .as_any()
                .downcast_ref::<crate::policies::CacheAwarePolicy>()
            {
                for dp_url in removed_workers.iter() {
                    cache_aware.remove_worker(dp_url);
                    info!("Removed worker from tree: {}", dp_url);
                }
            }
        } else {
            let mut workers_guard = self.workers.write().unwrap();
            if let Some(index) = workers_guard.iter().position(|w| w.url() == worker_url) {
                workers_guard.remove(index);
                info!("Removed worker: {}", worker_url);
                RouterMetrics::set_active_workers(workers_guard.len());
            } else {
                warn!("Worker {} not found, skipping removal", worker_url);
                return;
            }

            // If cache aware policy, remove the workers from the tree
            if let Some(cache_aware) = self
                .policy
                .as_any()
                .downcast_ref::<crate::policies::CacheAwarePolicy>()
            {
                cache_aware.remove_worker(worker_url);
                info!("Removed worker from tree: {}", worker_url);
            }
        }
    }

885
    async fn get_worker_load(&self, worker_url: &str) -> Option<isize> {
886
887
888
889
890
891
892
893
894
895
896
897
898
899
        let worker_url = if self.dp_aware {
            // Need to extract the URL from "http://host:port@dp_rank"
            let (worker_url_prefix, _dp_rank) = match Self::extract_dp_rank(worker_url) {
                Ok(tup) => tup,
                Err(e) => {
                    error!("Failed to extract dp_rank: {}", e);
                    return None;
                }
            };
            worker_url_prefix
        } else {
            worker_url
        };

900
901
902
903
904
905
        match self
            .client
            .get(&format!("{}/get_load", worker_url))
            .send()
            .await
        {
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
            Ok(res) if res.status().is_success() => match res.bytes().await {
                Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
                    Ok(data) => data
                        .get("load")
                        .and_then(|v| v.as_i64())
                        .map(|v| v as isize),
                    Err(e) => {
                        debug!("Failed to parse load response from {}: {}", worker_url, e);
                        None
                    }
                },
                Err(e) => {
                    debug!("Failed to read load response from {}: {}", worker_url, e);
                    None
                }
            },
            Ok(res) => {
                debug!(
                    "Worker {} returned non-success status: {}",
                    worker_url,
                    res.status()
                );
                None
            }
            Err(e) => {
                debug!("Failed to get load from {}: {}", worker_url, e);
                None
            }
        }
    }

    // Background task to monitor worker loads
    async fn monitor_worker_loads(
        worker_urls: Vec<String>,
        tx: tokio::sync::watch::Sender<HashMap<String, isize>>,
        interval_secs: u64,
        policy: Arc<dyn LoadBalancingPolicy>,
943
        client: Client,
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
    ) {
        let mut interval = tokio::time::interval(Duration::from_secs(interval_secs));

        loop {
            interval.tick().await;

            let mut loads = HashMap::new();
            for url in &worker_urls {
                if let Some(load) = Self::get_worker_load_static(&client, url).await {
                    loads.insert(url.clone(), load);
                }
            }

            if !loads.is_empty() {
                // Update policy with new loads
                policy.update_loads(&loads);

                // Send to watchers
                if let Err(e) = tx.send(loads) {
                    error!("Failed to send load update: {}", e);
                }
            }
        }
    }

    // Static version of get_worker_load for use in monitoring task
    async fn get_worker_load_static(client: &reqwest::Client, worker_url: &str) -> Option<isize> {
971
972
973
974
975
976
977
978
979
980
981
982
983
984
        let worker_url = if worker_url.contains("@") {
            // Need to extract the URL from "http://host:port@dp_rank"
            let (worker_url_prefix, _dp_rank) = match Self::extract_dp_rank(worker_url) {
                Ok(tup) => tup,
                Err(e) => {
                    debug!("Failed to extract dp_rank: {}", e);
                    return None;
                }
            };
            worker_url_prefix
        } else {
            worker_url
        };

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
        match client.get(&format!("{}/get_load", worker_url)).send().await {
            Ok(res) if res.status().is_success() => match res.bytes().await {
                Ok(bytes) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
                    Ok(data) => data
                        .get("load")
                        .and_then(|v| v.as_i64())
                        .map(|v| v as isize),
                    Err(e) => {
                        debug!("Failed to parse load response from {}: {}", worker_url, e);
                        None
                    }
                },
                Err(e) => {
                    debug!("Failed to read load response from {}: {}", worker_url, e);
                    None
                }
            },
            Ok(res) => {
                debug!(
                    "Worker {} returned non-success status: {}",
                    worker_url,
                    res.status()
                );
                None
            }
            Err(e) => {
                debug!("Failed to get load from {}: {}", worker_url, e);
                None
            }
        }
    }
}

use async_trait::async_trait;

#[async_trait]
impl WorkerManagement for Router {
    async fn add_worker(&self, worker_url: &str) -> Result<String, String> {
        Router::add_worker(self, worker_url).await
    }

    fn remove_worker(&self, worker_url: &str) {
        Router::remove_worker(self, worker_url)
    }

    fn get_worker_urls(&self) -> Vec<String> {
        Router::get_worker_urls(self)
    }
}

1035
#[async_trait]
1036
1037
1038
1039
1040
impl RouterTrait for Router {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

1041
    async fn health(&self, _req: Request<Body>) -> Response {
1042
1043
1044
1045
1046
1047
        let workers = self.workers.read().unwrap();
        let unhealthy_servers: Vec<_> = workers
            .iter()
            .filter(|w| !w.is_healthy())
            .map(|w| w.url().to_string())
            .collect();
1048

1049
1050
        if unhealthy_servers.is_empty() {
            (StatusCode::OK, "All servers healthy").into_response()
1051
        } else {
1052
1053
1054
1055
1056
            (
                StatusCode::SERVICE_UNAVAILABLE,
                format!("Unhealthy servers: {:?}", unhealthy_servers),
            )
                .into_response()
1057
1058
1059
        }
    }

1060
1061
    async fn health_generate(&self, req: Request<Body>) -> Response {
        self.proxy_get_request(req, "health_generate").await
1062
1063
    }

1064
1065
    async fn get_server_info(&self, req: Request<Body>) -> Response {
        self.proxy_get_request(req, "get_server_info").await
1066
1067
    }

1068
1069
    async fn get_models(&self, req: Request<Body>) -> Response {
        self.proxy_get_request(req, "v1/models").await
1070
1071
    }

1072
1073
    async fn get_model_info(&self, req: Request<Body>) -> Response {
        self.proxy_get_request(req, "get_model_info").await
1074
1075
1076
1077
    }

    async fn route_generate(
        &self,
1078
1079
1080
        headers: Option<&HeaderMap>,
        body: &GenerateRequest,
    ) -> Response {
1081
        self.route_typed_request(headers, body, "/generate").await
1082
1083
1084
1085
    }

    async fn route_chat(
        &self,
1086
1087
1088
        headers: Option<&HeaderMap>,
        body: &ChatCompletionRequest,
    ) -> Response {
1089
        self.route_typed_request(headers, body, "/v1/chat/completions")
1090
            .await
1091
1092
1093
1094
    }

    async fn route_completion(
        &self,
1095
1096
1097
        headers: Option<&HeaderMap>,
        body: &CompletionRequest,
    ) -> Response {
1098
        self.route_typed_request(headers, body, "/v1/completions")
1099
            .await
1100
1101
    }

1102
    async fn flush_cache(&self) -> Response {
1103
1104
1105
1106
1107
1108
        // Get all worker URLs
        let worker_urls = self.get_worker_urls();

        // Send requests to all workers concurrently without headers
        let mut tasks = Vec::new();
        for worker_url in &worker_urls {
1109
1110
1111
1112
1113
1114
            let worker_url = if self.dp_aware {
                // Need to extract the URL from "http://host:port@dp_rank"
                let (worker_url_prefix, _dp_rank) = match Self::extract_dp_rank(worker_url) {
                    Ok(tup) => tup,
                    Err(e) => {
                        error!("Failed to extract dp_rank: {}", e);
1115
1116
1117
1118
1119
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            format!("Failed to extract dp_rank: {}", e),
                        )
                            .into_response();
1120
1121
1122
1123
1124
1125
                    }
                };
                worker_url_prefix
            } else {
                worker_url
            };
1126
            let request_builder = self.client.post(format!("{}/flush_cache", worker_url));
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
            tasks.push(request_builder.send());
        }

        // Wait for all responses
        let results = futures_util::future::join_all(tasks).await;

        // Check if all succeeded
        let all_success = results.iter().all(|r| {
            r.as_ref()
                .map(|res| res.status().is_success())
                .unwrap_or(false)
        });

        if all_success {
1141
            (StatusCode::OK, "Cache flushed on all servers").into_response()
1142
        } else {
1143
1144
1145
1146
1147
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Cache flush failed on one or more servers",
            )
                .into_response()
1148
1149
1150
        }
    }

1151
    async fn get_worker_loads(&self) -> Response {
1152
1153
1154
1155
1156
        let urls = self.get_worker_urls();
        let mut loads = Vec::new();

        // Get loads from all workers
        for url in &urls {
1157
            let load = self.get_worker_load(url).await.unwrap_or(-1);
1158
1159
1160
1161
1162
1163
            loads.push(serde_json::json!({
                "worker": url,
                "load": load
            }));
        }

1164
        Json(serde_json::json!({
1165
1166
            "workers": loads
        }))
1167
        .into_response()
1168
1169
1170
1171
1172
1173
    }

    fn router_type(&self) -> &'static str {
        "regular"
    }

1174
    fn readiness(&self) -> Response {
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
        // Regular router is ready if it has at least one healthy worker
        let healthy_count = self
            .workers
            .read()
            .unwrap()
            .iter()
            .filter(|w| w.is_healthy())
            .count();

        if healthy_count > 0 {
1185
            Json(serde_json::json!({
1186
1187
1188
1189
                "status": "ready",
                "healthy_workers": healthy_count,
                "total_workers": self.workers.read().unwrap().len()
            }))
1190
            .into_response()
1191
        } else {
1192
1193
1194
1195
1196
1197
1198
1199
1200
            (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(serde_json::json!({
                    "status": "not_ready",
                    "reason": "no healthy workers available",
                    "total_workers": self.workers.read().unwrap().len()
                })),
            )
                .into_response()
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policies::RandomPolicy;
    use std::collections::HashMap;

    fn create_test_regular_router() -> Router {
        let workers = vec![
            WorkerFactory::create_regular("http://worker1:8080".to_string()),
            WorkerFactory::create_regular("http://worker2:8080".to_string()),
        ];
        let (_, rx) = tokio::sync::watch::channel(HashMap::new());
        Router {
            workers: Arc::new(RwLock::new(workers)),
            policy: Arc::new(RandomPolicy::new()),
            timeout_secs: 5,
            interval_secs: 1,
1222
1223
            dp_aware: false,
            api_key: None,
1224
            client: Client::new(),
1225
            retry_config: RetryConfig::default(),
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
            _worker_loads: Arc::new(rx),
            _load_monitor_handle: None,
            _health_checker: None,
        }
    }

    #[test]
    fn test_router_get_worker_urls_regular() {
        let router = create_test_regular_router();
        let urls = router.get_worker_urls();

        assert_eq!(urls.len(), 2);
        assert!(urls.contains(&"http://worker1:8080".to_string()));
        assert!(urls.contains(&"http://worker2:8080".to_string()));
    }

    #[test]
    fn test_select_first_worker_regular() {
        let router = create_test_regular_router();
        let result = router.select_first_worker();

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "http://worker1:8080");
    }

    #[test]
    fn test_wait_for_healthy_workers_empty_list() {
1253
        // Empty list will timeout as there are no workers to check
1254
        let result = Router::wait_for_healthy_workers(&[], 1, 1);
1255
1256
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Timeout"));
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
    }

    #[test]
    fn test_wait_for_healthy_workers_invalid_urls() {
        // This test will timeout quickly since the URLs are invalid
        let result =
            Router::wait_for_healthy_workers(&["http://nonexistent:8080".to_string()], 1, 1);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Timeout"));
    }
}