2025-01-28 18:48:17 +00:00
|
|
|
use axum::{
|
|
|
|
routing::Router,
|
|
|
|
routing::{get, post},
|
|
|
|
};
|
2025-03-31 14:14:12 +00:00
|
|
|
use hyper::StatusCode;
|
|
|
|
use kvrouter::{
|
|
|
|
handler, set_backends_handler, Communicator, ContentAware, OverloadHandler, RoundRobin,
|
|
|
|
};
|
2025-01-28 18:48:17 +00:00
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
// List of backend servers
|
2025-04-08 07:40:45 +00:00
|
|
|
let backends = vec![
|
2025-03-31 14:14:12 +00:00
|
|
|
// "http://localhost:8000".to_string(),
|
2025-01-31 08:07:31 +00:00
|
|
|
// "http://localhost:8001".to_string(),
|
|
|
|
// "http://localhost:8002".to_string(),
|
|
|
|
// "http://localhost:8003".to_string(),
|
2025-04-08 07:40:45 +00:00
|
|
|
];
|
2025-01-28 18:48:17 +00:00
|
|
|
|
|
|
|
// Create a new instance of the RoundRobinRouter
|
|
|
|
|
2025-01-31 08:07:31 +00:00
|
|
|
println!("Using Content aware");
|
|
|
|
// Create the Axum router
|
2025-01-28 18:48:17 +00:00
|
|
|
|
2025-01-31 08:07:31 +00:00
|
|
|
let (sx, rx) = tokio::sync::mpsc::channel(100);
|
|
|
|
let communicator = Communicator::new(sx);
|
2025-04-10 07:14:30 +00:00
|
|
|
let host = std::env::var("TGI_KVROUTER_HOST").unwrap_or("127.0.0.1");
|
|
|
|
let port : u16= std::env::var("TGI_KVROUTER_PORT").unwrap_or("3000").parse()?;
|
2025-01-31 08:07:31 +00:00
|
|
|
tokio::task::spawn(async move {
|
|
|
|
if std::env::var("TGI_KVROUTER_LB").unwrap_or("".to_string()) == *"roundrobin" {
|
|
|
|
println!("Using round robin");
|
|
|
|
let lb = RoundRobin::new();
|
2025-04-10 07:14:30 +00:00
|
|
|
let mut router = OverloadHandler::new(lb, backends, rx);
|
2025-01-31 08:07:31 +00:00
|
|
|
router.run().await;
|
|
|
|
} else {
|
|
|
|
let lb = ContentAware::new();
|
2025-04-10 07:14:30 +00:00
|
|
|
let mut router = OverloadHandler::new(lb, backends, rx);
|
2025-01-31 08:07:31 +00:00
|
|
|
router.run().await;
|
|
|
|
};
|
|
|
|
});
|
|
|
|
let app = Router::new()
|
|
|
|
.route("/{*key}", get(handler))
|
|
|
|
.route("/{*key}", post(handler))
|
2025-03-31 14:14:12 +00:00
|
|
|
.route("/_kvrouter/health", get(|| async { StatusCode::OK }))
|
|
|
|
.route("/_kvrouter/set-backends", post(set_backends_handler))
|
2025-01-31 08:07:31 +00:00
|
|
|
.with_state(communicator);
|
|
|
|
|
|
|
|
// run it
|
2025-04-10 07:14:30 +00:00
|
|
|
let listener = tokio::net::TcpListener::bind((HOST, PORT)).await.unwrap();
|
2025-01-31 08:07:31 +00:00
|
|
|
println!("listening on {}", listener.local_addr().unwrap());
|
|
|
|
axum::serve(listener, app).await.unwrap();
|
2025-01-28 18:48:17 +00:00
|
|
|
}
|