Skip to main content

wabot_addon_chat_controller_socket/
lib.rs

1//! Socket.IO chat channel — port of wabot-ts
2//! `addon/chat-controller/socket/SocketChannel.ts`. Built on
3//! [`socketioxide`].
4//!
5//! Runs its own axum server on a configurable bind address (sharing
6//! with the REST router is a future enhancement — would let one
7//! process expose REST + WebSocket on the same port). Listens on the
8//! configured namespace for `"message"` events whose payload matches
9//! [`SocketIncoming`]; each message becomes a `ChannelMessage` and is
10//! forwarded to the chat-controller framework. Replies emit `"message"`
11//! back to the originating socket.
12//!
13//! ## Configuration
14//!
15//! Register a [`SocketChannelConfig`] singleton before
16//! `register_singletons!(&c, SocketChannel)`:
17//!
18//! ```ignore
19//! c.register_instance::<SocketChannelConfig>(Arc::new(
20//!     SocketChannelConfig::new("/chat", "0.0.0.0:3001"),
21//! ));
22//! register_singletons!(&c, SocketChannel);
23//! ```
24
25use std::collections::HashMap;
26use std::net::SocketAddr;
27use std::sync::Arc;
28
29use async_trait::async_trait;
30use parking_lot::Mutex;
31use serde::{Deserialize, Serialize};
32use socketioxide::extract::{Data, SocketRef};
33use socketioxide::SocketIo;
34use tower_http::cors::CorsLayer;
35
36use wabot_feature_chat_controller::{
37    ChannelError, ChannelMessage, ChatChannel, ChatConnection, ChatMessage, ChatMessageFile,
38    ChatType, MessageCallback, ReplyResult,
39};
40
41pub const SOCKET_CHANNEL_NAME: &str = "SocketChannel";
42
43/// Bind address + namespace + CORS for the socket.io server.
44#[derive(Debug, Clone)]
45pub struct SocketChannelConfig {
46    /// e.g. `"/chat"` — `socketioxide` namespaces are path-like.
47    pub namespace: String,
48    /// e.g. `"0.0.0.0:3001"`.
49    pub bind_addr: SocketAddr,
50    /// `Some("*")` for permissive, `None` for default (no CORS layer).
51    pub cors_origin: Option<String>,
52}
53
54impl SocketChannelConfig {
55    pub fn new(namespace: impl Into<String>, bind_addr: &str) -> Self {
56        Self {
57            namespace: namespace.into(),
58            bind_addr: bind_addr.parse().expect("invalid bind_addr"),
59            cors_origin: None,
60        }
61    }
62
63    pub fn from_env(namespace: &str, port_var: &str, default_port: u16) -> Self {
64        let port: u16 = std::env::var(port_var)
65            .ok()
66            .and_then(|s| s.parse().ok())
67            .unwrap_or(default_port);
68        let cors = std::env::var("SOCKET_CORS_ORIGIN").ok();
69        Self {
70            namespace: namespace.into(),
71            bind_addr: format!("0.0.0.0:{port}").parse().unwrap(),
72            cors_origin: cors,
73        }
74    }
75
76    pub fn with_cors_origin(mut self, origin: impl Into<String>) -> Self {
77        self.cors_origin = Some(origin.into());
78        self
79    }
80}
81
82/// Inbound message shape — matches `SocketChannelReceivedMessage` from
83/// the TS addon. All except `chat_id` is optional.
84#[derive(Debug, Deserialize)]
85#[serde(rename_all = "camelCase")]
86pub struct SocketIncoming {
87    pub chat_id: String,
88    #[serde(default)]
89    pub sender_name: Option<String>,
90    #[serde(default)]
91    pub text: Option<String>,
92    #[serde(default)]
93    pub metadata: HashMap<String, String>,
94    #[serde(default)]
95    pub images: Vec<SocketFile>,
96    #[serde(default)]
97    pub documents: Vec<SocketFile>,
98}
99
100/// File attachment payload over socket.io.
101#[derive(Debug, Clone, Deserialize, Serialize)]
102#[serde(rename_all = "camelCase")]
103pub struct SocketFile {
104    pub id: String,
105    pub mime_type: String,
106    #[serde(default)]
107    pub name: Option<String>,
108    #[serde(default)]
109    pub public_url: Option<String>,
110    #[serde(default)]
111    pub base64_url: Option<String>,
112}
113
114impl SocketFile {
115    fn into_chat_file(self) -> Option<ChatMessageFile> {
116        // Match TS: must have one of public_url or base64_url.
117        if self.public_url.is_some() || self.base64_url.is_some() {
118            Some(ChatMessageFile {
119                id: self.id,
120                mime_type: self.mime_type,
121                name: self.name,
122                public_url: self.public_url,
123                base64_url: self.base64_url,
124            })
125        } else {
126            None
127        }
128    }
129}
130
131/// Socket.IO chat channel. Cheap to clone (`Arc`-internal); construct
132/// once per process and register as a singleton.
133pub struct SocketChannel {
134    inner: Arc<Inner>,
135}
136
137struct Inner {
138    config: SocketChannelConfig,
139    callback: Mutex<Option<MessageCallback>>,
140    /// Sender that, when fired, makes axum stop accepting new requests
141    /// and finish in-flight ones gracefully.
142    shutdown: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
143}
144
145impl SocketChannel {
146    pub fn new(config: SocketChannelConfig) -> Self {
147        Self {
148            inner: Arc::new(Inner {
149                config,
150                callback: Mutex::new(None),
151                shutdown: Mutex::new(None),
152            }),
153        }
154    }
155}
156
157#[async_trait]
158impl ChatChannel for SocketChannel {
159    fn listen(&self, callback: MessageCallback) {
160        *self.inner.callback.lock() = Some(callback);
161    }
162
163    async fn connect(&self) -> Result<(), ChannelError> {
164        let inner = self.inner.clone();
165        let (layer, io) = SocketIo::new_layer();
166
167        let ns = inner.config.namespace.clone();
168
169        // Register the namespace handler. Per-socket handler hooks the
170        // "message" event and forwards each one through the chat
171        // controller pipeline. Inner is shared via Arc clone so each
172        // handler can re-read the latest `listen` callback.
173        let inner_for_ns = inner.clone();
174        // socketioxide expects an owned `Cow<'static, str>` for the
175        // namespace path; pass the String by value rather than a borrow.
176        io.ns(ns, move |socket: SocketRef| {
177            let inner_for_socket = inner_for_ns.clone();
178            async move {
179                socket.on(
180                    "message",
181                    move |socket: SocketRef, Data::<serde_json::Value>(payload)| {
182                        let inner_for_msg = inner_for_socket.clone();
183                        async move {
184                            handle_socket_message(inner_for_msg, socket, payload).await;
185                        }
186                    },
187                );
188            }
189        });
190
191        let mut app = axum::Router::new().layer(layer);
192        if let Some(origin) = inner.config.cors_origin.clone() {
193            let cors = if origin == "*" {
194                CorsLayer::permissive()
195            } else {
196                CorsLayer::new()
197                    .allow_origin(
198                        origin
199                            .parse::<axum::http::HeaderValue>()
200                            .map_err(|e| ChannelError::SendFailed(e.to_string()))?,
201                    )
202                    .allow_methods(tower_http::cors::Any)
203                    .allow_headers(tower_http::cors::Any)
204            };
205            app = app.layer(cors);
206        }
207
208        let listener = tokio::net::TcpListener::bind(&inner.config.bind_addr)
209            .await
210            .map_err(|e| ChannelError::SendFailed(e.to_string()))?;
211        tracing::info!(
212            "SocketChannel listening on {} (namespace `{}`)",
213            inner.config.bind_addr,
214            inner.config.namespace
215        );
216
217        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
218        *inner.shutdown.lock() = Some(tx);
219
220        axum::serve(listener, app)
221            .with_graceful_shutdown(async move {
222                let _ = rx.await;
223            })
224            .await
225            .map_err(|e| ChannelError::SendFailed(e.to_string()))?;
226        Ok(())
227    }
228
229    async fn disconnect(&self) -> Result<(), ChannelError> {
230        *self.inner.callback.lock() = None;
231        if let Some(tx) = self.inner.shutdown.lock().take() {
232            let _ = tx.send(());
233        }
234        Ok(())
235    }
236}
237
238async fn handle_socket_message(inner: Arc<Inner>, socket: SocketRef, payload: serde_json::Value) {
239    let cb = { inner.callback.lock().clone() };
240    let Some(cb) = cb else { return };
241
242    let parsed: SocketIncoming = match serde_json::from_value(payload) {
243        Ok(v) => v,
244        Err(e) => {
245            tracing::warn!(error = %e, "socket message payload invalid");
246            let _ = socket.emit(
247                "message",
248                &serde_json::json!({"error": format!("invalid message: {e}")}),
249            );
250            return;
251        }
252    };
253
254    if parsed.chat_id.trim().is_empty() {
255        tracing::warn!("socket message missing chatId");
256        return;
257    }
258
259    let images: Vec<ChatMessageFile> = parsed
260        .images
261        .into_iter()
262        .filter_map(SocketFile::into_chat_file)
263        .collect();
264    let documents: Vec<ChatMessageFile> = parsed
265        .documents
266        .into_iter()
267        .filter_map(SocketFile::into_chat_file)
268        .collect();
269
270    let chat_connection = ChatConnection {
271        id: parsed.chat_id,
272        chat_type: ChatType::Private,
273        channel_name: SOCKET_CHANNEL_NAME.into(),
274    };
275
276    let metadata = parsed.metadata;
277    let channel_msg = ChannelMessage {
278        channel_name: SOCKET_CHANNEL_NAME,
279        chat_connection,
280        message: ChatMessage {
281            object: None,
282            audios: None,
283            sender_id: None,
284            sender_name: parsed.sender_name,
285            text: parsed.text,
286            images: if images.is_empty() {
287                None
288            } else {
289                Some(images)
290            },
291            documents: if documents.is_empty() {
292                None
293            } else {
294                Some(documents)
295            },
296            metadata,
297        },
298        reply: build_reply(socket),
299        inject_instances: Vec::new(),
300    };
301
302    cb(channel_msg).await;
303}
304
305fn build_reply(socket: SocketRef) -> wabot_feature_chat_controller::ReplyFn {
306    Box::new(move |reply: ChatMessage| {
307        let socket = socket.clone();
308        Box::pin(async move {
309            let payload = serde_json::json!({
310                "senderId": reply.sender_id,
311                "senderName": reply.sender_name,
312                "text": reply.text,
313                "metadata": reply.metadata,
314                "images": reply.images,
315                "documents": reply.documents,
316            });
317            socket
318                .emit("message", &payload)
319                .map_err(|e| ChannelError::SendFailed(format!("{e:?}")))?;
320            Ok::<(), ChannelError>(())
321        }) as std::pin::Pin<Box<dyn std::future::Future<Output = ReplyResult> + Send>>
322    })
323}
324
325/// DI helper — pair with `register_singletons!(&c, SocketChannel)`.
326///
327/// Requires `Arc<SocketChannelConfig>` to be registered first.
328impl wabot_core::injection::IsSingleton for SocketChannel {
329    fn register_in(c: &wabot_core::injection::Container) {
330        c.register_singleton_factory::<SocketChannel, _>(|c2| {
331            let cfg: Arc<SocketChannelConfig> = c2.resolve::<SocketChannelConfig>();
332            Arc::new(SocketChannel::new((*cfg).clone()))
333        });
334    }
335}