"vscode:/vscode.git/clone" did not exist on "0478d440f0ba62202bc4b98043ae4a7d0b85e4ba"
server.rs 5.13 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
use actix_web::{get, post, web, App, HttpServer, HttpResponse, HttpRequest, Responder};
use bytes::Bytes;
use futures_util::StreamExt;
use actix_web::http::header::{HeaderValue, CONTENT_TYPE};
use crate::router::Router;
use crate::router::create_router;


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


impl AppState
{
    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);
        
        Self {
            router,
            client,
        }
    }
}

#[get("/v1/models")]
async fn v1_model(
    data: web::Data<AppState>,
) -> impl Responder {
    let worker_url= match data.router.get_first() {
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };
    // Use the shared client
    match data.client
        .get(&format!("{}/v1/models", worker_url))
        .send()
        .await 
    {
        Ok(res) => {
            let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);
        
            // 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(),
            }
        },
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

#[get("/get_model_info")]
async fn get_model_info(
    data: web::Data<AppState>,
) -> impl Responder {
    let worker_url= match data.router.get_first() {
        Some(url) => url,
        None => return HttpResponse::InternalServerError().finish(),
    };
    // Use the shared client
    match data.client
        .get(&format!("{}/get_model_info", worker_url))
        .send()
        .await 
    {
        Ok(res) => {
            let status = actix_web::http::StatusCode::from_u16(res.status().as_u16())
            .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);
        
            // 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(),
            }
        },
        Err(_) => HttpResponse::InternalServerError().finish(),
    }
}

// no deser and ser, just forward and return
#[post("/generate")]
async fn generate(
    req: HttpRequest,
    body: Bytes,
    data: web::Data<AppState>,
) -> impl Responder {

    // create a router struct
    // TODO: use router abstraction for different policy
    let worker_url= match data.router.select() {
        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);

    let res = match data.client
        .post(&format!("{}/generate", worker_url))
        .header(
            "Content-Type", 
            req.headers()
                .get("Content-Type")
                .and_then(|h| h.to_str().ok())
                .unwrap_or("application/json")
        )
        .body(body.to_vec())
        .send()
        .await 
    {
        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(),
        } 
    } 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),
                Err(_) => Err(actix_web::Error::from(actix_web::error::ErrorInternalServerError("Failed to read stream"))),
            }))
    }
}

pub async fn startup(host: String, port: u16, worker_urls: Vec<String>, routing_policy: String) -> std::io::Result<()> {
    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
    let app_state = web::Data::new(AppState::new(
        worker_urls,
        routing_policy,
        client,
    ));

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