| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use serde::{Deserialize, Serialize}; |
| use std::collections::{HashMap, VecDeque}; |
| use std::sync::atomic::{AtomicU64, Ordering}; |
| use std::sync::Mutex; |
| use axum::extract::ws::{WebSocket, Message}; |
| use futures_util::{SinkExt, StreamExt}; |
|
|
| |
| |
| |
|
|
| |
| |
| pub static CHANNEL_HUB: Mutex<Option<ChannelHub>> = Mutex::new(None); |
|
|
| |
| static MSG_SEQ: AtomicU64 = AtomicU64::new(0); |
|
|
| |
| |
| |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| #[serde(rename_all = "lowercase")] |
| pub enum MessageType { |
| |
| Text, |
| |
| System, |
| |
| ToolResult, |
| } |
|
|
| |
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct ChannelMessage { |
| |
| pub id: String, |
| |
| pub channel_id: String, |
| |
| pub from: String, |
| |
| pub from_name: String, |
| |
| pub text: String, |
| |
| pub timestamp: String, |
| |
| pub msg_type: MessageType, |
| } |
|
|
| |
| |
| fn new_message_id() -> String { |
| let ts = chrono::Utc::now().timestamp_millis(); |
| let seq = MSG_SEQ.fetch_add(1, Ordering::Relaxed); |
| format!("msg-{}-{}", ts, seq) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| #[derive(Debug, Clone)] |
| pub struct Participant { |
| |
| pub key: String, |
| |
| pub name: String, |
| |
| |
| pub ws_sender: Option<tokio::sync::mpsc::UnboundedSender<String>>, |
| } |
|
|
| |
| |
| |
|
|
| |
| const MAX_CHANNEL_HISTORY: usize = 1000; |
|
|
| |
| |
| pub struct Channel { |
| |
| pub id: String, |
| |
| pub name: String, |
| |
| pub created_by: String, |
| |
| pub created_at: String, |
| |
| pub participants: Vec<Participant>, |
| |
| pub messages: VecDeque<ChannelMessage>, |
| } |
|
|
| impl Channel { |
| |
| pub fn new(id: String, name: String, created_by: String) -> Self { |
| Self { |
| id, |
| name, |
| created_by, |
| created_at: chrono::Utc::now().to_rfc3339(), |
| participants: Vec::new(), |
| messages: VecDeque::new(), |
| } |
| } |
|
|
| |
| pub fn add_participant(&mut self, key: &str, name: &str) -> bool { |
| if self.participants.iter().any(|p| p.key == key) { |
| return false; |
| } |
| self.participants.push(Participant { |
| key: key.to_string(), |
| name: name.to_string(), |
| ws_sender: None, |
| }); |
| true |
| } |
|
|
| |
| pub fn remove_participant(&mut self, key: &str) -> bool { |
| let before = self.participants.len(); |
| self.participants.retain(|p| p.key != key); |
| self.participants.len() < before |
| } |
|
|
| |
| pub fn has_participant(&self, key: &str) -> bool { |
| self.participants.iter().any(|p| p.key == key) |
| } |
|
|
| |
| pub fn set_ws_sender( |
| &mut self, |
| key: &str, |
| sender: tokio::sync::mpsc::UnboundedSender<String>, |
| ) -> bool { |
| if let Some(p) = self.participants.iter_mut().find(|p| p.key == key) { |
| p.ws_sender = Some(sender); |
| true |
| } else { |
| false |
| } |
| } |
|
|
| |
| pub fn clear_ws_sender(&mut self, key: &str) { |
| if let Some(p) = self.participants.iter_mut().find(|p| p.key == key) { |
| p.ws_sender = None; |
| } |
| } |
|
|
| |
| pub fn push_message(&mut self, msg: ChannelMessage) { |
| if self.messages.len() >= MAX_CHANNEL_HISTORY { |
| self.messages.pop_front(); |
| } |
| self.messages.push_back(msg); |
| } |
|
|
| |
| pub fn get_history(&self, limit: usize) -> Vec<&ChannelMessage> { |
| let start = self.messages.len().saturating_sub(limit); |
| self.messages.iter().skip(start).collect() |
| } |
|
|
| |
| |
| |
| pub fn broadcast(&mut self, msg: &ChannelMessage) -> usize { |
| let json = match serde_json::to_string(msg) { |
| Ok(j) => j, |
| Err(_) => return 0, |
| }; |
|
|
| let mut delivered = 0; |
| let mut dead_keys: Vec<String> = Vec::new(); |
|
|
| for participant in &self.participants { |
| |
| if participant.key == msg.from { |
| continue; |
| } |
| if let Some(ref sender) = participant.ws_sender { |
| if sender.send(json.clone()).is_ok() { |
| delivered += 1; |
| } else { |
| dead_keys.push(participant.key.clone()); |
| } |
| } |
| } |
|
|
| |
| for key in &dead_keys { |
| self.clear_ws_sender(key); |
| } |
|
|
| delivered |
| } |
|
|
| |
| pub fn participant_count(&self) -> usize { |
| self.participants.len() |
| } |
|
|
| |
| pub fn connected_count(&self) -> usize { |
| self.participants.iter().filter(|p| p.ws_sender.is_some()).count() |
| } |
|
|
| |
| pub fn message_count(&self) -> usize { |
| self.messages.len() |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| pub struct ChannelHub { |
| |
| channels: HashMap<String, Channel>, |
| |
| next_id: u64, |
| } |
|
|
| impl ChannelHub { |
| |
| pub fn new() -> Self { |
| Self { |
| channels: HashMap::new(), |
| next_id: 1, |
| } |
| } |
|
|
| |
| |
| pub fn create_channel( |
| &mut self, |
| name: &str, |
| created_by: &str, |
| created_by_name: &str, |
| ) -> String { |
| let id = format!("ch-{}", self.next_id); |
| self.next_id += 1; |
|
|
| let mut channel = Channel::new(id.clone(), name.to_string(), created_by.to_string()); |
| channel.add_participant(created_by, created_by_name); |
|
|
| |
| let sys_msg = ChannelMessage { |
| id: new_message_id(), |
| channel_id: id.clone(), |
| from: "system".to_string(), |
| from_name: "System".to_string(), |
| text: format!("Channel '{}' created by {}", name, created_by_name), |
| timestamp: chrono::Utc::now().to_rfc3339(), |
| msg_type: MessageType::System, |
| }; |
| channel.push_message(sys_msg); |
|
|
| self.channels.insert(id.clone(), channel); |
| id |
| } |
|
|
| |
| pub fn join_channel( |
| &mut self, |
| channel_id: &str, |
| key: &str, |
| name: &str, |
| ) -> Result<(), String> { |
| let channel = self.channels.get_mut(channel_id) |
| .ok_or_else(|| format!("Channel not found: {}", channel_id))?; |
|
|
| if channel.has_participant(key) { |
| return Ok(()); |
| } |
|
|
| channel.add_participant(key, name); |
|
|
| |
| let sys_msg = ChannelMessage { |
| id: new_message_id(), |
| channel_id: channel_id.to_string(), |
| from: "system".to_string(), |
| from_name: "System".to_string(), |
| text: format!("{} joined the channel", name), |
| timestamp: chrono::Utc::now().to_rfc3339(), |
| msg_type: MessageType::System, |
| }; |
| channel.broadcast(&sys_msg); |
| channel.push_message(sys_msg); |
|
|
| Ok(()) |
| } |
|
|
| |
| pub fn leave_channel( |
| &mut self, |
| channel_id: &str, |
| key: &str, |
| ) -> Result<(), String> { |
| let channel = self.channels.get_mut(channel_id) |
| .ok_or_else(|| format!("Channel not found: {}", channel_id))?; |
|
|
| let name = channel.participants.iter() |
| .find(|p| p.key == key) |
| .map(|p| p.name.clone()) |
| .unwrap_or_else(|| key[..8.min(key.len())].to_string()); |
|
|
| if !channel.remove_participant(key) { |
| return Err(format!("Not a participant in channel {}", channel_id)); |
| } |
|
|
| |
| let sys_msg = ChannelMessage { |
| id: new_message_id(), |
| channel_id: channel_id.to_string(), |
| from: "system".to_string(), |
| from_name: "System".to_string(), |
| text: format!("{} left the channel", name), |
| timestamp: chrono::Utc::now().to_rfc3339(), |
| msg_type: MessageType::System, |
| }; |
| channel.broadcast(&sys_msg); |
| channel.push_message(sys_msg); |
|
|
| Ok(()) |
| } |
|
|
| |
| |
| pub fn send_message( |
| &mut self, |
| channel_id: &str, |
| from: &str, |
| from_name: &str, |
| text: &str, |
| msg_type: MessageType, |
| ) -> Result<ChannelMessage, String> { |
| let channel = self.channels.get_mut(channel_id) |
| .ok_or_else(|| format!("Channel not found: {}", channel_id))?; |
|
|
| if !channel.has_participant(from) { |
| return Err(format!("Not a participant in channel {}", channel_id)); |
| } |
|
|
| let msg = ChannelMessage { |
| id: new_message_id(), |
| channel_id: channel_id.to_string(), |
| from: from.to_string(), |
| from_name: from_name.to_string(), |
| text: text.to_string(), |
| timestamp: chrono::Utc::now().to_rfc3339(), |
| msg_type, |
| }; |
|
|
| let delivered = channel.broadcast(&msg); |
| channel.push_message(msg.clone()); |
|
|
| eprintln!("[SPF-CHANNEL] {} → #{}: '{}' (delivered to {})", |
| from_name, channel_id, |
| text.chars().take(50).collect::<String>(), |
| delivered); |
|
|
| Ok(msg) |
| } |
|
|
| |
| pub fn get_history( |
| &self, |
| channel_id: &str, |
| limit: usize, |
| ) -> Result<Vec<&ChannelMessage>, String> { |
| let channel = self.channels.get(channel_id) |
| .ok_or_else(|| format!("Channel not found: {}", channel_id))?; |
| Ok(channel.get_history(limit)) |
| } |
|
|
| |
| pub fn get_channel_mut(&mut self, channel_id: &str) -> Option<&mut Channel> { |
| self.channels.get_mut(channel_id) |
| } |
|
|
| |
| pub fn get_channel(&self, channel_id: &str) -> Option<&Channel> { |
| self.channels.get(channel_id) |
| } |
|
|
| |
| pub fn has_channel(&self, channel_id: &str) -> bool { |
| self.channels.contains_key(channel_id) |
| } |
|
|
| |
| pub fn list_channels(&self) -> Vec<ChannelSummary> { |
| self.channels.values().map(|ch| ChannelSummary { |
| id: ch.id.clone(), |
| name: ch.name.clone(), |
| created_by: ch.created_by.clone(), |
| created_at: ch.created_at.clone(), |
| participants: ch.participants.iter().map(|p| ParticipantInfo { |
| key: p.key.clone(), |
| name: p.name.clone(), |
| connected: p.ws_sender.is_some(), |
| }).collect(), |
| participant_count: ch.participant_count(), |
| connected_count: ch.connected_count(), |
| message_count: ch.message_count(), |
| }).collect() |
| } |
|
|
| |
| pub fn channel_count(&self) -> usize { |
| self.channels.len() |
| } |
|
|
| |
| pub fn remove_channel(&mut self, channel_id: &str) -> bool { |
| self.channels.remove(channel_id).is_some() |
| } |
|
|
| |
| |
| |
| pub fn register_ws( |
| &mut self, |
| channel_id: &str, |
| key: &str, |
| name: &str, |
| sender: tokio::sync::mpsc::UnboundedSender<String>, |
| ) -> Result<(), String> { |
| let channel = self.channels.get_mut(channel_id) |
| .ok_or_else(|| format!("Channel not found: {}", channel_id))?; |
|
|
| |
| if !channel.has_participant(key) { |
| channel.add_participant(key, name); |
| let sys_msg = ChannelMessage { |
| id: new_message_id(), |
| channel_id: channel_id.to_string(), |
| from: "system".to_string(), |
| from_name: "System".to_string(), |
| text: format!("{} joined the channel", name), |
| timestamp: chrono::Utc::now().to_rfc3339(), |
| msg_type: MessageType::System, |
| }; |
| channel.broadcast(&sys_msg); |
| channel.push_message(sys_msg); |
| } |
|
|
| channel.set_ws_sender(key, sender); |
| eprintln!("[SPF-CHANNEL] WS registered: {} ({}) on #{}", |
| name, &key[..8.min(key.len())], channel_id); |
| Ok(()) |
| } |
|
|
| |
| |
| pub fn unregister_ws(&mut self, channel_id: &str, key: &str) { |
| if let Some(channel) = self.channels.get_mut(channel_id) { |
| channel.clear_ws_sender(key); |
| eprintln!("[SPF-CHANNEL] WS disconnected: {} on #{}", |
| &key[..8.min(key.len())], channel_id); |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Deserialize)] |
| struct WsInbound { |
| |
| action: String, |
| |
| #[serde(default)] |
| text: String, |
| |
| #[serde(default = "default_msg_type")] |
| msg_type: MessageType, |
| |
| #[serde(default = "default_history_limit")] |
| limit: usize, |
| } |
|
|
| fn default_msg_type() -> MessageType { MessageType::Text } |
| fn default_history_limit() -> usize { 50 } |
|
|
| |
| #[derive(Debug, Serialize)] |
| struct WsOutbound { |
| |
| #[serde(rename = "type")] |
| resp_type: String, |
| |
| data: serde_json::Value, |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| pub async fn handle_channel_ws( |
| mut socket: WebSocket, |
| channel_id: String, |
| peer_key: String, |
| peer_name: String, |
| ) { |
| |
| let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<String>(); |
|
|
| |
| |
| let register_err: Option<String> = { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
| match hub.register_ws(&channel_id, &peer_key, &peer_name, tx) { |
| Ok(()) => None, |
| Err(e) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(e), |
| }).unwrap_or_default()), |
| } |
| }; |
| if let Some(err_json) = register_err { |
| let _ = socket.send(Message::Text(err_json.into())).await; |
| return; |
| } |
|
|
| eprintln!("[SPF-CHANNEL] WS connected: {} ({}) on #{}", |
| peer_name, &peer_key[..8.min(peer_key.len())], channel_id); |
|
|
| |
| |
| let history_json: Option<String> = { |
| let guard = CHANNEL_HUB.lock().unwrap(); |
| if let Some(hub) = guard.as_ref() { |
| if let Ok(history) = hub.get_history(&channel_id, 50) { |
| let msgs: Vec<&ChannelMessage> = history; |
| let envelope = WsOutbound { |
| resp_type: "history".to_string(), |
| data: serde_json::to_value(&msgs).unwrap_or_default(), |
| }; |
| serde_json::to_string(&envelope).ok() |
| } else { None } |
| } else { None } |
| }; |
| if let Some(json) = history_json { |
| let _ = socket.send(Message::Text(json.into())).await; |
| } |
|
|
| |
| loop { |
| tokio::select! { |
| |
| msg = rx.recv() => { |
| match msg { |
| Some(text) => { |
| if socket.send(Message::Text(text.into())).await.is_err() { |
| break; |
| } |
| } |
| None => break, |
| } |
| } |
|
|
| |
| ws_msg = socket.recv() => { |
| match ws_msg { |
| Some(Ok(Message::Text(text))) => { |
| let response = process_ws_command( |
| &text, &channel_id, &peer_key, &peer_name |
| ); |
| if let Some(resp_json) = response { |
| if socket.send(Message::Text(resp_json.into())).await.is_err() { |
| break; |
| } |
| } |
| } |
| Some(Ok(Message::Ping(data))) => { |
| if socket.send(Message::Pong(data)).await.is_err() { |
| break; |
| } |
| } |
| Some(Ok(Message::Close(_))) | Some(Err(_)) | None => break, |
| _ => {} |
| } |
| } |
| } |
| } |
|
|
| |
| { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| if let Some(hub) = guard.as_mut() { |
| hub.unregister_ws(&channel_id, &peer_key); |
| } |
| } |
|
|
| eprintln!("[SPF-CHANNEL] WS disconnected: {} ({}) from #{}", |
| peer_name, &peer_key[..8.min(peer_key.len())], channel_id); |
| } |
|
|
| |
| |
| fn process_ws_command( |
| text: &str, |
| channel_id: &str, |
| peer_key: &str, |
| peer_name: &str, |
| ) -> Option<String> { |
| let cmd: WsInbound = match serde_json::from_str(text) { |
| Ok(c) => c, |
| Err(e) => { |
| return Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(format!("Invalid JSON: {}", e)), |
| }).unwrap_or_default()); |
| } |
| }; |
|
|
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
|
|
| match cmd.action.as_str() { |
| "send" => { |
| match hub.send_message(channel_id, peer_key, peer_name, &cmd.text, cmd.msg_type) { |
| Ok(msg) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "ack".to_string(), |
| data: serde_json::to_value(&msg).unwrap_or_default(), |
| }).unwrap_or_default()), |
| Err(e) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(e), |
| }).unwrap_or_default()), |
| } |
| } |
|
|
| "history" => { |
| match hub.get_history(channel_id, cmd.limit) { |
| Ok(msgs) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "history".to_string(), |
| data: serde_json::to_value(&msgs).unwrap_or_default(), |
| }).unwrap_or_default()), |
| Err(e) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(e), |
| }).unwrap_or_default()), |
| } |
| } |
|
|
| "join" => { |
| |
| match hub.join_channel(channel_id, peer_key, peer_name) { |
| Ok(()) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "system".to_string(), |
| data: serde_json::Value::String("Joined".to_string()), |
| }).unwrap_or_default()), |
| Err(e) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(e), |
| }).unwrap_or_default()), |
| } |
| } |
|
|
| "leave" => { |
| match hub.leave_channel(channel_id, peer_key) { |
| Ok(()) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "system".to_string(), |
| data: serde_json::Value::String("Left channel".to_string()), |
| }).unwrap_or_default()), |
| Err(e) => Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(e), |
| }).unwrap_or_default()), |
| } |
| } |
|
|
| other => { |
| Some(serde_json::to_string(&WsOutbound { |
| resp_type: "error".to_string(), |
| data: serde_json::Value::String(format!("Unknown action: {}", other)), |
| }).unwrap_or_default()) |
| } |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| pub fn api_create_channel(name: &str, key: &str, display_name: &str) -> serde_json::Value { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
| let id = hub.create_channel(name, key, display_name); |
| serde_json::json!({ |
| "ok": true, |
| "channel_id": id, |
| "name": name, |
| "created_by": display_name |
| }) |
| } |
|
|
| |
| |
| pub fn api_join_channel(channel_id: &str, key: &str, name: &str) -> serde_json::Value { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
| match hub.join_channel(channel_id, key, name) { |
| Ok(()) => serde_json::json!({ "ok": true, "channel_id": channel_id }), |
| Err(e) => serde_json::json!({ "ok": false, "error": e }), |
| } |
| } |
|
|
| |
| |
| pub fn api_leave_channel(channel_id: &str, key: &str) -> serde_json::Value { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
| match hub.leave_channel(channel_id, key) { |
| Ok(()) => serde_json::json!({ "ok": true, "channel_id": channel_id }), |
| Err(e) => serde_json::json!({ "ok": false, "error": e }), |
| } |
| } |
|
|
| |
| |
| pub fn api_send_message( |
| channel_id: &str, |
| key: &str, |
| name: &str, |
| text: &str, |
| msg_type: MessageType, |
| ) -> serde_json::Value { |
| let mut guard = CHANNEL_HUB.lock().unwrap(); |
| let hub = guard.get_or_insert_with(ChannelHub::new); |
| match hub.send_message(channel_id, key, name, text, msg_type) { |
| Ok(msg) => serde_json::json!({ |
| "ok": true, |
| "message": msg |
| }), |
| Err(e) => serde_json::json!({ "ok": false, "error": e }), |
| } |
| } |
|
|
| |
| pub fn api_list_channels() -> serde_json::Value { |
| let guard = CHANNEL_HUB.lock().unwrap(); |
| match guard.as_ref() { |
| Some(hub) => serde_json::json!({ |
| "ok": true, |
| "channels": hub.list_channels(), |
| "count": hub.channel_count() |
| }), |
| None => serde_json::json!({ |
| "ok": true, |
| "channels": [], |
| "count": 0 |
| }), |
| } |
| } |
|
|
| |
| pub fn api_channel_history(channel_id: &str, limit: usize) -> serde_json::Value { |
| let guard = CHANNEL_HUB.lock().unwrap(); |
| match guard.as_ref() { |
| Some(hub) => match hub.get_history(channel_id, limit) { |
| Ok(msgs) => serde_json::json!({ |
| "ok": true, |
| "channel_id": channel_id, |
| "messages": msgs, |
| "count": msgs.len() |
| }), |
| Err(e) => serde_json::json!({ "ok": false, "error": e }), |
| }, |
| None => serde_json::json!({ "ok": false, "error": "No channels exist" }), |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct InboundMessage { |
| |
| #[serde(rename = "type")] |
| pub msg_type: String, |
| |
| pub data: serde_json::Value, |
| } |
|
|
| |
| |
| |
| |
| |
| pub struct WsClientConnection { |
| |
| pub channel_id: String, |
| |
| pub hub_url: String, |
| |
| pub outbound_tx: tokio::sync::mpsc::UnboundedSender<String>, |
| |
| pub inbound: std::sync::Arc<std::sync::Mutex<VecDeque<InboundMessage>>>, |
| |
| pub task_handle: tokio::task::JoinHandle<()>, |
| |
| pub connected: std::sync::Arc<std::sync::atomic::AtomicBool>, |
| } |
|
|
| |
| |
| pub static WS_CLIENTS: Mutex<Option<HashMap<String, WsClientConnection>>> = Mutex::new(None); |
|
|
| |
| fn client_key(hub_url: &str, channel_id: &str) -> String { |
| format!("{}#{}", hub_url, channel_id) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| pub fn ws_client_connect( |
| handle: &tokio::runtime::Handle, |
| hub_url: &str, |
| channel_id: &str, |
| api_key: &str, |
| peer_key: &str, |
| peer_name: &str, |
| ) -> Result<String, String> { |
| let key = client_key(hub_url, channel_id); |
|
|
| |
| { |
| let guard = WS_CLIENTS.lock().unwrap(); |
| if let Some(clients) = guard.as_ref() { |
| if let Some(conn) = clients.get(&key) { |
| if conn.connected.load(std::sync::atomic::Ordering::Relaxed) { |
| return Ok(key); |
| } |
| } |
| } |
| } |
|
|
| |
| let ws_url = format!( |
| "{}/ws/channel/{}?key={}&name={}", |
| hub_url.replace("http://", "ws://").replace("https://", "wss://"), |
| channel_id, |
| peer_key, |
| urlencoding(peer_name), |
| ); |
|
|
| let (outbound_tx, mut outbound_rx) = tokio::sync::mpsc::unbounded_channel::<String>(); |
| let inbound_buf: std::sync::Arc<std::sync::Mutex<VecDeque<InboundMessage>>> |
| = std::sync::Arc::new(std::sync::Mutex::new(VecDeque::new())); |
| let connected = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); |
|
|
| let inbound_clone = inbound_buf.clone(); |
| let connected_clone = connected.clone(); |
| let api_key_owned = api_key.to_string(); |
| let ws_url_owned = ws_url.clone(); |
| let key_clone = key.clone(); |
| let hub_url_owned = hub_url.to_string(); |
| let channel_id_owned = channel_id.to_string(); |
|
|
| const MAX_INBOUND_BUFFER: usize = 500; |
|
|
| |
| let task_handle = handle.spawn(async move { |
| |
| let request = match http::Request::builder() |
| .uri(&ws_url_owned) |
| .header("x-spf-key", &api_key_owned) |
| .header("sec-websocket-key", tokio_tungstenite::tungstenite::handshake::client::generate_key()) |
| .header("sec-websocket-version", "13") |
| .header("connection", "Upgrade") |
| .header("upgrade", "websocket") |
| .header("host", extract_host(&hub_url_owned)) |
| .body(()) |
| { |
| Ok(r) => r, |
| Err(e) => { |
| eprintln!("[SPF-CHANNEL-CLIENT] Request build error: {}", e); |
| return; |
| } |
| }; |
|
|
| let ws_stream = match tokio_tungstenite::connect_async(request).await { |
| Ok((stream, _)) => stream, |
| Err(e) => { |
| eprintln!("[SPF-CHANNEL-CLIENT] Connect failed to {}: {}", ws_url_owned, e); |
| return; |
| } |
| }; |
|
|
| connected_clone.store(true, std::sync::atomic::Ordering::Relaxed); |
| eprintln!("[SPF-CHANNEL-CLIENT] Connected to {} #{}", hub_url_owned, channel_id_owned); |
|
|
| let (mut ws_sink, mut ws_stream_rx) = ws_stream.split(); |
|
|
| loop { |
| tokio::select! { |
| |
| ws_msg = ws_stream_rx.next() => { |
| match ws_msg { |
| Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) => { |
| if let Ok(msg) = serde_json::from_str::<InboundMessage>(&text) { |
| let mut buf = inbound_clone.lock().unwrap(); |
| if buf.len() >= MAX_INBOUND_BUFFER { |
| buf.pop_front(); |
| } |
| buf.push_back(msg); |
| } |
| } |
| Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) => break, |
| Some(Err(e)) => { |
| eprintln!("[SPF-CHANNEL-CLIENT] WS error: {}", e); |
| break; |
| } |
| None => break, |
| _ => {} |
| } |
| } |
|
|
| |
| out_msg = outbound_rx.recv() => { |
| match out_msg { |
| Some(text) => { |
| if ws_sink.send(tokio_tungstenite::tungstenite::Message::Text(text.into())).await.is_err() { |
| break; |
| } |
| } |
| None => break, |
| } |
| } |
| } |
| } |
|
|
| connected_clone.store(false, std::sync::atomic::Ordering::Relaxed); |
| eprintln!("[SPF-CHANNEL-CLIENT] Disconnected from {} #{}", hub_url_owned, channel_id_owned); |
|
|
| |
| let mut guard = WS_CLIENTS.lock().unwrap(); |
| if let Some(clients) = guard.as_mut() { |
| clients.remove(&key_clone); |
| } |
| }); |
|
|
| |
| let conn = WsClientConnection { |
| channel_id: channel_id.to_string(), |
| hub_url: hub_url.to_string(), |
| outbound_tx, |
| inbound: inbound_buf, |
| task_handle, |
| connected, |
| }; |
|
|
| let mut guard = WS_CLIENTS.lock().unwrap(); |
| let clients = guard.get_or_insert_with(HashMap::new); |
| clients.insert(key.clone(), conn); |
|
|
| Ok(key) |
| } |
|
|
| |
| pub fn ws_client_send( |
| client_key: &str, |
| text: &str, |
| msg_type: &str, |
| ) -> Result<(), String> { |
| let guard = WS_CLIENTS.lock().unwrap(); |
| let clients = guard.as_ref().ok_or("No client connections")?; |
| let conn = clients.get(client_key).ok_or("Not connected")?; |
|
|
| if !conn.connected.load(std::sync::atomic::Ordering::Relaxed) { |
| return Err("Connection lost".to_string()); |
| } |
|
|
| let cmd = serde_json::json!({ |
| "action": "send", |
| "text": text, |
| "msg_type": msg_type, |
| }); |
| conn.outbound_tx.send(cmd.to_string()) |
| .map_err(|e| format!("Send failed: {}", e)) |
| } |
|
|
| |
| |
| pub fn ws_client_drain(client_key: &str) -> Result<Vec<InboundMessage>, String> { |
| let guard = WS_CLIENTS.lock().unwrap(); |
| let clients = guard.as_ref().ok_or("No client connections")?; |
| let conn = clients.get(client_key).ok_or("Not connected")?; |
|
|
| let mut buf = conn.inbound.lock().unwrap(); |
| let messages: Vec<InboundMessage> = buf.drain(..).collect(); |
| Ok(messages) |
| } |
|
|
| |
| pub fn ws_client_disconnect(client_key: &str) -> Result<(), String> { |
| let mut guard = WS_CLIENTS.lock().unwrap(); |
| let clients = guard.as_mut().ok_or("No client connections")?; |
|
|
| if let Some(conn) = clients.remove(client_key) { |
| conn.task_handle.abort(); |
| Ok(()) |
| } else { |
| Err("Not connected".to_string()) |
| } |
| } |
|
|
| |
| pub fn ws_client_list() -> Vec<serde_json::Value> { |
| let guard = WS_CLIENTS.lock().unwrap(); |
| match guard.as_ref() { |
| Some(clients) => clients.iter().map(|(key, conn)| { |
| serde_json::json!({ |
| "key": key, |
| "channel_id": conn.channel_id, |
| "hub_url": conn.hub_url, |
| "connected": conn.connected.load(std::sync::atomic::Ordering::Relaxed), |
| "buffered": conn.inbound.lock().unwrap().len(), |
| }) |
| }).collect(), |
| None => Vec::new(), |
| } |
| } |
|
|
| |
| fn urlencoding(s: &str) -> String { |
| s.chars().map(|c| match c { |
| 'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => c.to_string(), |
| ' ' => "%20".to_string(), |
| _ => format!("%{:02X}", c as u32), |
| }).collect() |
| } |
|
|
| |
| fn extract_host(url: &str) -> String { |
| url.trim_start_matches("http://") |
| .trim_start_matches("https://") |
| .split('/') |
| .next() |
| .unwrap_or("localhost") |
| .to_string() |
| } |
|
|
| |
| |
| |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct ChannelSummary { |
| pub id: String, |
| pub name: String, |
| pub created_by: String, |
| pub created_at: String, |
| pub participants: Vec<ParticipantInfo>, |
| pub participant_count: usize, |
| pub connected_count: usize, |
| pub message_count: usize, |
| } |
|
|
| |
| #[derive(Debug, Clone, Serialize, Deserialize)] |
| pub struct ParticipantInfo { |
| pub key: String, |
| pub name: String, |
| pub connected: bool, |
| } |
|
|
| |
| |
| |
|
|
| #[cfg(test)] |
| mod tests { |
| use super::*; |
|
|
| #[test] |
| fn test_message_id_unique() { |
| let id1 = new_message_id(); |
| let id2 = new_message_id(); |
| assert_ne!(id1, id2); |
| assert!(id1.starts_with("msg-")); |
| } |
|
|
| #[test] |
| fn test_create_channel() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
| assert_eq!(id, "ch-1"); |
| assert!(hub.has_channel("ch-1")); |
| assert_eq!(hub.channel_count(), 1); |
|
|
| let ch = hub.get_channel("ch-1").unwrap(); |
| assert_eq!(ch.name, "ops"); |
| assert_eq!(ch.created_by, "key_aaa"); |
| assert_eq!(ch.participant_count(), 1); |
| assert!(ch.has_participant("key_aaa")); |
| assert_eq!(ch.message_count(), 1); |
| } |
|
|
| #[test] |
| fn test_join_leave() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
|
|
| hub.join_channel(&id, "key_bbb", "BRAVO").unwrap(); |
| let ch = hub.get_channel(&id).unwrap(); |
| assert_eq!(ch.participant_count(), 2); |
| assert!(ch.has_participant("key_bbb")); |
|
|
| |
| hub.join_channel(&id, "key_bbb", "BRAVO").unwrap(); |
| assert_eq!(hub.get_channel(&id).unwrap().participant_count(), 2); |
|
|
| hub.leave_channel(&id, "key_bbb").unwrap(); |
| assert_eq!(hub.get_channel(&id).unwrap().participant_count(), 1); |
| assert!(!hub.get_channel(&id).unwrap().has_participant("key_bbb")); |
| } |
|
|
| #[test] |
| fn test_join_nonexistent() { |
| let mut hub = ChannelHub::new(); |
| let result = hub.join_channel("ch-999", "key_aaa", "ALPHA"); |
| assert!(result.is_err()); |
| } |
|
|
| #[test] |
| fn test_send_message() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
| hub.join_channel(&id, "key_bbb", "BRAVO").unwrap(); |
|
|
| let msg = hub.send_message(&id, "key_aaa", "ALPHA", "hello team", MessageType::Text).unwrap(); |
| assert_eq!(msg.channel_id, id); |
| assert_eq!(msg.from, "key_aaa"); |
| assert_eq!(msg.text, "hello team"); |
| assert_eq!(msg.msg_type, MessageType::Text); |
|
|
| |
| assert_eq!(hub.get_channel(&id).unwrap().message_count(), 3); |
| } |
|
|
| #[test] |
| fn test_send_not_participant() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
| let result = hub.send_message(&id, "key_zzz", "STRANGER", "hi", MessageType::Text); |
| assert!(result.is_err()); |
| } |
|
|
| #[test] |
| fn test_history_limit() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
|
|
| for i in 0..10 { |
| hub.send_message(&id, "key_aaa", "ALPHA", &format!("msg {}", i), MessageType::Text).unwrap(); |
| } |
|
|
| let history = hub.get_history(&id, 3).unwrap(); |
| assert_eq!(history.len(), 3); |
| assert!(history[2].text.contains("msg 9")); |
| } |
|
|
| #[test] |
| fn test_eviction() { |
| let mut channel = Channel::new("test".to_string(), "Test".to_string(), "key".to_string()); |
| for i in 0..(MAX_CHANNEL_HISTORY + 10) { |
| channel.push_message(ChannelMessage { |
| id: format!("msg-{}", i), |
| channel_id: "test".to_string(), |
| from: "key".to_string(), |
| from_name: "Test".to_string(), |
| text: format!("message {}", i), |
| timestamp: "2026-04-07T00:00:00Z".to_string(), |
| msg_type: MessageType::Text, |
| }); |
| } |
| assert_eq!(channel.message_count(), MAX_CHANNEL_HISTORY); |
| assert!(channel.messages.front().unwrap().text.contains("message 10")); |
| } |
|
|
| #[test] |
| fn test_list_channels() { |
| let mut hub = ChannelHub::new(); |
| hub.create_channel("ops", "key_aaa", "ALPHA"); |
| hub.create_channel("research", "key_bbb", "BRAVO"); |
|
|
| let list = hub.list_channels(); |
| assert_eq!(list.len(), 2); |
| let names: Vec<&str> = list.iter().map(|s| s.name.as_str()).collect(); |
| assert!(names.contains(&"ops")); |
| assert!(names.contains(&"research")); |
| } |
|
|
| #[test] |
| fn test_remove_channel() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("temp", "key_aaa", "ALPHA"); |
| assert!(hub.remove_channel(&id)); |
| assert!(!hub.has_channel(&id)); |
| assert!(!hub.remove_channel(&id)); |
| } |
|
|
| #[test] |
| fn test_ids_increment() { |
| let mut hub = ChannelHub::new(); |
| assert_eq!(hub.create_channel("a", "k", "n"), "ch-1"); |
| assert_eq!(hub.create_channel("b", "k", "n"), "ch-2"); |
| assert_eq!(hub.create_channel("c", "k", "n"), "ch-3"); |
| } |
|
|
| #[test] |
| fn test_register_ws_auto_joins() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
|
|
| let (tx, _rx) = tokio::sync::mpsc::unbounded_channel(); |
| hub.register_ws(&id, "key_bbb", "BRAVO", tx).unwrap(); |
|
|
| let ch = hub.get_channel(&id).unwrap(); |
| assert_eq!(ch.participant_count(), 2); |
| assert!(ch.has_participant("key_bbb")); |
| assert_eq!(ch.connected_count(), 1); |
| } |
|
|
| #[test] |
| fn test_unregister_ws_keeps_participant() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
|
|
| let (tx, _rx) = tokio::sync::mpsc::unbounded_channel(); |
| hub.register_ws(&id, "key_aaa", "ALPHA", tx).unwrap(); |
| assert_eq!(hub.get_channel(&id).unwrap().connected_count(), 1); |
|
|
| hub.unregister_ws(&id, "key_aaa"); |
| let ch = hub.get_channel(&id).unwrap(); |
| assert_eq!(ch.connected_count(), 0); |
| assert!(ch.has_participant("key_aaa")); |
| } |
|
|
| #[test] |
| fn test_broadcast_skips_sender() { |
| let mut hub = ChannelHub::new(); |
| let id = hub.create_channel("ops", "key_aaa", "ALPHA"); |
|
|
| let (tx_a, mut rx_a) = tokio::sync::mpsc::unbounded_channel(); |
| let (tx_b, mut rx_b) = tokio::sync::mpsc::unbounded_channel(); |
|
|
| hub.register_ws(&id, "key_aaa", "ALPHA", tx_a).unwrap(); |
| hub.register_ws(&id, "key_bbb", "BRAVO", tx_b).unwrap(); |
|
|
| |
| hub.send_message(&id, "key_aaa", "ALPHA", "test", MessageType::Text).unwrap(); |
|
|
| |
| assert!(rx_b.try_recv().is_ok()); |
| |
| assert!(rx_a.try_recv().is_err()); |
| } |
| } |
|
|