Skip to main content

yaiko_core/
websocket.rs

1//! WebSocket support for Yaiko applications
2//!
3//! Provides WebSocket upgrade handling and connection management
4//! with rooms, keepalive, rate limiting, and typed message serialization.
5
6use crate::{Request, Response};
7use hyper::{Body, StatusCode};
8use std::collections::{HashMap, HashSet};
9use std::sync::Arc;
10use std::time::Instant;
11use tokio::sync::RwLock;
12
13/// WebSocket connection manager
14pub struct WebSocketManager {
15    connections: Arc<RwLock<HashMap<String, WebSocketConnection>>>,
16    rooms: Arc<RwLock<HashMap<String, HashSet<String>>>>,
17    rate_limits: Arc<RwLock<HashMap<String, Vec<Instant>>>>,
18}
19
20/// Represents an active WebSocket connection
21pub struct WebSocketConnection {
22    pub id: String,
23    pub user_id: Option<String>,
24    pub metadata: HashMap<String, String>,
25    pub sender: Option<tokio::sync::mpsc::Sender<String>>,
26}
27
28impl WebSocketManager {
29    /// Create a new WebSocket manager
30    pub fn new() -> Self {
31        Self {
32            connections: Arc::new(RwLock::new(HashMap::new())),
33            rooms: Arc::new(RwLock::new(HashMap::new())),
34            rate_limits: Arc::new(RwLock::new(HashMap::new())),
35        }
36    }
37
38    /// Get the number of active connections
39    pub async fn connection_count(&self) -> usize {
40        self.connections.read().await.len()
41    }
42
43    /// Register a new connection
44    pub async fn register(
45        &self,
46        id: String,
47        user_id: Option<String>,
48        sender: Option<tokio::sync::mpsc::Sender<String>>,
49    ) {
50        let conn = WebSocketConnection {
51            id: id.clone(),
52            user_id,
53            metadata: HashMap::new(),
54            sender,
55        };
56        self.connections.write().await.insert(id, conn);
57    }
58
59    /// Remove a connection and clean up its room memberships
60    pub async fn unregister(&self, id: &str) {
61        self.connections.write().await.remove(id);
62        // Remove from all rooms
63        let mut rooms = self.rooms.write().await;
64        for members in rooms.values_mut() {
65            members.remove(id);
66        }
67        // Remove empty rooms
68        rooms.retain(|_, members| !members.is_empty());
69        // Remove rate limit tracking
70        self.rate_limits.write().await.remove(id);
71    }
72
73    /// Get all connection IDs
74    pub async fn get_connection_ids(&self) -> Vec<String> {
75        self.connections.read().await.keys().cloned().collect()
76    }
77
78    // ── Sending ─────────────────────────────────────────────
79
80    /// Send a message to a specific connection by ID
81    pub async fn send(&self, id: &str, msg: String) -> Result<(), &'static str> {
82        let connections = self.connections.read().await;
83        if let Some(conn) = connections.get(id) {
84            if let Some(sender) = &conn.sender {
85                if sender.send(msg).await.is_ok() {
86                    return Ok(());
87                }
88            }
89        }
90        Err("Connection not found or sender unavailable")
91    }
92
93    /// Send a message to all connections belonging to a specific user
94    pub async fn send_to_user(&self, user_id: &str, msg: String) {
95        let connections = self.connections.read().await;
96        for conn in connections.values() {
97            if conn.user_id.as_deref() == Some(user_id) {
98                if let Some(sender) = &conn.sender {
99                    let _ = sender.send(msg.clone()).await;
100                }
101            }
102        }
103    }
104
105    /// Broadcast a message to all active connections
106    pub async fn broadcast(&self, msg: String) {
107        let connections = self.connections.read().await;
108        for conn in connections.values() {
109            if let Some(sender) = &conn.sender {
110                let _ = sender.send(msg.clone()).await;
111            }
112        }
113    }
114
115    /// Send a JSON-serializable value to a specific connection
116    pub async fn send_json<T: serde::Serialize>(&self, id: &str, data: &T) -> Result<(), String> {
117        let json_str = serde_json::to_string(data).map_err(|e| e.to_string())?;
118        self.send(id, json_str).await.map_err(|e| e.to_string())
119    }
120
121    /// Broadcast a JSON-serializable value to all connections
122    pub async fn broadcast_json<T: serde::Serialize>(&self, data: &T) -> Result<(), String> {
123        let json_str = serde_json::to_string(data).map_err(|e| e.to_string())?;
124        self.broadcast(json_str).await;
125        Ok(())
126    }
127
128    // ── Rooms ───────────────────────────────────────────────
129
130    /// Add a connection to a room
131    pub async fn join_room(&self, conn_id: &str, room: &str) {
132        self.rooms
133            .write()
134            .await
135            .entry(room.to_string())
136            .or_insert_with(HashSet::new)
137            .insert(conn_id.to_string());
138    }
139
140    /// Remove a connection from a room
141    pub async fn leave_room(&self, conn_id: &str, room: &str) {
142        let mut rooms = self.rooms.write().await;
143        if let Some(members) = rooms.get_mut(room) {
144            members.remove(conn_id);
145            if members.is_empty() {
146                rooms.remove(room);
147            }
148        }
149    }
150
151    /// Send a message to all connections in a room
152    pub async fn send_to_room(&self, room: &str, msg: String) {
153        let rooms = self.rooms.read().await;
154        if let Some(members) = rooms.get(room) {
155            let connections = self.connections.read().await;
156            for member_id in members {
157                if let Some(conn) = connections.get(member_id) {
158                    if let Some(sender) = &conn.sender {
159                        let _ = sender.send(msg.clone()).await;
160                    }
161                }
162            }
163        }
164    }
165
166    /// Get all connection IDs in a room
167    pub async fn get_room_members(&self, room: &str) -> Vec<String> {
168        self.rooms
169            .read()
170            .await
171            .get(room)
172            .map(|m| m.iter().cloned().collect())
173            .unwrap_or_default()
174    }
175
176    // ── Keepalive & Cleanup ─────────────────────────────────
177
178    /// Start a background keepalive loop that pings connections and removes dead ones
179    pub fn start_keepalive(self: Arc<Self>, interval_secs: u64) -> tokio::task::JoinHandle<()> {
180        tokio::spawn(async move {
181            let mut interval =
182                tokio::time::interval(tokio::time::Duration::from_secs(interval_secs));
183            loop {
184                interval.tick().await;
185
186                let mut dead_ids = Vec::new();
187                {
188                    let connections = self.connections.read().await;
189                    for (id, conn) in connections.iter() {
190                        if let Some(sender) = &conn.sender {
191                            if sender.send("__ping".to_string()).await.is_err() {
192                                dead_ids.push(id.clone());
193                            }
194                        } else {
195                            dead_ids.push(id.clone());
196                        }
197                    }
198                }
199
200                // Remove dead connections
201                for id in &dead_ids {
202                    tracing::info!(conn_id = %id, "Removing dead WebSocket connection");
203                    self.unregister(id).await;
204                }
205            }
206        })
207    }
208
209    // ── Rate Limiting ───────────────────────────────────────
210
211    /// Check if a connection is within its rate limit.
212    /// Returns `true` if allowed, `false` if rate-limited.
213    /// Records the timestamp if allowed.
214    pub async fn check_rate_limit(&self, id: &str, max_per_sec: u32) -> bool {
215        let now = Instant::now();
216        let mut limits = self.rate_limits.write().await;
217        let timestamps = limits.entry(id.to_string()).or_insert_with(Vec::new);
218
219        // Prune entries older than 1 second
220        timestamps.retain(|t| now.duration_since(*t).as_secs_f64() < 1.0);
221
222        if (timestamps.len() as u32) < max_per_sec {
223            timestamps.push(now);
224            true
225        } else {
226            false
227        }
228    }
229}
230
231impl Default for WebSocketManager {
232    fn default() -> Self {
233        Self::new()
234    }
235}
236
237/// Check if a request is a WebSocket upgrade request
238pub fn is_websocket_upgrade(req: &Request) -> bool {
239    let upgrade = req
240        .headers
241        .get("upgrade")
242        .and_then(|v| v.to_str().ok())
243        .map(|s| s.to_lowercase())
244        .unwrap_or_default();
245
246    let connection = req
247        .headers
248        .get("connection")
249        .and_then(|v| v.to_str().ok())
250        .map(|s| s.to_lowercase())
251        .unwrap_or_default();
252
253    upgrade == "websocket" && connection.contains("upgrade")
254}
255
256/// Create a WebSocket upgrade response
257///
258/// Note: This creates the HTTP upgrade response headers.
259pub fn websocket_upgrade_response(key: &str) -> Response {
260    use base64::{engine::general_purpose::STANDARD, Engine as _};
261
262    // Calculate Sec-WebSocket-Accept
263    let mut hasher = sha1_smol::Sha1::new();
264    hasher.update(format!("{}258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key).as_bytes());
265    let accept = STANDARD.encode(hasher.digest().bytes());
266
267    Response {
268        status: StatusCode::SWITCHING_PROTOCOLS,
269        headers: {
270            let mut h = HashMap::new();
271            h.insert("Upgrade".to_string(), "websocket".to_string());
272            h.insert("Connection".to_string(), "Upgrade".to_string());
273            h.insert("Sec-WebSocket-Accept".to_string(), accept);
274            h
275        },
276        body: Body::empty(),
277    }
278}
279
280/// Handle a complete WebSocket upgrade within a route handler.
281///
282/// This function:
283/// 1. Validates the upgrade request and extracts the key
284/// 2. Creates an mpsc channel for outbound messages
285/// 3. Registers the connection with the WebSocketManager
286/// 4. Returns the upgrade response
287///
288/// The caller should spawn the actual frame read/write loop separately
289/// using the returned `Receiver<String>` for outbound messages.
290///
291/// # Example
292/// ```rust,ignore
293/// async fn ws_handler(req: Request) -> Result<Response, BoxError> {
294///     let manager = get_ws_manager(); // your shared manager
295///     let (response, conn_id, rx) = handle_websocket_upgrade(&req, manager.clone(), None).await?;
296///     // Spawn your frame loop using `rx` for outbound and the manager for inbound
297///     Ok(response)
298/// }
299/// ```
300pub async fn handle_websocket_upgrade(
301    req: &Request,
302    manager: Arc<WebSocketManager>,
303    user_id: Option<String>,
304) -> Result<
305    (Response, String, tokio::sync::mpsc::Receiver<String>),
306    Box<dyn std::error::Error + Send + Sync>,
307> {
308    if !is_websocket_upgrade(req) {
309        return Err("Not a WebSocket upgrade request".into());
310    }
311
312    let key = req
313        .headers
314        .get("sec-websocket-key")
315        .and_then(|v| v.to_str().ok())
316        .ok_or("Missing Sec-WebSocket-Key header")?;
317
318    let response = websocket_upgrade_response(key);
319
320    // Create a channel for outbound messages to this connection
321    let (tx, rx) = tokio::sync::mpsc::channel::<String>(256);
322
323    let conn_id = uuid::Uuid::new_v4().to_string();
324    manager.register(conn_id.clone(), user_id, Some(tx)).await;
325
326    Ok((response, conn_id, rx))
327}
328
329/// A message received on a WebSocket connection
330#[derive(Debug, Clone)]
331pub enum WsMessage {
332    /// A text message
333    Text(String),
334    /// A binary message
335    Binary(Vec<u8>),
336    /// A ping message
337    Ping,
338    /// A pong message
339    Pong,
340    /// Connection closed
341    Close,
342}