router.rs 22.8 KB
Newer Older
1
2
// gRPC Router Implementation

3
use crate::config::types::RetryConfig;
4
use crate::core::{
5
    BasicWorkerBuilder, CircuitBreakerConfig, HealthConfig, WorkerRegistry, WorkerType,
6
};
7
use crate::grpc::{proto, SglangSchedulerClient};
8
use crate::metrics::RouterMetrics;
9
use crate::policies::{LoadBalancingPolicy, PolicyRegistry};
10
11
12
13
use crate::protocols::spec::{
    ChatCompletionRequest, ChatMessage, ContentPart, ResponseFormat, StringOrArray,
    UserMessageContent,
};
14
use crate::reasoning_parser::ParserFactory;
15
use crate::routers::RouterTrait;
16
use crate::tokenizer::{chat_template::ChatMessage as TokenizerChatMessage, traits::Tokenizer};
17
use crate::tool_parser::ParserRegistry;
18
19
20
21
22
23
24
use async_trait::async_trait;
use axum::{
    body::Body,
    extract::Request,
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
};
25
use std::collections::HashMap;
26
use std::sync::Arc;
27
use std::time::Duration;
28
29
30
31
32
33
34
35
36
37
use tracing::{debug, error, info, warn};
use uuid::Uuid;

// Data structures for processing
#[derive(Debug)]
pub struct ProcessedMessages {
    pub text: String,
    pub multimodal_inputs: Option<proto::MultimodalInputs>,
    pub stop_sequences: Option<StringOrArray>,
}
38

39
40
41
/// gRPC router implementation for SGLang
#[allow(dead_code)] // Fields will be used once implementation is complete
pub struct GrpcRouter {
42
43
44
45
    /// Centralized worker registry
    worker_registry: Arc<WorkerRegistry>,
    /// Centralized policy registry
    policy_registry: Arc<PolicyRegistry>,
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    /// Load balancing policy
    policy: Arc<dyn LoadBalancingPolicy>,
    /// Tokenizer for handling text encoding/decoding
    tokenizer: Arc<dyn Tokenizer>,
    /// Reasoning parser factory for structured reasoning outputs
    reasoning_parser_factory: ParserFactory,
    /// Tool parser registry for function/tool calls
    tool_parser_registry: &'static ParserRegistry,
    /// Configuration
    timeout_secs: u64,
    interval_secs: u64,
    dp_aware: bool,
    api_key: Option<String>,
    retry_config: RetryConfig,
    circuit_breaker_config: CircuitBreakerConfig,
}
62
63

