server.rs 6.24 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
        let router = Router::new(worker_urls, policy_config);
24
25

        Self { router, client }
26
27
28
    }
}

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

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

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#[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
}

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

80
    forward_request(&data.client, worker_url, "/get_server_info".to_string()).await
81
82
}

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

90
    forward_request(&data.client, worker_url, "/v1/models".to_string()).await
91
92
}

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

100
101
    forward_request(&data.client, worker_url, "/get_model_info".to_string()).await
}
102

103
104
#[post("/generate")]
async fn generate(req: HttpRequest, body: Bytes, data: web::Data<AppState>) -> impl Responder {
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
    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
130
131
}

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#[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")
        }
    };
    data.router.add_worker(worker_url);
    HttpResponse::Ok().finish()
}

148
149
150
151
152
153
154
155
156
157
158
159
160
#[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()
}

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
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();

    info!("Starting server on {}:{}", config.host, config.port);
    info!("Worker URLs: {:?}", config.worker_urls);
    info!("Policy Config: {:?}", config.policy_config);

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

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

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