2025-12-03 18:42:22 -03:00
|
|
|
use axum::{
|
2025-12-10 22:58:09 -03:00
|
|
|
body::Body,
|
|
|
|
|
extract::{
|
|
|
|
|
ws::{Message as AxumMessage, WebSocket, WebSocketUpgrade},
|
|
|
|
|
OriginalUri, Query, State,
|
|
|
|
|
},
|
|
|
|
|
http::{Request, StatusCode},
|
|
|
|
|
response::{Html, IntoResponse, Response},
|
|
|
|
|
routing::{any, get},
|
2025-12-03 18:42:22 -03:00
|
|
|
Router,
|
|
|
|
|
};
|
2025-12-10 22:58:09 -03:00
|
|
|
use futures_util::{SinkExt, StreamExt};
|
|
|
|
|
use log::{debug, error, info};
|
|
|
|
|
use serde::Deserialize;
|
2025-12-04 09:33:31 -03:00
|
|
|
use std::{fs, path::PathBuf};
|
2025-12-10 22:58:09 -03:00
|
|
|
use tokio_tungstenite::{
|
2025-12-15 23:16:09 -03:00
|
|
|
connect_async_tls_with_config, tungstenite::protocol::Message as TungsteniteMessage,
|
2025-12-10 22:58:09 -03:00
|
|
|
};
|
2025-12-20 19:58:04 -03:00
|
|
|
use tower_http::services::ServeDir;
|
2025-12-03 18:42:22 -03:00
|
|
|
|
2025-12-04 09:33:31 -03:00
|
|
|
use crate::shared::AppState;
|
2025-12-03 18:42:22 -03:00
|
|
|
|
2025-12-20 19:58:04 -03:00
|
|
|
const SUITE_DIRS: &[&str] = &[
|
|
|
|
|
"js",
|
|
|
|
|
"css",
|
|
|
|
|
"public",
|
|
|
|
|
"drive",
|
|
|
|
|
"chat",
|
|
|
|
|
"mail",
|
|
|
|
|
"tasks",
|
|
|
|
|
"calendar",
|
|
|
|
|
"meet",
|
|
|
|
|
"paper",
|
|
|
|
|
"research",
|
|
|
|
|
"analytics",
|
|
|
|
|
"monitoring",
|
|
|
|
|
"admin",
|
|
|
|
|
"auth",
|
|
|
|
|
"settings",
|
|
|
|
|
"sources",
|
|
|
|
|
"attendant",
|
|
|
|
|
"tools",
|
|
|
|
|
"assets",
|
|
|
|
|
"partials",
|
|
|
|
|
];
|
|
|
|
|
|
2025-12-03 18:42:22 -03:00
|
|
|
pub async fn index() -> impl IntoResponse {
|
2025-12-10 21:55:25 -03:00
|
|
|
serve_suite().await
|
2025-12-03 18:42:22 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn serve_minimal() -> impl IntoResponse {
|
|
|
|
|
match fs::read_to_string("ui/minimal/index.html") {
|
|
|
|
|
Ok(html) => (StatusCode::OK, [("content-type", "text/html")], Html(html)),
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Failed to load minimal UI: {}", e);
|
|
|
|
|
(
|
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
|
[("content-type", "text/plain")],
|
|
|
|
|
Html("Failed to load minimal interface".to_string()),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn serve_suite() -> impl IntoResponse {
|
|
|
|
|
match fs::read_to_string("ui/suite/index.html") {
|
|
|
|
|
Ok(html) => (StatusCode::OK, [("content-type", "text/html")], Html(html)),
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Failed to load suite UI: {}", e);
|
|
|
|
|
(
|
|
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
|
[("content-type", "text/plain")],
|
|
|
|
|
Html("Failed to load suite interface".to_string()),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-04 09:33:31 -03:00
|
|
|
async fn health(State(state): State<AppState>) -> (StatusCode, axum::Json<serde_json::Value>) {
|
|
|
|
|
match state.health_check().await {
|
2025-12-03 18:42:22 -03:00
|
|
|
true => (
|
|
|
|
|
StatusCode::OK,
|
|
|
|
|
axum::Json(serde_json::json!({
|
|
|
|
|
"status": "healthy",
|
|
|
|
|
"service": "botui",
|
|
|
|
|
"mode": "web"
|
|
|
|
|
})),
|
|
|
|
|
),
|
|
|
|
|
false => (
|
|
|
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
|
|
|
axum::Json(serde_json::json!({
|
|
|
|
|
"status": "unhealthy",
|
|
|
|
|
"service": "botui",
|
|
|
|
|
"error": "botserver unreachable"
|
|
|
|
|
})),
|
|
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn api_health() -> (StatusCode, axum::Json<serde_json::Value>) {
|
|
|
|
|
(
|
|
|
|
|
StatusCode::OK,
|
|
|
|
|
axum::Json(serde_json::json!({
|
|
|
|
|
"status": "ok",
|
2025-12-04 09:33:31 -03:00
|
|
|
"version": env!("CARGO_PKG_VERSION")
|
2025-12-03 18:42:22 -03:00
|
|
|
})),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-17 17:42:55 -03:00
|
|
|
fn extract_app_context(headers: &axum::http::HeaderMap, path: &str) -> Option<String> {
|
|
|
|
|
if let Some(referer) = headers.get("referer") {
|
|
|
|
|
if let Ok(referer_str) = referer.to_str() {
|
|
|
|
|
if let Some(start) = referer_str.find("/apps/") {
|
|
|
|
|
let after_apps = &referer_str[start + 6..];
|
|
|
|
|
if let Some(end) = after_apps.find('/') {
|
|
|
|
|
return Some(after_apps[..end].to_string());
|
|
|
|
|
} else if !after_apps.is_empty() {
|
|
|
|
|
return Some(after_apps.to_string());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if path.starts_with("/apps/") {
|
|
|
|
|
let after_apps = &path[6..];
|
|
|
|
|
if let Some(end) = after_apps.find('/') {
|
|
|
|
|
return Some(after_apps[..end].to_string());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
async fn proxy_api(
|
|
|
|
|
State(state): State<AppState>,
|
|
|
|
|
original_uri: OriginalUri,
|
|
|
|
|
req: Request<Body>,
|
|
|
|
|
) -> Response<Body> {
|
|
|
|
|
let path = original_uri.path();
|
2025-12-15 23:16:09 -03:00
|
|
|
let query = original_uri
|
|
|
|
|
.query()
|
|
|
|
|
.map(|q| format!("?{}", q))
|
|
|
|
|
.unwrap_or_default();
|
2025-12-10 22:58:09 -03:00
|
|
|
let method = req.method().clone();
|
|
|
|
|
let headers = req.headers().clone();
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-17 17:42:55 -03:00
|
|
|
let app_context = extract_app_context(&headers, path);
|
|
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let target_url = format!("{}{}{}", state.client.base_url(), path, query);
|
2025-12-17 17:42:55 -03:00
|
|
|
debug!(
|
|
|
|
|
"Proxying {} {} to {} (app: {:?})",
|
|
|
|
|
method, path, target_url, app_context
|
|
|
|
|
);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let client = reqwest::Client::builder()
|
|
|
|
|
.danger_accept_invalid_certs(true)
|
|
|
|
|
.build()
|
|
|
|
|
.unwrap_or_else(|_| reqwest::Client::new());
|
|
|
|
|
let mut proxy_req = client.request(method.clone(), &target_url);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
for (name, value) in headers.iter() {
|
|
|
|
|
if name != "host" {
|
|
|
|
|
if let Ok(v) = value.to_str() {
|
|
|
|
|
proxy_req = proxy_req.header(name.as_str(), v);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-17 17:42:55 -03:00
|
|
|
if let Some(app) = app_context {
|
|
|
|
|
proxy_req = proxy_req.header("X-App-Context", app);
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let body_bytes = match axum::body::to_bytes(req.into_body(), usize::MAX).await {
|
|
|
|
|
Ok(bytes) => bytes,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Failed to read request body: {}", e);
|
|
|
|
|
return Response::builder()
|
|
|
|
|
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
|
|
|
|
.body(Body::from("Failed to read request body"))
|
|
|
|
|
.unwrap();
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
if !body_bytes.is_empty() {
|
|
|
|
|
proxy_req = proxy_req.body(body_bytes.to_vec());
|
|
|
|
|
}
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
match proxy_req.send().await {
|
|
|
|
|
Ok(resp) => {
|
|
|
|
|
let status = resp.status();
|
|
|
|
|
let headers = resp.headers().clone();
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
match resp.bytes().await {
|
|
|
|
|
Ok(body) => {
|
|
|
|
|
let mut response = Response::builder().status(status);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
for (name, value) in headers.iter() {
|
|
|
|
|
response = response.header(name, value);
|
|
|
|
|
}
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
response.body(Body::from(body)).unwrap_or_else(|_| {
|
|
|
|
|
Response::builder()
|
|
|
|
|
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
|
|
|
|
.body(Body::from("Failed to build response"))
|
|
|
|
|
.unwrap()
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Failed to read response body: {}", e);
|
|
|
|
|
Response::builder()
|
|
|
|
|
.status(StatusCode::BAD_GATEWAY)
|
|
|
|
|
.body(Body::from(format!("Failed to read response: {}", e)))
|
|
|
|
|
.unwrap()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Proxy request failed: {}", e);
|
|
|
|
|
Response::builder()
|
|
|
|
|
.status(StatusCode::BAD_GATEWAY)
|
|
|
|
|
.body(Body::from(format!("Proxy error: {}", e)))
|
|
|
|
|
.unwrap()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn create_api_router() -> Router<AppState> {
|
|
|
|
|
Router::new()
|
|
|
|
|
.route("/health", get(api_health))
|
|
|
|
|
.fallback(any(proxy_api))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
|
|
|
struct WsQuery {
|
|
|
|
|
session_id: String,
|
|
|
|
|
user_id: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn ws_proxy(
|
|
|
|
|
ws: WebSocketUpgrade,
|
|
|
|
|
State(state): State<AppState>,
|
|
|
|
|
Query(params): Query<WsQuery>,
|
|
|
|
|
) -> impl IntoResponse {
|
|
|
|
|
ws.on_upgrade(move |socket| handle_ws_proxy(socket, state, params))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn handle_ws_proxy(client_socket: WebSocket, state: AppState, params: WsQuery) {
|
|
|
|
|
let backend_url = format!(
|
|
|
|
|
"{}/ws?session_id={}&user_id={}",
|
2025-12-15 23:16:09 -03:00
|
|
|
state
|
|
|
|
|
.client
|
|
|
|
|
.base_url()
|
|
|
|
|
.replace("https://", "wss://")
|
|
|
|
|
.replace("http://", "ws://"),
|
2025-12-10 22:58:09 -03:00
|
|
|
params.session_id,
|
|
|
|
|
params.user_id
|
|
|
|
|
);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
info!("Proxying WebSocket to: {}", backend_url);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let tls_connector = native_tls::TlsConnector::builder()
|
|
|
|
|
.danger_accept_invalid_certs(true)
|
|
|
|
|
.danger_accept_invalid_hostnames(true)
|
|
|
|
|
.build()
|
|
|
|
|
.expect("Failed to build TLS connector");
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let connector = tokio_tungstenite::Connector::NativeTls(tls_connector);
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-15 23:16:09 -03:00
|
|
|
let backend_result =
|
|
|
|
|
connect_async_tls_with_config(&backend_url, None, false, Some(connector)).await;
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let backend_socket = match backend_result {
|
|
|
|
|
Ok((socket, _)) => socket,
|
|
|
|
|
Err(e) => {
|
|
|
|
|
error!("Failed to connect to backend WebSocket: {}", e);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
info!("Connected to backend WebSocket");
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let (mut client_tx, mut client_rx) = client_socket.split();
|
|
|
|
|
let (mut backend_tx, mut backend_rx) = backend_socket.split();
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let client_to_backend = async {
|
|
|
|
|
while let Some(msg) = client_rx.next().await {
|
|
|
|
|
match msg {
|
|
|
|
|
Ok(AxumMessage::Text(text)) => {
|
2025-12-15 23:16:09 -03:00
|
|
|
if backend_tx
|
|
|
|
|
.send(TungsteniteMessage::Text(text))
|
|
|
|
|
.await
|
|
|
|
|
.is_err()
|
|
|
|
|
{
|
2025-12-10 22:58:09 -03:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(AxumMessage::Binary(data)) => {
|
2025-12-15 23:16:09 -03:00
|
|
|
if backend_tx
|
|
|
|
|
.send(TungsteniteMessage::Binary(data))
|
|
|
|
|
.await
|
|
|
|
|
.is_err()
|
|
|
|
|
{
|
2025-12-10 22:58:09 -03:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(AxumMessage::Ping(data)) => {
|
2025-12-15 23:16:09 -03:00
|
|
|
if backend_tx
|
|
|
|
|
.send(TungsteniteMessage::Ping(data))
|
|
|
|
|
.await
|
|
|
|
|
.is_err()
|
|
|
|
|
{
|
2025-12-10 22:58:09 -03:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(AxumMessage::Pong(data)) => {
|
2025-12-15 23:16:09 -03:00
|
|
|
if backend_tx
|
|
|
|
|
.send(TungsteniteMessage::Pong(data))
|
|
|
|
|
.await
|
|
|
|
|
.is_err()
|
|
|
|
|
{
|
2025-12-10 22:58:09 -03:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(AxumMessage::Close(_)) | Err(_) => break,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
let backend_to_client = async {
|
|
|
|
|
while let Some(msg) = backend_rx.next().await {
|
|
|
|
|
match msg {
|
|
|
|
|
Ok(TungsteniteMessage::Text(text)) => {
|
|
|
|
|
if client_tx.send(AxumMessage::Text(text)).await.is_err() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(TungsteniteMessage::Binary(data)) => {
|
|
|
|
|
if client_tx.send(AxumMessage::Binary(data)).await.is_err() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(TungsteniteMessage::Ping(data)) => {
|
|
|
|
|
if client_tx.send(AxumMessage::Ping(data)).await.is_err() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(TungsteniteMessage::Pong(data)) => {
|
|
|
|
|
if client_tx.send(AxumMessage::Pong(data)).await.is_err() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Ok(TungsteniteMessage::Close(_)) | Err(_) => break,
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
2025-12-12 17:33:11 -03:00
|
|
|
|
2025-12-10 22:58:09 -03:00
|
|
|
tokio::select! {
|
|
|
|
|
_ = client_to_backend => info!("Client connection closed"),
|
|
|
|
|
_ = backend_to_client => info!("Backend connection closed"),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn create_ws_router() -> Router<AppState> {
|
2025-12-15 23:16:09 -03:00
|
|
|
Router::new().fallback(any(ws_proxy))
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-17 17:42:55 -03:00
|
|
|
fn create_apps_router() -> Router<AppState> {
|
2025-12-20 19:58:04 -03:00
|
|
|
Router::new().fallback(any(proxy_api))
|
2025-12-17 17:42:55 -03:00
|
|
|
}
|
|
|
|
|
|
2025-12-15 23:16:09 -03:00
|
|
|
fn create_ui_router() -> Router<AppState> {
|
2025-12-20 19:58:04 -03:00
|
|
|
Router::new().fallback(any(proxy_api))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn add_static_routes(router: Router<AppState>, suite_path: &PathBuf) -> Router<AppState> {
|
|
|
|
|
let mut r = router;
|
|
|
|
|
|
|
|
|
|
for dir in SUITE_DIRS {
|
|
|
|
|
let path = suite_path.join(dir);
|
|
|
|
|
r = r
|
|
|
|
|
.nest_service(&format!("/suite/{}", dir), ServeDir::new(path.clone()))
|
|
|
|
|
.nest_service(&format!("/{}", dir), ServeDir::new(path));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
r
|
2025-12-10 22:58:09 -03:00
|
|
|
}
|
|
|
|
|
|
2025-12-04 09:33:31 -03:00
|
|
|
pub fn configure_router() -> Router {
|
|
|
|
|
let suite_path = PathBuf::from("./ui/suite");
|
|
|
|
|
let state = AppState::new();
|
|
|
|
|
|
2025-12-20 19:58:04 -03:00
|
|
|
let mut router = Router::new()
|
2025-12-04 09:33:31 -03:00
|
|
|
.route("/health", get(health))
|
2025-12-10 22:58:09 -03:00
|
|
|
.nest("/api", create_api_router())
|
2025-12-15 23:16:09 -03:00
|
|
|
.nest("/ui", create_ui_router())
|
2025-12-10 22:58:09 -03:00
|
|
|
.nest("/ws", create_ws_router())
|
2025-12-17 17:42:55 -03:00
|
|
|
.nest("/apps", create_apps_router())
|
2025-12-04 09:33:31 -03:00
|
|
|
.route("/", get(index))
|
|
|
|
|
.route("/minimal", get(serve_minimal))
|
2025-12-20 19:58:04 -03:00
|
|
|
.route("/suite", get(serve_suite));
|
|
|
|
|
|
|
|
|
|
router = add_static_routes(router, &suite_path);
|
|
|
|
|
|
|
|
|
|
router
|
2025-12-04 09:33:31 -03:00
|
|
|
.fallback_service(
|
2025-12-20 19:58:04 -03:00
|
|
|
ServeDir::new(suite_path.clone())
|
|
|
|
|
.fallback(ServeDir::new(suite_path).append_index_html_on_directories(true)),
|
2025-12-04 09:33:31 -03:00
|
|
|
)
|
|
|
|
|
.with_state(state)
|
2025-12-03 18:42:22 -03:00
|
|
|
}
|