Skip to main content

oxirs_chat/
server.rs

1//! HTTP Server and WebSocket Implementation for OxiRS Chat
2
3use axum::{
4    extract::{ws::WebSocket, Path, Query, State, WebSocketUpgrade},
5    http::{header, HeaderValue, Method, StatusCode},
6    response::Response,
7    routing::{get, post},
8    Json, Router,
9};
10// use axum_extra::headers::{Authorization, Bearer}; // Removed due to compilation issues
11use futures_util::{sink::SinkExt, stream::StreamExt};
12use serde::{Deserialize, Serialize};
13use std::{
14    collections::HashMap,
15    net::SocketAddr,
16    sync::Arc,
17    time::{Duration, SystemTime},
18};
19use tokio::sync::{broadcast, RwLock};
20use tower::ServiceBuilder;
21use tower_http::{
22    cors::{Any, CorsLayer},
23    trace::TraceLayer,
24};
25use tracing::{debug, error, info, warn};
26use uuid::Uuid;
27
28use crate::{MessageRole, OxiRSChat, ThreadInfo};
29
30/// Server state shared across handlers
31#[derive(Clone)]
32pub struct AppState {
33    pub chat: Arc<OxiRSChat>,
34    pub websocket_sessions: Arc<RwLock<HashMap<String, WebSocketSessionInfo>>>,
35    pub broadcast_tx: broadcast::Sender<ServerMessage>,
36    pub config: ServerConfig,
37    /// Process/server start instant, used to report real uptime in `/api/stats`.
38    pub started_at: std::time::Instant,
39}
40
41/// Server configuration
42#[derive(Debug, Clone)]
43pub struct ServerConfig {
44    pub host: String,
45    pub port: u16,
46    pub max_connections: usize,
47    pub session_timeout: Duration,
48    pub enable_metrics: bool,
49    pub cors_origins: Vec<String>,
50}
51
52impl Default for ServerConfig {
53    fn default() -> Self {
54        Self {
55            host: "localhost".to_string(),
56            port: 8080,
57            max_connections: 1000,
58            session_timeout: Duration::from_secs(3600),
59            enable_metrics: true,
60            cors_origins: vec!["*".to_string()],
61        }
62    }
63}
64
65/// WebSocket session information
66#[derive(Debug, Clone)]
67pub struct WebSocketSessionInfo {
68    pub session_id: String,
69    pub user_id: Option<String>,
70    pub connected_at: SystemTime,
71    pub last_activity: SystemTime,
72    pub subscribed_topics: std::collections::HashSet<String>,
73}
74
75/// Server-wide broadcast messages
76#[derive(Debug, Clone, Serialize)]
77pub struct ServerMessage {
78    pub message_type: ServerMessageType,
79    pub session_id: String,
80    pub data: serde_json::Value,
81}
82
83#[derive(Debug, Clone, Serialize)]
84#[serde(rename_all = "snake_case")]
85pub enum ServerMessageType {
86    ChatMessage,
87    SessionCreated,
88    SessionClosed,
89    SystemStatus,
90}
91
92/// REST API request/response types
93#[derive(Debug, Deserialize)]
94pub struct CreateSessionRequest {
95    pub user_id: Option<String>,
96    pub config: Option<serde_json::Value>,
97}
98
99#[derive(Debug, Serialize)]
100pub struct CreateSessionResponse {
101    pub session_id: String,
102    pub websocket_url: String,
103}
104
105#[derive(Debug, Deserialize)]
106pub struct SendMessageRequest {
107    pub content: String,
108    pub metadata: Option<serde_json::Value>,
109    pub thread_id: Option<String>,
110    pub parent_message_id: Option<String>,
111}
112
113#[derive(Debug, Serialize)]
114pub struct MessageResponse {
115    pub message_id: String,
116    pub content: String,
117    pub role: String,
118    pub timestamp: String,
119    pub metadata: Option<serde_json::Value>,
120    pub thread_id: Option<String>,
121    pub parent_message_id: Option<String>,
122    pub reactions: Vec<crate::MessageReaction>,
123}
124
125#[derive(Debug, Deserialize)]
126pub struct SessionQuery {
127    pub limit: Option<usize>,
128    pub offset: Option<usize>,
129}
130
131/// WebSocket message types
132#[derive(Debug, Deserialize)]
133#[serde(tag = "type")]
134pub enum WebSocketMessage {
135    #[serde(rename = "send_message")]
136    SendMessage {
137        content: String,
138        thread_id: Option<String>,
139        parent_message_id: Option<String>,
140    },
141    #[serde(rename = "ping")]
142    Ping,
143    #[serde(rename = "subscribe")]
144    Subscribe { topics: Vec<String> },
145    #[serde(rename = "add_reaction")]
146    AddReaction {
147        message_id: String,
148        emoji: String,
149        user_id: String,
150    },
151}
152
153#[derive(Debug, Serialize)]
154#[serde(tag = "type")]
155pub enum WebSocketResponse {
156    #[serde(rename = "message")]
157    Message {
158        message_id: String,
159        content: String,
160        role: String,
161        timestamp: String,
162        metadata: Option<serde_json::Value>,
163    },
164    #[serde(rename = "pong")]
165    Pong,
166    #[serde(rename = "error")]
167    Error { code: String, message: String },
168    #[serde(rename = "status")]
169    Status {
170        status: String,
171        data: serde_json::Value,
172    },
173}
174
175/// Main server implementation
176pub struct ChatServer {
177    state: AppState,
178}
179
180impl ChatServer {
181    pub fn new(chat: Arc<OxiRSChat>, config: ServerConfig) -> Self {
182        let (broadcast_tx, _) = broadcast::channel(1000);
183
184        let state = AppState {
185            chat,
186            websocket_sessions: Arc::new(RwLock::new(HashMap::new())),
187            broadcast_tx,
188            config,
189            started_at: std::time::Instant::now(),
190        };
191
192        Self { state }
193    }
194
195    pub async fn serve(self) -> Result<(), Box<dyn std::error::Error>> {
196        // Configure CORS based on server configuration
197        let cors = if self.state.config.cors_origins.contains(&"*".to_string()) {
198            // Allow any origin if wildcard is specified
199            CorsLayer::new()
200                .allow_origin(Any)
201                .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
202                .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
203        } else {
204            // Configure specific allowed origins
205            let origins: Result<Vec<HeaderValue>, _> = self
206                .state
207                .config
208                .cors_origins
209                .iter()
210                .map(|origin| origin.parse())
211                .collect();
212
213            match origins {
214                Ok(origins) => {
215                    info!(
216                        "Configuring CORS with specific origins: {:?}",
217                        self.state.config.cors_origins
218                    );
219                    CorsLayer::new()
220                        .allow_origin(origins)
221                        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
222                        .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
223                }
224                Err(e) => {
225                    warn!(
226                        "Invalid CORS origin configuration: {}, falling back to any origin",
227                        e
228                    );
229                    CorsLayer::new()
230                        .allow_origin(Any)
231                        .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
232                        .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
233                }
234            }
235        };
236
237        let middleware = ServiceBuilder::new()
238            .layer(TraceLayer::new_for_http())
239            .layer(cors);
240
241        let app = Self::build_router(self.state.clone()).layer(middleware);
242
243        let addr = SocketAddr::from(([127, 0, 0, 1], self.state.config.port));
244        info!("Starting chat server on {}", addr);
245
246        let listener = tokio::net::TcpListener::bind(addr).await?;
247        axum::serve(listener, app).await?;
248
249        Ok(())
250    }
251
252    /// Build the axum [`Router`] for the chat REST/WebSocket API.
253    ///
254    /// Split out from [`serve`](Self::serve) so the route table (and its
255    /// path-string syntax) can be exercised directly by tests without
256    /// binding a real TCP listener.
257    fn build_router(state: AppState) -> Router {
258        Router::new()
259            .route("/api/sessions", post(create_session))
260            .route("/api/sessions/{session_id}", get(get_session))
261            .route("/api/sessions/{session_id}/messages", post(send_message))
262            .route("/api/sessions/{session_id}/messages", get(get_messages))
263            .route("/api/sessions/{session_id}/threads", get(get_threads))
264            .route(
265                "/api/sessions/{session_id}/threads/{thread_id}/messages",
266                get(get_thread_messages),
267            )
268            .route(
269                "/api/sessions/{session_id}/messages/{message_id}/replies",
270                get(get_message_replies),
271            )
272            .route(
273                "/api/sessions/{session_id}/messages/{message_id}/reactions",
274                post(add_reaction),
275            )
276            .route("/api/sessions/{session_id}/ws", get(websocket_handler))
277            .route("/api/stats", get(get_stats))
278            .route("/health", get(health_check))
279            .route("/metrics", get(metrics_handler))
280            .with_state(state)
281    }
282}
283
284/// REST API Handlers
285async fn create_session(
286    State(state): State<AppState>,
287    Json(_request): Json<CreateSessionRequest>,
288) -> Result<Json<CreateSessionResponse>, StatusCode> {
289    let session_id = Uuid::new_v4().to_string();
290
291    match state.chat.create_session(session_id.clone()).await {
292        Ok(_) => {
293            let websocket_url = format!(
294                "ws://{}:{}/api/sessions/{}/ws",
295                state.config.host, state.config.port, session_id
296            );
297
298            Ok(Json(CreateSessionResponse {
299                session_id,
300                websocket_url,
301            }))
302        }
303        Err(e) => {
304            error!("Failed to create session: {}", e);
305            Err(StatusCode::INTERNAL_SERVER_ERROR)
306        }
307    }
308}
309
310async fn get_session(
311    Path(session_id): Path<String>,
312    State(state): State<AppState>,
313) -> Result<Json<serde_json::Value>, StatusCode> {
314    match state.chat.get_session(&session_id).await {
315        Some(session_arc) => {
316            let session = session_arc.lock().await;
317            Ok(Json(serde_json::json!({
318                "session_id": session_id,
319                "status": "active",
320                "message_count": session.messages.len(),
321                "created_at": session.created_at.to_rfc3339(),
322                "last_activity": session.last_activity.to_rfc3339()
323            })))
324        }
325        _ => Err(StatusCode::NOT_FOUND),
326    }
327}
328
329async fn send_message(
330    Path(session_id): Path<String>,
331    State(state): State<AppState>,
332    Json(request): Json<SendMessageRequest>,
333) -> Result<Json<MessageResponse>, StatusCode> {
334    // Fail-loud input screening (size limit + injection detection) before the
335    // content reaches RAG/LLM. Reject invalid input with 400 rather than 500.
336    if let Err(e) = state.chat.validate_input(&request.content) {
337        warn!("Rejected message input for session {}: {}", session_id, e);
338        return Err(StatusCode::BAD_REQUEST);
339    }
340
341    match state.chat.get_session(&session_id).await {
342        Some(_session_arc) => {
343            match state
344                .chat
345                .process_message_with_options(
346                    &session_id,
347                    request.content,
348                    request.thread_id,
349                    request.parent_message_id,
350                    request.metadata,
351                )
352                .await
353            {
354                Ok(message) => {
355                    // Session is automatically managed by OxiRSChat
356
357                    let response = MessageResponse {
358                        message_id: message.id,
359                        content: message.content.to_string(),
360                        role: match message.role {
361                            MessageRole::User => "user".to_string(),
362                            MessageRole::Assistant => "assistant".to_string(),
363                            MessageRole::System => "system".to_string(),
364                            MessageRole::Function => "function".to_string(),
365                        },
366                        timestamp: message.timestamp.to_rfc3339(),
367                        metadata: message
368                            .metadata
369                            .map(|m| serde_json::to_value(m).unwrap_or_default()),
370                        thread_id: message.thread_id,
371                        parent_message_id: message.parent_message_id,
372                        reactions: message.reactions,
373                    };
374
375                    Ok(Json(response))
376                }
377                Err(e) => {
378                    error!("Failed to process message: {}", e);
379                    Err(StatusCode::INTERNAL_SERVER_ERROR)
380                }
381            }
382        }
383        _ => Err(StatusCode::NOT_FOUND),
384    }
385}
386
387async fn get_messages(
388    Path(session_id): Path<String>,
389    Query(params): Query<SessionQuery>,
390    State(state): State<AppState>,
391) -> Result<Json<Vec<MessageResponse>>, StatusCode> {
392    match state.chat.get_session(&session_id).await {
393        Some(session_arc) => {
394            let session = session_arc.lock().await;
395            let messages: Vec<MessageResponse> = session
396                .messages
397                .iter()
398                .skip(params.offset.unwrap_or(0))
399                .take(params.limit.unwrap_or(100))
400                .map(|msg| MessageResponse {
401                    message_id: msg.id.clone(),
402                    content: msg.content.to_string(),
403                    role: match msg.role {
404                        MessageRole::User => "user".to_string(),
405                        MessageRole::Assistant => "assistant".to_string(),
406                        MessageRole::System => "system".to_string(),
407                        MessageRole::Function => "function".to_string(),
408                    },
409                    timestamp: msg.timestamp.to_rfc3339(),
410                    metadata: msg
411                        .metadata
412                        .as_ref()
413                        .map(|m| serde_json::to_value(m).unwrap_or_default()),
414                    thread_id: msg.thread_id.clone(),
415                    parent_message_id: msg.parent_message_id.clone(),
416                    reactions: msg.reactions.clone(),
417                })
418                .collect();
419
420            Ok(Json(messages))
421        }
422        _ => Err(StatusCode::NOT_FOUND),
423    }
424}
425
426async fn websocket_handler(
427    Path(session_id): Path<String>,
428    ws: WebSocketUpgrade,
429    State(state): State<AppState>,
430) -> Response {
431    ws.on_upgrade(move |socket| handle_websocket(socket, session_id, state))
432}
433
434async fn get_threads(
435    Path(session_id): Path<String>,
436    State(state): State<AppState>,
437) -> Result<Json<Vec<ThreadInfo>>, StatusCode> {
438    match state.chat.get_session(&session_id).await {
439        Some(session_arc) => {
440            let session = session_arc.lock().await;
441
442            // Aggregate distinct thread_id values from the session's messages.
443            let mut threads: HashMap<String, ThreadInfo> = HashMap::new();
444            for msg in &session.messages {
445                if let Some(thread_id) = &msg.thread_id {
446                    let entry = threads
447                        .entry(thread_id.clone())
448                        .or_insert_with(|| ThreadInfo {
449                            thread_id: thread_id.clone(),
450                            title: None,
451                            message_count: 0,
452                            created_at: msg.timestamp,
453                            last_activity: msg.timestamp,
454                        });
455                    entry.message_count += 1;
456                    if msg.timestamp < entry.created_at {
457                        entry.created_at = msg.timestamp;
458                    }
459                    if msg.timestamp > entry.last_activity {
460                        entry.last_activity = msg.timestamp;
461                    }
462                }
463            }
464
465            let mut threads: Vec<ThreadInfo> = threads.into_values().collect();
466            threads.sort_by_key(|t| std::cmp::Reverse(t.last_activity));
467            Ok(Json(threads))
468        }
469        _ => Err(StatusCode::NOT_FOUND),
470    }
471}
472
473async fn get_thread_messages(
474    Path((session_id, thread_id)): Path<(String, String)>,
475    State(state): State<AppState>,
476) -> Result<Json<Vec<MessageResponse>>, StatusCode> {
477    match state.chat.get_session(&session_id).await {
478        Some(session_arc) => {
479            let session = session_arc.lock().await;
480            let messages: Vec<MessageResponse> = session
481                .messages
482                .iter()
483                .filter(|msg| msg.thread_id.as_ref() == Some(&thread_id))
484                .map(|msg| MessageResponse {
485                    message_id: msg.id.clone(),
486                    content: msg.content.to_string(),
487                    role: match msg.role {
488                        MessageRole::User => "user".to_string(),
489                        MessageRole::Assistant => "assistant".to_string(),
490                        MessageRole::System => "system".to_string(),
491                        MessageRole::Function => "function".to_string(),
492                    },
493                    timestamp: msg.timestamp.to_rfc3339(),
494                    metadata: msg
495                        .metadata
496                        .as_ref()
497                        .map(|m| serde_json::to_value(m).unwrap_or_default()),
498                    thread_id: msg.thread_id.clone(),
499                    parent_message_id: msg.parent_message_id.clone(),
500                    reactions: msg.reactions.clone(),
501                })
502                .collect();
503
504            Ok(Json(messages))
505        }
506        _ => Err(StatusCode::NOT_FOUND),
507    }
508}
509
510async fn get_message_replies(
511    Path((session_id, message_id)): Path<(String, String)>,
512    State(state): State<AppState>,
513) -> Result<Json<Vec<MessageResponse>>, StatusCode> {
514    match state.chat.get_session(&session_id).await {
515        Some(session_arc) => {
516            let session = session_arc.lock().await;
517            let messages: Vec<MessageResponse> = session
518                .messages
519                .iter()
520                .filter(|msg| msg.parent_message_id.as_ref() == Some(&message_id))
521                .map(|msg| MessageResponse {
522                    message_id: msg.id.clone(),
523                    content: msg.content.to_string(),
524                    role: match msg.role {
525                        MessageRole::User => "user".to_string(),
526                        MessageRole::Assistant => "assistant".to_string(),
527                        MessageRole::System => "system".to_string(),
528                        MessageRole::Function => "function".to_string(),
529                    },
530                    timestamp: msg.timestamp.to_rfc3339(),
531                    metadata: msg
532                        .metadata
533                        .as_ref()
534                        .map(|m| serde_json::to_value(m).unwrap_or_default()),
535                    thread_id: msg.thread_id.clone(),
536                    parent_message_id: msg.parent_message_id.clone(),
537                    reactions: msg.reactions.clone(),
538                })
539                .collect();
540
541            Ok(Json(messages))
542        }
543        _ => Err(StatusCode::NOT_FOUND),
544    }
545}
546
547#[derive(Debug, Deserialize)]
548pub struct AddReactionRequest {
549    pub emoji: String,
550    pub user_id: String,
551}
552
553async fn add_reaction(
554    Path((session_id, message_id)): Path<(String, String)>,
555    State(state): State<AppState>,
556    Json(request): Json<AddReactionRequest>,
557) -> Result<StatusCode, StatusCode> {
558    match state.chat.get_session(&session_id).await {
559        Some(session_arc) => {
560            let mut session = session_arc.lock().await;
561            // Convert emoji string to ReactionType
562            let reaction_type = match request.emoji.as_str() {
563                "👍" | "like" => crate::ReactionType::Like,
564                "👎" | "dislike" => crate::ReactionType::Dislike,
565                "✅" | "helpful" => crate::ReactionType::Helpful,
566                "❌" | "not_helpful" => crate::ReactionType::NotHelpful,
567                "✔️" | "accurate" => crate::ReactionType::Accurate,
568                "inaccurate" => crate::ReactionType::Inaccurate,
569                "💭" | "clear" => crate::ReactionType::Clear,
570                "😵" | "confusing" => crate::ReactionType::Confusing,
571                _ => crate::ReactionType::Like, // Default to Like for unknown emojis
572            };
573
574            // Find and update the message
575            if let Some(message) = session.messages.iter_mut().find(|m| m.id == message_id) {
576                message.reactions.push(crate::MessageReaction {
577                    reaction_type,
578                    user_id: Some(request.user_id),
579                    timestamp: chrono::Utc::now(),
580                });
581
582                // Session is automatically managed
583                Ok(StatusCode::OK)
584            } else {
585                Err(StatusCode::NOT_FOUND)
586            }
587        }
588        _ => Err(StatusCode::NOT_FOUND),
589    }
590}
591
592async fn get_stats(State(state): State<AppState>) -> Result<Json<crate::SessionStats>, StatusCode> {
593    // Aggregate real per-session metrics (messages, tokens, activity/expiry
594    // state, response time) and report genuine process uptime.
595    let uptime_seconds = state.started_at.elapsed().as_secs();
596    let stats = state.chat.compute_session_stats(uptime_seconds).await;
597    Ok(Json(stats))
598}
599
600async fn handle_websocket(socket: WebSocket, session_id: String, state: AppState) {
601    let ws_session_id = Uuid::new_v4().to_string();
602    let ws_info = WebSocketSessionInfo {
603        session_id: session_id.clone(),
604        user_id: None,
605        connected_at: SystemTime::now(),
606        last_activity: SystemTime::now(),
607        subscribed_topics: std::collections::HashSet::new(),
608    };
609
610    {
611        let mut sessions = state.websocket_sessions.write().await;
612        sessions.insert(ws_session_id.clone(), ws_info);
613    }
614
615    let (mut sender, mut receiver) = socket.split();
616    let mut broadcast_rx = state.broadcast_tx.subscribe();
617
618    // Create a channel for sending messages to the websocket
619    let (tx, mut rx) = tokio::sync::mpsc::channel::<String>(100);
620    let tx_clone = tx.clone();
621
622    let session_id_clone = session_id.clone();
623    let _ws_session_id_clone = ws_session_id.clone();
624    let ws_session_id_cleanup = ws_session_id.clone();
625    let mut send_task = tokio::spawn(async move {
626        loop {
627            tokio::select! {
628                // Handle broadcast messages
629                Ok(msg) = broadcast_rx.recv() => {
630                    if msg.session_id == session_id_clone {
631                        let response = WebSocketResponse::Status {
632                            status: "broadcast".to_string(),
633                            data: msg.data,
634                        };
635
636                        if let Ok(json) = serde_json::to_string(&response) {
637                            if sender
638                                .send(axum::extract::ws::Message::Text(json.into()))
639                                .await
640                                .is_err()
641                            {
642                                break;
643                            }
644                        }
645                    }
646                }
647                // Handle direct messages
648                Some(msg) = rx.recv() => {
649                    if sender
650                        .send(axum::extract::ws::Message::Text(msg.into()))
651                        .await
652                        .is_err()
653                    {
654                        break;
655                    }
656                }
657            }
658        }
659    });
660
661    let state_clone = state.clone();
662    let mut recv_task = tokio::spawn(async move {
663        let tx = tx_clone;
664        let ws_session_id = ws_session_id.clone();
665        let state = state_clone;
666        while let Some(msg) = receiver.next().await {
667            if let Ok(msg) = msg {
668                match msg {
669                    axum::extract::ws::Message::Text(text) => {
670                        if let Ok(ws_msg) = serde_json::from_str::<WebSocketMessage>(&text) {
671                            match ws_msg {
672                                WebSocketMessage::SendMessage {
673                                    content,
674                                    thread_id,
675                                    parent_message_id,
676                                } => {
677                                    // Fail-loud input screening before processing.
678                                    if let Err(e) = state.chat.validate_input(&content) {
679                                        let error_response = WebSocketResponse::Error {
680                                            code: "INVALID_INPUT".to_string(),
681                                            message: format!("Input rejected: {e}"),
682                                        };
683                                        if let Ok(json) = serde_json::to_string(&error_response) {
684                                            let _ = tx.send(json).await;
685                                        }
686                                        continue;
687                                    }
688                                    // Process message using OxiRSChat, preserving thread context
689                                    match state
690                                        .chat
691                                        .process_message_with_options(
692                                            &session_id,
693                                            content,
694                                            thread_id,
695                                            parent_message_id,
696                                            None,
697                                        )
698                                        .await
699                                    {
700                                        Ok(response_msg) => {
701                                            let response = WebSocketResponse::Message {
702                                                message_id: response_msg.id,
703                                                content: response_msg.content.to_string(),
704                                                role: match response_msg.role {
705                                                    MessageRole::User => "user".to_string(),
706                                                    MessageRole::Assistant => {
707                                                        "assistant".to_string()
708                                                    }
709                                                    MessageRole::System => "system".to_string(),
710                                                    MessageRole::Function => "function".to_string(),
711                                                },
712                                                timestamp: response_msg.timestamp.to_rfc3339(),
713                                                metadata: response_msg.metadata.map(|m| {
714                                                    serde_json::to_value(m).unwrap_or_default()
715                                                }),
716                                            };
717
718                                            // Session is automatically managed by OxiRSChat
719
720                                            if let Ok(json) = serde_json::to_string(&response) {
721                                                let _ = tx.send(json).await;
722                                            }
723                                        }
724                                        _ => {
725                                            // Handle message processing error
726                                            let error_response = WebSocketResponse::Error {
727                                                code: "PROCESSING_ERROR".to_string(),
728                                                message: "Failed to process message".to_string(),
729                                            };
730                                            if let Ok(json) = serde_json::to_string(&error_response)
731                                            {
732                                                let _ = tx.send(json).await;
733                                            }
734                                        }
735                                    }
736                                }
737                                WebSocketMessage::Ping => {
738                                    let pong = WebSocketResponse::Pong;
739                                    if let Ok(json) = serde_json::to_string(&pong) {
740                                        let _ = tx.send(json).await;
741                                    }
742                                }
743                                WebSocketMessage::Subscribe { topics } => {
744                                    // Implement topic subscription
745                                    let mut sessions = state.websocket_sessions.write().await;
746                                    if let Some(ws_info) = sessions.get_mut(&ws_session_id) {
747                                        // Update subscribed topics
748                                        ws_info.subscribed_topics.clear();
749                                        for topic in &topics {
750                                            ws_info.subscribed_topics.insert(topic.clone());
751                                        }
752                                        ws_info.last_activity = SystemTime::now();
753
754                                        // Send confirmation
755                                        let response = WebSocketResponse::Status {
756                                            status: "subscribed".to_string(),
757                                            data: serde_json::json!({
758                                                "topics": topics,
759                                                "subscription_count": ws_info.subscribed_topics.len()
760                                            }),
761                                        };
762
763                                        if let Ok(json) = serde_json::to_string(&response) {
764                                            let _ = tx.send(json).await;
765                                        }
766
767                                        info!(
768                                            "WebSocket session {} subscribed to topics: {:?}",
769                                            ws_session_id, topics
770                                        );
771                                    } else {
772                                        // Session not found
773                                        let error_response = WebSocketResponse::Error {
774                                            code: "SESSION_NOT_FOUND".to_string(),
775                                            message: "WebSocket session not found".to_string(),
776                                        };
777                                        if let Ok(json) = serde_json::to_string(&error_response) {
778                                            let _ = tx.send(json).await;
779                                        }
780                                    }
781                                }
782                                WebSocketMessage::AddReaction {
783                                    message_id,
784                                    emoji,
785                                    user_id,
786                                } => {
787                                    if let Some(session_arc) =
788                                        state.chat.get_session(&session_id).await
789                                    {
790                                        let mut session = session_arc.lock().await;
791                                        // Convert emoji to reaction type
792                                        let reaction_type = match emoji.as_str() {
793                                            "👍" | "like" => crate::ReactionType::Like,
794                                            "👎" | "dislike" => crate::ReactionType::Dislike,
795                                            "✅" | "helpful" => crate::ReactionType::Helpful,
796                                            "❌" | "not_helpful" => {
797                                                crate::ReactionType::NotHelpful
798                                            }
799                                            "✔️" | "accurate" => crate::ReactionType::Accurate,
800                                            "inaccurate" => crate::ReactionType::Inaccurate,
801                                            "💭" | "clear" => crate::ReactionType::Clear,
802                                            "😵" | "confusing" => crate::ReactionType::Confusing,
803                                            _ => crate::ReactionType::Like,
804                                        };
805
806                                        if let Some(message) =
807                                            session.messages.iter_mut().find(|m| m.id == message_id)
808                                        {
809                                            message.reactions.push(crate::MessageReaction {
810                                                reaction_type,
811                                                user_id: Some(user_id),
812                                                timestamp: chrono::Utc::now(),
813                                            });
814
815                                            let response = WebSocketResponse::Status {
816                                                status: "reaction_added".to_string(),
817                                                data: serde_json::json!({
818                                                    "message_id": message_id,
819                                                    "success": true
820                                                }),
821                                            };
822
823                                            if let Ok(json) = serde_json::to_string(&response) {
824                                                let _ = tx.send(json).await;
825                                            }
826                                        } else {
827                                            // Message not found
828                                            let error_response = WebSocketResponse::Error {
829                                                code: "NOT_FOUND".to_string(),
830                                                message: "Message not found".to_string(),
831                                            };
832                                            if let Ok(json) = serde_json::to_string(&error_response)
833                                            {
834                                                let _ = tx.send(json).await;
835                                            }
836                                        }
837                                    }
838                                }
839                            }
840                        }
841                    }
842                    axum::extract::ws::Message::Close(_) => break,
843                    _ => {}
844                }
845            }
846        }
847    });
848
849    // When either side finishes (typically the client disconnecting, which ends
850    // `recv_task`), abort the other task so it cannot leak — otherwise the
851    // surviving `send_task` keeps its split WS sink and broadcast subscription
852    // alive indefinitely on a `broadcast_rx.recv()` arm.
853    tokio::select! {
854        _ = &mut send_task => {
855            recv_task.abort();
856        },
857        _ = &mut recv_task => {
858            send_task.abort();
859        },
860    }
861
862    {
863        let mut sessions = state.websocket_sessions.write().await;
864        sessions.remove(&ws_session_id_cleanup);
865    }
866}
867
868async fn health_check() -> Json<serde_json::Value> {
869    Json(serde_json::json!({
870        "status": "healthy",
871        "timestamp": chrono::Utc::now().to_rfc3339(),
872        "service": "oxirs-chat"
873    }))
874}
875
876async fn metrics_handler() -> Result<String, StatusCode> {
877    // Basic Prometheus metrics implementation
878    let mut metrics = vec![
879        "# HELP oxirs_chat_requests_total Total number of requests received".to_string(),
880        "# TYPE oxirs_chat_requests_total counter".to_string(),
881        "# HELP oxirs_chat_sessions_active Number of active chat sessions".to_string(),
882        "# TYPE oxirs_chat_sessions_active gauge".to_string(),
883        "# HELP oxirs_chat_messages_total Total number of messages processed".to_string(),
884        "# TYPE oxirs_chat_messages_total counter".to_string(),
885        "# HELP oxirs_chat_response_time_seconds Response time in seconds".to_string(),
886        "# TYPE oxirs_chat_response_time_seconds histogram".to_string(),
887        "# HELP oxirs_chat_sparql_queries_total Total number of SPARQL queries generated"
888            .to_string(),
889        "# TYPE oxirs_chat_sparql_queries_total counter".to_string(),
890        "# HELP oxirs_chat_llm_requests_total Total number of LLM requests".to_string(),
891        "# TYPE oxirs_chat_llm_requests_total counter".to_string(),
892        "# HELP oxirs_chat_errors_total Total number of errors".to_string(),
893        "# TYPE oxirs_chat_errors_total counter".to_string(),
894    ];
895
896    // Sample metric values (in production, these would be collected from actual metrics)
897    let timestamp = std::time::SystemTime::now()
898        .duration_since(std::time::UNIX_EPOCH)
899        .expect("SystemTime should be after UNIX_EPOCH")
900        .as_millis();
901
902    metrics.push(format!(
903        "oxirs_chat_requests_total{{method=\"POST\",endpoint=\"/api/sessions\"}} 150 {timestamp}"
904    ));
905    metrics.push(format!(
906        "oxirs_chat_requests_total{{method=\"GET\",endpoint=\"/api/sessions\"}} 45 {timestamp}"
907    ));
908    metrics.push(format!(
909        "oxirs_chat_requests_total{{method=\"POST\",endpoint=\"/api/sessions/messages\"}} 320 {timestamp}"
910    ));
911
912    metrics.push(format!("oxirs_chat_sessions_active 12 {timestamp}"));
913    metrics.push(format!("oxirs_chat_messages_total 1250 {timestamp}"));
914
915    metrics.push(format!(
916        "oxirs_chat_response_time_seconds_bucket{{le=\"0.1\"}} 45 {timestamp}"
917    ));
918    metrics.push(format!(
919        "oxirs_chat_response_time_seconds_bucket{{le=\"0.5\"}} 120 {timestamp}"
920    ));
921    metrics.push(format!(
922        "oxirs_chat_response_time_seconds_bucket{{le=\"1.0\"}} 180 {timestamp}"
923    ));
924    metrics.push(format!(
925        "oxirs_chat_response_time_seconds_bucket{{le=\"2.0\"}} 195 {timestamp}"
926    ));
927    metrics.push(format!(
928        "oxirs_chat_response_time_seconds_bucket{{le=\"+Inf\"}} 200 {timestamp}"
929    ));
930
931    metrics.push(format!(
932        "oxirs_chat_sparql_queries_total{{status=\"success\"}} 85 {timestamp}"
933    ));
934    metrics.push(format!(
935        "oxirs_chat_sparql_queries_total{{status=\"failed\"}} 5 {timestamp}"
936    ));
937
938    metrics.push(format!(
939        "oxirs_chat_llm_requests_total{{provider=\"openai\",model=\"gpt-4\"}} 120 {timestamp}"
940    ));
941    metrics.push(format!(
942        "oxirs_chat_llm_requests_total{{provider=\"anthropic\",model=\"claude-3-opus\"}} 80 {timestamp}"
943    ));
944
945    metrics.push(format!(
946        "oxirs_chat_errors_total{{type=\"validation\"}} 3 {timestamp}"
947    ));
948    metrics.push(format!(
949        "oxirs_chat_errors_total{{type=\"llm_timeout\"}} 2 {timestamp}"
950    ));
951    metrics.push(format!(
952        "oxirs_chat_errors_total{{type=\"sparql_generation\"}} 1 {timestamp}"
953    ));
954
955    Ok(metrics.join("\n"))
956}
957
958/// Broadcast a message to all WebSocket clients subscribed to a specific topic
959async fn broadcast_to_topic(
960    state: &AppState,
961    topic: &str,
962    message: serde_json::Value,
963) -> Result<usize, Box<dyn std::error::Error>> {
964    let sessions = state.websocket_sessions.read().await;
965    let mut sent_count = 0;
966
967    // Create the broadcast message
968    let server_message = ServerMessage {
969        message_type: ServerMessageType::SystemStatus,
970        session_id: "system".to_string(),
971        data: serde_json::json!({
972            "topic": topic,
973            "message": message
974        }),
975    };
976
977    // Find all sessions subscribed to this topic
978    for (ws_session_id, ws_info) in sessions.iter() {
979        if ws_info.subscribed_topics.contains(topic) {
980            // Send the message via broadcast channel
981            if state.broadcast_tx.send(server_message.clone()).is_ok() {
982                sent_count += 1;
983                debug!(
984                    "Sent topic '{}' message to WebSocket session: {}",
985                    topic, ws_session_id
986                );
987            }
988        }
989    }
990
991    if sent_count > 0 {
992        info!(
993            "Broadcasted topic '{}' message to {} subscribers",
994            topic, sent_count
995        );
996    }
997
998    Ok(sent_count)
999}
1000
1001/// Get list of all active topics with subscriber counts
1002async fn get_active_topics(state: &AppState) -> HashMap<String, usize> {
1003    let sessions = state.websocket_sessions.read().await;
1004    let mut topic_counts: HashMap<String, usize> = HashMap::new();
1005
1006    for ws_info in sessions.values() {
1007        for topic in &ws_info.subscribed_topics {
1008            *topic_counts.entry(topic.clone()).or_insert(0) += 1;
1009        }
1010    }
1011
1012    topic_counts
1013}
1014
1015#[cfg(test)]
1016mod tests {
1017    use super::*;
1018    use crate::OxiRSChat;
1019
1020    /// Regression test for the axum 0.8 route-syntax migration.
1021    ///
1022    /// `Router::route` parses every path string at *construction* time
1023    /// (matchit 0.8 under axum 0.8), not at compile time. Old-style
1024    /// `:param` / `*wildcard` segments compile fine but panic the instant
1025    /// the router is built. This test builds the real router via
1026    /// [`ChatServer::build_router`] with the cheapest valid `AppState` so
1027    /// any reintroduction of the old syntax fails the test suite instead
1028    /// of surfacing only as a startup panic in production.
1029    ///
1030    /// Deliberately a plain (non-async) `#[test]`: `OxiRSChat::create_default`
1031    /// spins up its own single-use Tokio runtime internally, and nesting
1032    /// that inside a `#[tokio::test]` runtime would itself panic.
1033    #[test]
1034    fn build_router_accepts_axum_08_route_syntax() {
1035        let chat = Arc::new(
1036            OxiRSChat::create_default().expect("failed to build default OxiRSChat for test"),
1037        );
1038        let (broadcast_tx, _rx) = broadcast::channel(16);
1039        let state = AppState {
1040            chat,
1041            websocket_sessions: Arc::new(RwLock::new(HashMap::new())),
1042            broadcast_tx,
1043            config: ServerConfig::default(),
1044            started_at: std::time::Instant::now(),
1045        };
1046
1047        // Must not panic: constructing the router forces axum to parse
1048        // every route path string registered in `build_router`.
1049        let _router: Router = ChatServer::build_router(state);
1050    }
1051}