worker_initializer.rs 13.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
// Worker Initialization Module
// Separates worker lifecycle management from router construction

use crate::config::types::{ConnectionMode as ConfigConnectionMode, RouterConfig, RoutingMode};
use crate::core::{
    BasicWorkerBuilder, CircuitBreakerConfig, ConnectionMode, HealthConfig, WorkerRegistry,
    WorkerType,
};
use std::sync::Arc;
use std::time::Duration;
use tracing::{info, warn};

/// WorkerInitializer handles the creation and registration of workers
/// based on routing configuration, separating this concern from router constructors
pub struct WorkerInitializer;

impl WorkerInitializer {
    /// Initialize workers based on configuration and register them in the WorkerRegistry
    pub async fn initialize_workers(
        config: &RouterConfig,
        worker_registry: &Arc<WorkerRegistry>,
    ) -> Result<(), String> {
        info!("Initializing workers for routing mode: {:?}", config.mode);

        match &config.mode {
            RoutingMode::Regular { worker_urls } => {
                Self::create_regular_workers(
                    worker_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
                )
                .await?;
            }
            RoutingMode::PrefillDecode {
                prefill_urls,
                decode_urls,
                ..
            } => {
                Self::create_prefill_workers(
                    prefill_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
                )
                .await?;
                Self::create_decode_workers(
                    decode_urls,
                    &config.connection_mode,
                    config,
                    worker_registry,
                )
                .await?;
            }
            RoutingMode::OpenAI { .. } => {
                info!("OpenAI routing mode - no local workers to initialize");
            }
        }

        // Wait for workers to be healthy if any were registered
        if worker_registry.stats().total_workers > 0 {
            Self::wait_for_healthy_workers(
                worker_registry,
                config.worker_startup_timeout_secs,
                config.worker_startup_check_interval_secs,
            )
            .await?;
        }

        Ok(())
    }

    /// Create regular workers for standard routing mode
    async fn create_regular_workers(
        urls: &[String],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
    ) -> Result<(), String> {
        info!("Creating {} regular workers", urls.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(config_connection_mode, urls.first());

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        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),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

        for url in urls {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Regular)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

            let worker_id = registry.register(Arc::new(worker));
            info!("Registered regular worker {} with ID {:?}", url, worker_id);
        }

