server.rs 5.08 KB
Newer Older
1
2
3
4
use crate::router::create_router;
use crate::router::Router;
use actix_web::http::header::{HeaderValue, CONTENT_TYPE};
use actix_web::{get, post, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
5
6
7
8
9
10
11
12
13
use bytes::Bytes;
use futures_util::StreamExt;

#[derive(Debug)]
pub struct AppState {
    router: Box<dyn Router>,
    client: reqwest::Client,
}

14
impl AppState {
15
16
17
    pub fn new(worker_urls: Vec<String>, policy: String, client: reqwest::Client) -> Self {
        // Create router based on policy
        let router = create_router(worker_urls, policy);
18
19

        Self { router, client }
20
21
22
23
    }
}

#[get("/v1/models")]
24
25
async fn v1_model(data: web::Data<AppState>) -> impl Responder {
    let worker_url = match data.router.get_first() {
26
27
28
29
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };
    // Use the shared client
30
31
32
    match data
        .client
        .get(format!("{}/v1/models", worker_url))
33
        .send()
34
        .await
35
36
37
    {
        Ok(res) => {
            let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
38
39
                .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

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

#[get("/get_model_info")]
52
53
async fn get_model_info(data: web::Data<AppState>) -> impl Responder {
    let worker_url = match data.router.get_first() {
54
55
56
57
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };
    // Use the shared client
58
59
60
    match data
        .client
        .get(format!("{}/get_model_info", worker_url))
61
        .send()
62
        .await
63
64
65
    {
        Ok(res) => {
            let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
66
67
                .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

68
69
70
71
72
73
            // print the status
            println!("Worker URL: {}, Status: {}", worker_url, status);
            match res.bytes().await {
                Ok(body) => HttpResponse::build(status).body(body.to_vec()),
                Err(_) => HttpResponse::InternalServerError().finish(),
            }
74
        }
75
76
77
78
79
80
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

// no deser and ser, just forward and return
#[post("/generate")]
81
async fn generate(req: HttpRequest, body: Bytes, data: web::Data<AppState>) -> impl Responder {
82
83
    // create a router struct
    // TODO: use router abstraction for different policy
84
    let worker_url = match data.router.select() {
85
86
87
88
89
90
91
92
93
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };

    // Check if client requested streaming
    let is_stream = serde_json::from_slice::<serde_json::Value>(&body)
        .map(|v| v.get("stream").and_then(|s| s.as_bool()).unwrap_or(false))
        .unwrap_or(false);

94
95
96
    let res = match data
        .client
        .post(format!("{}/generate", worker_url))
97
        .header(
98
            "Content-Type",
99
100
101
            req.headers()
                .get("Content-Type")
                .and_then(|h| h.to_str().ok())
102
                .unwrap_or("application/json"),
103
104
105
        )
        .body(body.to_vec())
        .send()
106
        .await
107
108
109
110
111
112
113
114
115
116
117
118
    {
        Ok(res) => res,
        Err(_) => return HttpResponse::InternalServerError().finish(),
    };

    let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
        .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

    if !is_stream {
        match res.bytes().await {
            Ok(body) => HttpResponse::build(status).body(body.to_vec()),
            Err(_) => HttpResponse::InternalServerError().finish(),
119
        }
120
121
122
123
124
    } else {
        HttpResponse::build(status)
            .insert_header((CONTENT_TYPE, HeaderValue::from_static("text/event-stream")))
            .streaming(res.bytes_stream().map(|b| match b {
                Ok(b) => Ok::<_, actix_web::Error>(b),
125
126
127
                Err(_) => Err(actix_web::error::ErrorInternalServerError(
                    "Failed to read stream",
                )),
128
129
130
131
            }))
    }
}

132
133
134
135
136
137
pub async fn startup(
    host: String,
    port: u16,
    worker_urls: Vec<String>,
    routing_policy: String,
) -> std::io::Result<()> {
138
139
140
141
142
143
144
145
146
    println!("Starting server on {}:{}", host, port);
    println!("Worker URLs: {:?}", worker_urls);

    // Create client once with configuration
    let client = reqwest::Client::builder()
        .build()
        .expect("Failed to create HTTP client");

    // Store both worker_urls and client in AppState
147
    let app_state = web::Data::new(AppState::new(worker_urls, routing_policy, client));
148
149
150
151
152
153
154
155
156
157
158

    HttpServer::new(move || {
        App::new()
            .app_data(app_state.clone())
            .service(generate)
            .service(v1_model)
            .service(get_model_info)
    })
    .bind((host, port))?
    .run()
    .await
159
}