impl GrpcRouter {
64
65
66
67
    /// Create a new gRPC router
    pub async fn new(
        worker_urls: Vec<String>,
        policy: Arc<dyn LoadBalancingPolicy>,
68
        ctx: &Arc<crate::server::AppContext>,
69
70
71
72
    ) -> Result<Self, String> {
        // Update metrics
        RouterMetrics::set_active_workers(worker_urls.len());

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        // Extract necessary components from context
        let tokenizer = ctx
            .tokenizer
            .as_ref()
            .ok_or_else(|| "gRPC router requires tokenizer".to_string())?
            .clone();
        let reasoning_parser_factory = ctx
            .reasoning_parser_factory
            .as_ref()
            .ok_or_else(|| "gRPC router requires reasoning parser factory".to_string())?
            .clone();
        let tool_parser_registry = ctx
            .tool_parser_registry
            .ok_or_else(|| "gRPC router requires tool parser registry".to_string())?;

88
        // Convert config CircuitBreakerConfig to core CircuitBreakerConfig
89
        let circuit_breaker_config = ctx.router_config.effective_circuit_breaker_config();
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        let core_cb_config = CircuitBreakerConfig {
            failure_threshold: circuit_breaker_config.failure_threshold,
            success_threshold: circuit_breaker_config.success_threshold,
            timeout_duration: Duration::from_secs(circuit_breaker_config.timeout_duration_secs),
            window_duration: Duration::from_secs(circuit_breaker_config.window_duration_secs),
        };

        // Create gRPC clients for each worker
        let mut grpc_clients = HashMap::new();
        for url in &worker_urls {
            match SglangSchedulerClient::connect(url).await {
                Ok(client) => {
                    grpc_clients.insert(url.clone(), client);
                    info!("Connected to gRPC worker at {}", url);
                }
                Err(e) => {
                    warn!("Failed to connect to gRPC worker at {}: {}", url, e);
                    // Continue with other workers
                }
            }
        }

        if grpc_clients.is_empty() {
            return Err("Failed to connect to any gRPC workers".to_string());
        }

116
117
118
        // Get registries from context
        let worker_registry = ctx.worker_registry.clone();
        let policy_registry = ctx.policy_registry.clone();
Chang Su's avatar
Chang Su committed
119

120
        // Create Worker trait objects with gRPC connection mode and register them
Chang Su's avatar
Chang Su committed
121
122
        for url in &worker_urls {
            if let Some(client) = grpc_clients.remove(url) {
123
124
125
126
127
128
129
130
131
132
133
134
135
                let worker = BasicWorkerBuilder::new(url.clone())
                    .worker_type(WorkerType::Regular)
                    .connection_mode(crate::core::ConnectionMode::Grpc { port: None })
                    .circuit_breaker_config(core_cb_config.clone())
                    .health_config(HealthConfig {
                        timeout_secs: ctx.router_config.health_check.timeout_secs,
                        check_interval_secs: ctx.router_config.health_check.check_interval_secs,
                        endpoint: ctx.router_config.health_check.endpoint.clone(),
                        failure_threshold: ctx.router_config.health_check.failure_threshold,
                        success_threshold: ctx.router_config.health_check.success_threshold,
                    })
                    .grpc_client(client)
                    .build();
Chang Su's avatar
Chang Su committed
136

137
138
                // Register worker in the centralized registry
                worker_registry.register(Arc::new(worker));
Chang Su's avatar
Chang Su committed
139
140
141
142
            } else {
                warn!("No gRPC client for worker {}, skipping", url);
            }
        }
143

144
145
146
147
148
149
150
151
        // Get only gRPC workers from registry for policy initialization
        let workers = worker_registry.get_workers_filtered(
            None, // any model
            Some(WorkerType::Regular),
            Some(crate::core::ConnectionMode::Grpc { port: None }),
            false, // include unhealthy workers during initialization
        );

152
153
154
155
156
157
158
159
        // Initialize policy with workers if needed
        if let Some(cache_aware) = policy
            .as_any()
            .downcast_ref::<crate::policies::CacheAwarePolicy>()
        {
            cache_aware.init_workers(&workers);
        }

160
        // No need for local health checkers - WorkerRegistry handles health checking
161
162

        Ok(GrpcRouter {
163
164
            worker_registry,
            policy_registry,
165
166
167
168
            policy,
            tokenizer,
            reasoning_parser_factory,
            tool_parser_registry,
169
170
171
172
173
            timeout_secs: ctx.router_config.worker_startup_timeout_secs,
            interval_secs: ctx.router_config.worker_startup_check_interval_secs,
            dp_aware: ctx.router_config.dp_aware,
            api_key: ctx.router_config.api_key.clone(),
            retry_config: ctx.router_config.effective_retry_config(),
174
175
176
            circuit_breaker_config: core_cb_config,
        })
    }
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

    // ============ Chat Implementation ============

    /// Main route_chat implementation
    async fn route_chat_impl(
        &self,
        _headers: Option<&HeaderMap>,
        body: &ChatCompletionRequest,
        model_id: Option<&str>,
    ) -> Response {
        debug!(
            "Processing chat completion request for model: {:?}",
            model_id
        );

        // Step 1: Select worker (fail fast if no workers available)
        let worker = match self.select_worker_for_request(model_id, None) {
            Some(w) => w,
            None => {
                warn!("No available workers for model: {:?}", model_id);
                return (StatusCode::SERVICE_UNAVAILABLE, "No available workers").into_response();
            }
        };

        debug!("Selected worker: {}", worker.url());

        // Step 2: Get gRPC client for worker (fail fast if can't connect)
        let client = match self.get_or_create_grpc_client(worker.url()).await {
            Ok(c) => c,
            Err(e) => {
                error!("Failed to get gRPC client: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Failed to get gRPC client: {}", e),
                )
                    .into_response();
            }
        };