        Ok(())
    }

    /// Create prefill workers for disaggregated routing mode
    async fn create_prefill_workers(
        prefill_entries: &[(String, Option<u16>)],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
    ) -> Result<(), String> {
        info!("Creating {} prefill workers", prefill_entries.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(
            config_connection_mode,
            prefill_entries.first().map(|(url, _)| url),
        );

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        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),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

        for (url, bootstrap_port) in prefill_entries {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Prefill {
                    bootstrap_port: *bootstrap_port,
                })
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

            let worker_id = registry.register(Arc::new(worker));
            info!("Registered prefill worker {} with ID {:?}", url, worker_id);
        }

        Ok(())
    }

    /// Create decode workers for disaggregated routing mode
    async fn create_decode_workers(
        urls: &[String],
        config_connection_mode: &ConfigConnectionMode,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
    ) -> Result<(), String> {
        info!("Creating {} decode workers", urls.len());

        // Convert config connection mode to core connection mode
        let connection_mode = Self::convert_connection_mode(config_connection_mode, urls.first());

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        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),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

        for url in urls {
            // TODO: Add DP-aware support when we have dp_rank/dp_size info
            let worker = BasicWorkerBuilder::new(url.clone())
                .worker_type(WorkerType::Decode)
                .connection_mode(connection_mode.clone())
                .circuit_breaker_config(core_cb_config.clone())
                .health_config(health_config.clone())
                .build();

            let worker_id = registry.register(Arc::new(worker));
            info!("Registered decode worker {} with ID {:?}", url, worker_id);
        }

        Ok(())
    }

    /// Convert config connection mode to core connection mode
    fn convert_connection_mode(
        config_mode: &ConfigConnectionMode,
        _sample_url: Option<&String>,
    ) -> ConnectionMode {
        match config_mode {
            ConfigConnectionMode::Http => ConnectionMode::Http,
            ConfigConnectionMode::Grpc => ConnectionMode::Grpc { port: None },
        }
    }

    /// Wait for workers to become healthy
    async fn wait_for_healthy_workers(
        registry: &Arc<WorkerRegistry>,
        timeout_secs: u64,
        check_interval_secs: u64,
    ) -> Result<(), String> {
        let timeout = Duration::from_secs(timeout_secs);
        let check_interval = Duration::from_secs(check_interval_secs);
        let start_time = std::time::Instant::now();

        info!(
            "Waiting for workers to become healthy (timeout: {}s)",
            timeout_secs
        );

        loop {
            let stats = registry.stats();

            if stats.healthy_workers > 0 {
                info!(
                    "Workers healthy: {}/{} workers are ready",
                    stats.healthy_workers, stats.total_workers
                );

                // If we have at least one healthy worker, we can proceed
                // This allows partial degradation rather than total failure
                return Ok(());
            }

            if start_time.elapsed() > timeout {
                let error_msg = format!(
                    "Timeout waiting for workers to become healthy after {}s. Total workers: {}, Healthy: {}",
                    timeout_secs, stats.total_workers, stats.healthy_workers
                );
                warn!("{}", error_msg);

                // If we have workers but none are healthy, it's still a failure
                if stats.total_workers > 0 {
                    return Err(error_msg);
                } else {
                    // No workers at all might be OK for some configurations
                    warn!("No workers registered, proceeding anyway");
                    return Ok(());
                }
            }

            tokio::time::sleep(check_interval).await;
        }
    }

    /// Initialize workers for gRPC connections specifically
    /// This is used when gRPC clients are pre-connected
    pub async fn initialize_grpc_workers(
        worker_urls: &[String],
        worker_type: WorkerType,
        config: &RouterConfig,
        registry: &Arc<WorkerRegistry>,
        grpc_clients: &mut std::collections::HashMap<String, crate::grpc::SglangSchedulerClient>,
    ) -> Result<(), String> {
        info!(
            "Creating {} gRPC workers of type {:?}",
            worker_urls.len(),
            worker_type
        );

        // Convert circuit breaker config
        let circuit_breaker_config = config.effective_circuit_breaker_config();
        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),
        };

        // Convert health check config
        let health_config = HealthConfig {
            timeout_secs: config.health_check.timeout_secs,
            check_interval_secs: config.health_check.check_interval_secs,
            endpoint: config.health_check.endpoint.clone(),
            failure_threshold: config.health_check.failure_threshold,
            success_threshold: config.health_check.success_threshold,
        };

        for url in worker_urls {
            if let Some(client) = grpc_clients.remove(url) {
                let worker = BasicWorkerBuilder::new(url.clone())
                    .worker_type(worker_type.clone())
                    .connection_mode(ConnectionMode::Grpc { port: None })
                    .circuit_breaker_config(core_cb_config.clone())
                    .health_config(health_config.clone())
                    .grpc_client(client)
                    .build();

                let worker_id = registry.register(Arc::new(worker));
                info!("Registered gRPC worker {} with ID {:?}", url, worker_id);
            } else {
                warn!("No gRPC client available for worker {}, skipping", url);
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_convert_connection_mode() {
        // HTTP mode
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(
                &ConfigConnectionMode::Http,
                Some(&"http://localhost:8080".to_string())
            ),
            ConnectionMode::Http
        ));

        // gRPC mode
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(
                &ConfigConnectionMode::Grpc,
                Some(&"grpc://localhost:50051".to_string())
            ),
            ConnectionMode::Grpc { .. }
        ));

        // No URL provided
        assert!(matches!(
            WorkerInitializer::convert_connection_mode(&ConfigConnectionMode::Http, None),
            ConnectionMode::Http
        ));
    }
}