1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use futures::{SinkExt, StreamExt};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::{Mutex, mpsc};
use tokio_tungstenite::accept_async;
use super::{GatewayMessage, GatewayResponse, GatewayTransport};
// ─── WebSocket API Server ───────────────────────────────────────────────────────
pub struct WebSocketApi {
bind_addr: String,
clients: Arc<Mutex<HashMap<String, mpsc::UnboundedSender<String>>>>,
}
impl WebSocketApi {
pub fn new(bind_addr: impl Into<String>) -> Self {
Self {
bind_addr: bind_addr.into(),
clients: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[async_trait::async_trait]
impl GatewayTransport for WebSocketApi {
fn name(&self) -> &str {
"ws-api"
}
async fn start(&self, tx: mpsc::UnboundedSender<GatewayMessage>) -> anyhow::Result<()> {
let listener = TcpListener::bind(&self.bind_addr).await?;
let clients = self.clients.clone();
tracing::info!("WebSocket API listening on {}", self.bind_addr);
tokio::spawn(async move {
loop {
match listener.accept().await {
Ok((stream, addr)) => {
tracing::debug!("WS connection from {}", addr);
let tx = tx.clone();
let clients = clients.clone();
tokio::spawn(async move {
match accept_async(stream).await {
Ok(ws_stream) => {
let (mut write, mut read) = ws_stream.split();
let chat_id = addr.to_string();
let (out_tx, mut out_rx) = mpsc::unbounded_channel::<String>();
clients.lock().await.insert(chat_id.clone(), out_tx);
loop {
tokio::select! {
Some(outbound) = out_rx.recv() => {
if write
.send(tokio_tungstenite::tungstenite::Message::Text(outbound.into()))
.await
.is_err()
{
break;
}
}
incoming = read.next() => {
match incoming {
Some(Ok(msg)) => {
if let tokio_tungstenite::tungstenite::Message::Text(text) = msg {
let _ = tx.send(GatewayMessage {
surface: "ws-api".into(),
user_id: "ws-user".into(),
chat_id: chat_id.clone(),
text: text.to_string(),
message_id: None,
});
let ack = serde_json::json!({"ack": "received"}).to_string();
let _ = write
.send(tokio_tungstenite::tungstenite::Message::Text(ack.into()))
.await;
}
}
Some(Err(e)) => {
tracing::error!("WS error: {}", e);
break;
}
None => break,
}
}
}
}
clients.lock().await.remove(&chat_id);
}
Err(e) => {
tracing::error!("WS handshake error: {}", e);
}
}
});
}
Err(e) => {
tracing::error!("Accept error: {}", e);
}
}
}
});
Ok(())
}
async fn send(&self, response: GatewayResponse) -> anyhow::Result<()> {
let payload = serde_json::json!({
"type": "message",
"text": response.text,
"reply_to": response.reply_to,
"buttons": response.buttons,
})
.to_string();
if let Some(client) = self.clients.lock().await.get(&response.chat_id).cloned() {
client
.send(payload)
.map_err(|_| anyhow::anyhow!("WebSocket client is no longer connected"))?;
Ok(())
} else {
anyhow::bail!("WebSocket client not connected: {}", response.chat_id)
}
}
async fn stop(&self) -> anyhow::Result<()> {
tracing::info!("WebSocket API stopped");
Ok(())
}
}