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

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

18
impl AppState {
19
20
21
22
23
    pub fn new(
        worker_urls: Vec<String>,
        client: reqwest::Client,
        policy_config: PolicyConfig,
    ) -> Self {
24
        // Create router based on policy
25
        let router = Router::new(worker_urls, policy_config);
26
27

        Self { router, client }
28
29
30
    }
}

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

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

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

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

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

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

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

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

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

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

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#[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()
}

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

184
185
186
187
    let client = reqwest::Client::builder()
        .build()
        .expect("Failed to create HTTP client");

188
189
190
191
192
    let app_state = web::Data::new(AppState::new(
        config.worker_urls,
        client,
        config.policy_config,
    ));
193
194
195
196
197

    HttpServer::new(move || {
        App::new()
            .app_data(app_state.clone())
            .service(generate)
198
199
200
            .service(v1_chat_completions)
            .service(v1_completions)
            .service(v1_models)
201
            .service(get_model_info)
202
203
            .service(health)
            .service(health_generate)
204
            .service(get_server_info)
205
            .service(add_worker)
206
    })
207
    .bind((config.host, config.port))?
208
209
    .run()
    .await
210
}