        // Step 3: Process messages and apply chat template
        let processed_messages = match self.process_chat_messages(body) {
            Ok(msgs) => msgs,
            Err(e) => {
                error!("Failed to process chat messages: {}", e);
                return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
            }
        };

        // Step 4: Tokenize the processed text
        let encoding = match self.tokenizer.encode(&processed_messages.text) {
            Ok(encoding) => encoding,
            Err(e) => {
                error!("Tokenization failed: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("Tokenization failed: {}", e),
                )
                    .into_response();
            }
        };

        let token_ids = encoding.token_ids().to_vec();
        debug!("Tokenized {} tokens from input", token_ids.len());

        // Step 5: Build tool constraints if needed
        let structural_tag = if let Some(tools) = &body.tools {
            self.generate_tool_constraints(tools, &body.tool_choice, &body.model)
        } else {
            None
        };

        // Step 6: Build SamplingParams for gRPC
        let sampling_params = match self.build_grpc_sampling_params(body, structural_tag) {
            Ok(params) => params,
            Err(e) => {
                error!("Failed to build sampling parameters: {}", e);
                return (
                    StatusCode::BAD_REQUEST,
                    format!("Invalid sampling parameters: {}", e),
                )
                    .into_response();
            }
        };

        // Step 7: Create GenerateRequest
        let grpc_request = proto::GenerateRequest {
            request_id: format!("chatcmpl-{}", Uuid::new_v4()),
            tokenized: Some(proto::TokenizedInput {
                original_text: processed_messages.text.clone(),
                input_ids: token_ids.into_iter().map(|id| id as i32).collect(),
            }),
            mm_inputs: processed_messages.multimodal_inputs,
            sampling_params: Some(sampling_params),
            return_logprob: body.logprobs,
            logprob_start_len: -1,
            top_logprobs_num: body.top_logprobs.unwrap_or(0) as i32,
            return_hidden_states: body.return_hidden_states,
            ..Default::default()
        };

