server.rs 6.5 KB
Newer Older
1
use crate::router::PolicyConfig;
2
use crate::router::Router;
3
use actix_web::{get, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
4
use bytes::Bytes;
5
use env_logger::Builder;
Byron Hsu's avatar
Byron Hsu committed
6
use log::{info, LevelFilter};
7
use std::collections::HashMap;
8
use std::io::Write;
9
10
11

#[derive(Debug)]
pub struct AppState {
12
    router: Router,
13
14
15
    client: reqwest::Client,
}

16
impl AppState {
17
18
19
20
21
    pub fn new(
        worker_urls: Vec<String>,
        client: reqwest::Client,
        policy_config: PolicyConfig,
    ) -> Self {
22
        // Create router based on policy
23
24
25
26
        let router = match Router::new(worker_urls, policy_config) {
            Ok(router) => router,
            Err(error) => panic!("Failed to create router: {}", error),
        };
27
28

        Self { router, client }
29
30
31
    }
}

32
33
34
35
36
37
async fn forward_request(
    client: &reqwest::Client,
    worker_url: String,
    route: String,
) -> HttpResponse {
    match client.get(format!("{}{}", worker_url, route)).send().await {
38
39
        Ok(res) => {
            let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
40
41
                .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

42
            // print the status
43
44
45
46
            println!(
                "Forwarding Request Worker URL: {}, Route: {}, Status: {}",
                worker_url, route, status
            );
47
48
49
50
            match res.bytes().await {
                Ok(body) => HttpResponse::build(status).body(body.to_vec()),
                Err(_) => HttpResponse::InternalServerError().finish(),
            }
51
        }
52
53
54
55
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#[get("/health")]
async fn health(data: web::Data<AppState>) -> impl Responder {
    let worker_url = match data.router.get_first() {
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };

    forward_request(&data.client, worker_url, "/health".to_string()).await
}

#[get("/health_generate")]
async fn health_generate(data: web::Data<AppState>) -> impl Responder {
    let worker_url = match data.router.get_first() {
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };

    forward_request(&data.client, worker_url, "/health_generate".to_string()).await
}

76
77
#[get("/get_server_info")]
async fn get_server_info(data: web::Data<AppState>) -> impl Responder {
78
79
80
81
82
    let worker_url = match data.router.get_first() {
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };

83
    forward_request(&data.client, worker_url, "/get_server_info".to_string()).await
84
85
}

86
#[get("/v1/models")]
87
async fn v1_models(data: web::Data<AppState>) -> impl Responder {
88
    let worker_url = match data.router.get_first() {
89
90
91
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };
92

93
    forward_request(&data.client, worker_url, "/v1/models".to_string()).await
94
95
}

96
97
98
#[get("/get_model_info")]
async fn get_model_info(data: web::Data<AppState>) -> impl Responder {
    let worker_url = match data.router.get_first() {
99
100
101
102
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };

103
104
    forward_request(&data.client, worker_url, "/get_model_info".to_string()).await
}
105

106
107
#[post("/generate")]
async fn generate(req: HttpRequest, body: Bytes, data: web::Data<AppState>) -> impl Responder {
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
    data.router
        .dispatch(&data.client, req, body, "generate")
        .await
}

#[post("/v1/chat/completions")]
async fn v1_chat_completions(
    req: HttpRequest,
    body: Bytes,
    data: web::Data<AppState>,
) -> impl Responder {
    data.router
        .dispatch(&data.client, req, body, "v1/chat/completions")
        .await
}

#[post("/v1/completions")]
async fn v1_completions(
    req: HttpRequest,
    body: Bytes,
    data: web::Data<AppState>,
) -> impl Responder {
    data.router
        .dispatch(&data.client, req, body, "v1/completions")
        .await
133
134
}

135
136
137
138
139
140
141
142
143
144
145
146
#[post("/add_worker")]
async fn add_worker(
    query: web::Query<HashMap<String, String>>,
    data: web::Data<AppState>,
) -> impl Responder {
    let worker_url = match query.get("url") {
        Some(url) => url.to_string(),
        None => {
            return HttpResponse::BadRequest()
                .body("Worker URL required. Provide 'url' query parameter")
        }
    };
147
148
149
150
151

    match data.router.add_worker(worker_url).await {
        Ok(message) => HttpResponse::Ok().body(message),
        Err(error) => HttpResponse::BadRequest().body(error),
    }
152
153
}

154
155
156
157
158
159
160
161
162
163
164
165
166
#[post("/remove_worker")]
async fn remove_worker(
    query: web::Query<HashMap<String, String>>,
    data: web::Data<AppState>,
) -> impl Responder {
    let worker_url = match query.get("url") {
        Some(url) => url.to_string(),
        None => return HttpResponse::BadRequest().finish(),
    };
    data.router.remove_worker(worker_url);
    HttpResponse::Ok().finish()
}

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
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub worker_urls: Vec<String>,
    pub policy_config: PolicyConfig,
    pub verbose: bool,
}

pub async fn startup(config: ServerConfig) -> std::io::Result<()> {
    Builder::new()
        .format(|buf, record| {
            use chrono::Local;
            writeln!(
                buf,
                "[Router (Rust)] {} - {} - {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"),
                record.level(),
                record.args()
            )
        })
        .filter(
            None,
            if config.verbose {
                LevelFilter::Debug
            } else {
                LevelFilter::Info
            },
        )
        .init();

197
198
199
200
    let client = reqwest::Client::builder()
        .build()
        .expect("Failed to create HTTP client");

201
    let app_state = web::Data::new(AppState::new(
202
        config.worker_urls.clone(),
203
        client,
204
        config.policy_config.clone(),
205
    ));
206

207
208
209
210
    info!("✅ Starting router on {}:{}", config.host, config.port);
    info!("✅ Serving Worker URLs: {:?}", config.worker_urls);
    info!("✅ Policy Config: {:?}", config.policy_config);

211
212
213
214
    HttpServer::new(move || {
        App::new()
            .app_data(app_state.clone())
            .service(generate)
215
216
217
            .service(v1_chat_completions)
            .service(v1_completions)
            .service(v1_models)
218
            .service(get_model_info)
219
220
            .service(health)
            .service(health_generate)
221
            .service(get_server_info)
222
            .service(add_worker)
223
            .service(remove_worker)
224
    })
225
    .bind((config.host, config.port))?
226
227
    .run()
    .await
228
}