        // Step 8: Handle streaming vs non-streaming
        if body.stream {
            self.handle_streaming_chat(client, grpc_request, body).await
        } else {
            self.handle_non_streaming_chat(client, grpc_request, body)
                .await
        }
    }

    // ============ Helper Methods ============

    /// Process chat messages and apply template
    fn process_chat_messages(
        &self,
        request: &ChatCompletionRequest,
    ) -> Result<ProcessedMessages, String> {
        let tokenizer_messages = self.convert_messages_for_tokenizer(&request.messages)?;

        // Use the tokenizer's chat template - we require HuggingFace tokenizer for gRPC
        let formatted_text = if let Some(hf_tokenizer) =
            self.tokenizer
                .as_any()
                .downcast_ref::<crate::tokenizer::HuggingFaceTokenizer>()
        {
            hf_tokenizer
                .apply_chat_template(&tokenizer_messages, true)
                .map_err(|e| format!("Failed to apply chat template: {}", e))?
        } else {
            return Err(
                "gRPC router requires HuggingFace tokenizer with chat template support".to_string(),
            );
        };

        // Placeholder for multimodal inputs
        let multimodal_inputs = None;

        Ok(ProcessedMessages {
            text: formatted_text,
            multimodal_inputs,
            stop_sequences: request.stop.clone(),
        })
    }

    /// Convert spec ChatMessage enum to tokenizer ChatMessage struct
    fn convert_messages_for_tokenizer(
        &self,
        messages: &[ChatMessage],
    ) -> Result<Vec<TokenizerChatMessage>, String> {
        let mut converted = Vec::new();

        for message in messages {
            let tokenizer_msg = match message {
                ChatMessage::System { content, .. } => TokenizerChatMessage::new("system", content),
                ChatMessage::User { content, .. } => {
                    let text_content = match content {
                        UserMessageContent::Text(text) => text.clone(),
                        UserMessageContent::Parts(parts) => {
                            // Simple text extraction for now - multimodal is placeholder
                            parts
                                .iter()
                                .filter_map(|part| match part {
                                    ContentPart::Text { text } => Some(text.as_str()),
                                    ContentPart::ImageUrl { .. } => None, // Skip images for now
                                })
                                .collect::<Vec<&str>>()
                                .join(" ")
                        }
                    };
                    TokenizerChatMessage::new("user", text_content)
                }
                ChatMessage::Assistant { content, .. } => {
                    // Simple content extraction - no special tool/reasoning formatting
                    TokenizerChatMessage::new("assistant", content.as_deref().unwrap_or(""))
                }
                ChatMessage::Tool { content, .. } => TokenizerChatMessage::new("tool", content),
                ChatMessage::Function { content, .. } => {
                    TokenizerChatMessage::new("function", content)
                }
            };
            converted.push(tokenizer_msg);
        }

        Ok(converted)
    }

    /// Build gRPC SamplingParams from OpenAI request
    fn build_grpc_sampling_params(
        &self,
        request: &ChatCompletionRequest,
        structural_tag: Option<String>,
    ) -> Result<proto::SamplingParams, String> {
        let stop_sequences = self.extract_stop_strings(request);

        // Handle max tokens: prefer max_completion_tokens (new) over max_tokens (deprecated)
        // If neither is specified, use None to let the backend decide the default
        #[allow(deprecated)]
        let max_new_tokens = request
            .max_completion_tokens
            .or(request.max_tokens)
            .map(|v| v as i32);

        #[allow(deprecated)]
        Ok(proto::SamplingParams {
            temperature: request.temperature.unwrap_or(1.0),
            top_p: request.top_p.unwrap_or(1.0),
            top_k: request.top_k.unwrap_or(-1),
            min_p: request.min_p.unwrap_or(0.0),
            frequency_penalty: request.frequency_penalty.unwrap_or(0.0),
            presence_penalty: request.presence_penalty.unwrap_or(0.0),
            repetition_penalty: request.repetition_penalty.unwrap_or(1.0),
            max_new_tokens,
            stop: stop_sequences,
            stop_token_ids: request.stop_token_ids.clone().unwrap_or_default(),
            skip_special_tokens: request.skip_special_tokens,
            n: request.n.unwrap_or(1) as i32,
            structural_tag: structural_tag.unwrap_or_default(),
            constraint: self.build_constraint(request)?,
            ..Default::default()
        })
    }

    /// Extract stop strings from request
    fn extract_stop_strings(&self, request: &ChatCompletionRequest) -> Vec<String> {
        match &request.stop {
            Some(StringOrArray::String(s)) => vec![s.clone()],
            Some(StringOrArray::Array(arr)) => arr.clone(),
            None => vec![],
        }
    }

    /// Build constraint for structured generation
    fn build_constraint(
        &self,
        request: &ChatCompletionRequest,
    ) -> Result<Option<proto::sampling_params::Constraint>, String> {
        if let Some(ResponseFormat::JsonSchema { json_schema }) = &request.response_format {
            let schema_str = serde_json::to_string(&json_schema.schema)
                .map_err(|e| format!("Failed to serialize JSON schema: {}", e))?;
            return Ok(Some(proto::sampling_params::Constraint::JsonSchema(
                schema_str,
            )));
        }

        if let Some(ebnf) = &request.ebnf {
            return Ok(Some(proto::sampling_params::Constraint::EbnfGrammar(
                ebnf.clone(),
            )));
        }

        if let Some(regex) = &request.regex {
            return Ok(Some(proto::sampling_params::Constraint::Regex(
                regex.clone(),
            )));
        }

        Ok(None)
    }

    /// Generate tool constraints for structured generation
    fn generate_tool_constraints(
        &self,
        _tools: &[crate::protocols::spec::Tool],
        _tool_choice: &Option<crate::protocols::spec::ToolChoice>,
        model: &str,
    ) -> Option<String> {
        let _parser = self.tool_parser_registry.get_parser(model)?;
        None
    }

    /// Select a worker for the request
    fn select_worker_for_request(
        &self,
        model_id: Option<&str>,
        text: Option<&str>,
    ) -> Option<Arc<dyn crate::core::Worker>> {
        // Get workers for the specified model, filtered by connection mode
        let workers = self.worker_registry.get_workers_filtered(
            model_id,
            Some(WorkerType::Regular),
            Some(crate::core::ConnectionMode::Grpc { port: None }),
            false, // get all workers, we'll filter by is_available() next
        );

        // Filter by availability (health + circuit breaker)
        let available: Vec<Arc<dyn crate::core::Worker>> = workers
            .iter()
            .filter(|w| w.is_available())
            .cloned()
            .collect();

        if available.is_empty() {
            return None;
        }

        // Get the appropriate policy for this model
        let policy = match model_id {
            Some(model) => self.policy_registry.get_policy_or_default(model),
            None => self.policy_registry.get_default_policy(),
        };

        // Select worker using the policy
        let idx = policy.select_worker(&available, text)?;
        Some(available[idx].clone())
    }

    /// Get or create a gRPC client for the worker
    async fn get_or_create_grpc_client(
        &self,
        worker_url: &str,
    ) -> Result<SglangSchedulerClient, String> {
        debug!("Creating new gRPC client for worker: {}", worker_url);
        SglangSchedulerClient::connect(worker_url)
            .await
            .map_err(|e| format!("Failed to connect to gRPC server: {}", e))
    }

    /// Placeholder for streaming handler (to be implemented in Phase 2)
    async fn handle_streaming_chat(
        &self,
        _client: SglangSchedulerClient,
        _request: proto::GenerateRequest,
        _original_request: &ChatCompletionRequest,
    ) -> Response {
        (StatusCode::NOT_IMPLEMENTED, "Streaming not yet implemented").into_response()
    }

    /// Placeholder for non-streaming handler (to be implemented in Phase 3)
    async fn handle_non_streaming_chat(
        &self,
        _client: SglangSchedulerClient,
        _request: proto::GenerateRequest,
        _original_request: &ChatCompletionRequest,
    ) -> Response {
        (
            StatusCode::NOT_IMPLEMENTED,
            "Non-streaming not yet implemented",
        )
            .into_response()
    }
516
517
518
519
}

impl std::fmt::Debug for GrpcRouter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520
        let stats = self.worker_registry.stats();
521
        f.debug_struct("GrpcRouter")
522
            .field("workers_count", &stats.total_workers)
523
524
525
526
            .field("timeout_secs", &self.timeout_secs)
            .field("interval_secs", &self.interval_secs)
            .field("dp_aware", &self.dp_aware)
            .finish()
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    }
}

#[async_trait]
impl RouterTrait for GrpcRouter {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    async fn health(&self, _req: Request<Body>) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn health_generate(&self, _req: Request<Body>) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn get_server_info(&self, _req: Request<Body>) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn get_models(&self, _req: Request<Body>) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn get_model_info(&self, _req: Request<Body>) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn route_generate(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &crate::protocols::spec::GenerateRequest,
560
        _model_id: Option<&str>,
561
562
563
564
565
566
    ) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn route_chat(
        &self,
567
568
569
        headers: Option<&HeaderMap>,
        body: &crate::protocols::spec::ChatCompletionRequest,
        model_id: Option<&str>,
570
    ) -> Response {
571
        self.route_chat_impl(headers, body, model_id).await
572
573
574
575
576
577
    }

    async fn route_completion(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &crate::protocols::spec::CompletionRequest,
578
        _model_id: Option<&str>,
579
580
581
582
    ) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

583
584
585
586
    async fn route_responses(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &crate::protocols::spec::ResponsesRequest,
587
        _model_id: Option<&str>,
588
589
590
591
    ) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

592
593
594
595
596
597
    async fn get_response(
        &self,
        _headers: Option<&HeaderMap>,
        _response_id: &str,
        _params: &crate::protocols::spec::ResponsesGetParams,
    ) -> Response {
598
599
600
601
602
603
604
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn cancel_response(&self, _headers: Option<&HeaderMap>, _response_id: &str) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

605
606
607
608
609
610
    async fn route_embeddings(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &crate::protocols::spec::EmbeddingRequest,
        _model_id: Option<&str>,
    ) -> Response {
611
612
613
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

614
615
616
617
    async fn route_rerank(
        &self,
        _headers: Option<&HeaderMap>,
        _body: &crate::protocols::spec::RerankRequest,
618
        _model_id: Option<&str>,
619
    ) -> Response {
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn flush_cache(&self) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

    async fn get_worker_loads(&self) -> Response {
        (StatusCode::NOT_IMPLEMENTED).into_response()
    }

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

    fn readiness(&self) -> Response {
        (StatusCode::SERVICE_UNAVAILABLE).into_response()
    }
}