wabot-addon-chat-controller-socket 0.2.0

Socket.IO chat channel addon — port of wabot-ts addon/chat-controller/socket, built on socketioxide.
Documentation
//! Socket.IO chat channel — port of wabot-ts
//! `addon/chat-controller/socket/SocketChannel.ts`. Built on
//! [`socketioxide`].
//!
//! Runs its own axum server on a configurable bind address (sharing
//! with the REST router is a future enhancement — would let one
//! process expose REST + WebSocket on the same port). Listens on the
//! configured namespace for `"message"` events whose payload matches
//! [`SocketIncoming`]; each message becomes a `ChannelMessage` and is
//! forwarded to the chat-controller framework. Replies emit `"message"`
//! back to the originating socket.
//!
//! ## Configuration
//!
//! Register a [`SocketChannelConfig`] singleton before
//! `register_singletons!(&c, SocketChannel)`:
//!
//! ```ignore
//! c.register_instance::<SocketChannelConfig>(Arc::new(
//!     SocketChannelConfig::new("/chat", "0.0.0.0:3001"),
//! ));
//! register_singletons!(&c, SocketChannel);
//! ```

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;

use async_trait::async_trait;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use socketioxide::extract::{Data, SocketRef};
use socketioxide::SocketIo;
use tower_http::cors::CorsLayer;

use wabot_feature_chat_controller::{
    ChannelError, ChannelMessage, ChatChannel, ChatConnection, ChatMessage, ChatMessageFile,
    ChatType, MessageCallback, ReplyResult,
};

pub const SOCKET_CHANNEL_NAME: &str = "SocketChannel";

/// Bind address + namespace + CORS for the socket.io server.
#[derive(Debug, Clone)]
pub struct SocketChannelConfig {
    /// e.g. `"/chat"` — `socketioxide` namespaces are path-like.
    pub namespace: String,
    /// e.g. `"0.0.0.0:3001"`.
    pub bind_addr: SocketAddr,
    /// `Some("*")` for permissive, `None` for default (no CORS layer).
    pub cors_origin: Option<String>,
}

impl SocketChannelConfig {
    pub fn new(namespace: impl Into<String>, bind_addr: &str) -> Self {
        Self {
            namespace: namespace.into(),
            bind_addr: bind_addr.parse().expect("invalid bind_addr"),
            cors_origin: None,
        }
    }

    pub fn from_env(namespace: &str, port_var: &str, default_port: u16) -> Self {
        let port: u16 = std::env::var(port_var)
            .ok()
            .and_then(|s| s.parse().ok())
            .unwrap_or(default_port);
        let cors = std::env::var("SOCKET_CORS_ORIGIN").ok();
        Self {
            namespace: namespace.into(),
            bind_addr: format!("0.0.0.0:{port}").parse().unwrap(),
            cors_origin: cors,
        }
    }

    pub fn with_cors_origin(mut self, origin: impl Into<String>) -> Self {
        self.cors_origin = Some(origin.into());
        self
    }
}

/// Inbound message shape — matches `SocketChannelReceivedMessage` from
/// the TS addon. All except `chat_id` is optional.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SocketIncoming {
    pub chat_id: String,
    #[serde(default)]
    pub sender_name: Option<String>,
    #[serde(default)]
    pub text: Option<String>,
    #[serde(default)]
    pub metadata: HashMap<String, String>,
    #[serde(default)]
    pub images: Vec<SocketFile>,
    #[serde(default)]
    pub documents: Vec<SocketFile>,
}

/// File attachment payload over socket.io.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SocketFile {
    pub id: String,
    pub mime_type: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub public_url: Option<String>,
    #[serde(default)]
    pub base64_url: Option<String>,
}

impl SocketFile {
    fn into_chat_file(self) -> Option<ChatMessageFile> {
        // Match TS: must have one of public_url or base64_url.
        if self.public_url.is_some() || self.base64_url.is_some() {
            Some(ChatMessageFile {
                id: self.id,
                mime_type: self.mime_type,
                name: self.name,
                public_url: self.public_url,
                base64_url: self.base64_url,
            })
        } else {
            None
        }
    }
}

/// Socket.IO chat channel. Cheap to clone (`Arc`-internal); construct
/// once per process and register as a singleton.
pub struct SocketChannel {
    inner: Arc<Inner>,
}

struct Inner {
    config: SocketChannelConfig,
    callback: Mutex<Option<MessageCallback>>,
    /// Sender that, when fired, makes axum stop accepting new requests
    /// and finish in-flight ones gracefully.
    shutdown: Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
}

impl SocketChannel {
    pub fn new(config: SocketChannelConfig) -> Self {
        Self {
            inner: Arc::new(Inner {
                config,
                callback: Mutex::new(None),
                shutdown: Mutex::new(None),
            }),
        }
    }
}

#[async_trait]
impl ChatChannel for SocketChannel {
    fn listen(&self, callback: MessageCallback) {
        *self.inner.callback.lock() = Some(callback);
    }

    async fn connect(&self) -> Result<(), ChannelError> {
        let inner = self.inner.clone();
        let (layer, io) = SocketIo::new_layer();

        let ns = inner.config.namespace.clone();

        // Register the namespace handler. Per-socket handler hooks the
        // "message" event and forwards each one through the chat
        // controller pipeline. Inner is shared via Arc clone so each
        // handler can re-read the latest `listen` callback.
        let inner_for_ns = inner.clone();
        // socketioxide expects an owned `Cow<'static, str>` for the
        // namespace path; pass the String by value rather than a borrow.
        io.ns(ns, move |socket: SocketRef| {
            let inner_for_socket = inner_for_ns.clone();
            async move {
                socket.on(
                    "message",
                    move |socket: SocketRef, Data::<serde_json::Value>(payload)| {
                        let inner_for_msg = inner_for_socket.clone();
                        async move {
                            handle_socket_message(inner_for_msg, socket, payload).await;
                        }
                    },
                );
            }
        });

        let mut app = axum::Router::new().layer(layer);
        if let Some(origin) = inner.config.cors_origin.clone() {
            let cors = if origin == "*" {
                CorsLayer::permissive()
            } else {
                CorsLayer::new()
                    .allow_origin(
                        origin
                            .parse::<axum::http::HeaderValue>()
                            .map_err(|e| ChannelError::SendFailed(e.to_string()))?,
                    )
                    .allow_methods(tower_http::cors::Any)
                    .allow_headers(tower_http::cors::Any)
            };
            app = app.layer(cors);
        }

        let listener = tokio::net::TcpListener::bind(&inner.config.bind_addr)
            .await
            .map_err(|e| ChannelError::SendFailed(e.to_string()))?;
        tracing::info!(
            "SocketChannel listening on {} (namespace `{}`)",
            inner.config.bind_addr,
            inner.config.namespace
        );

        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
        *inner.shutdown.lock() = Some(tx);

        axum::serve(listener, app)
            .with_graceful_shutdown(async move {
                let _ = rx.await;
            })
            .await
            .map_err(|e| ChannelError::SendFailed(e.to_string()))?;
        Ok(())
    }

    async fn disconnect(&self) -> Result<(), ChannelError> {
        *self.inner.callback.lock() = None;
        if let Some(tx) = self.inner.shutdown.lock().take() {
            let _ = tx.send(());
        }
        Ok(())
    }
}

async fn handle_socket_message(inner: Arc<Inner>, socket: SocketRef, payload: serde_json::Value) {
    let cb = { inner.callback.lock().clone() };
    let Some(cb) = cb else { return };

    let parsed: SocketIncoming = match serde_json::from_value(payload) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(error = %e, "socket message payload invalid");
            let _ = socket.emit(
                "message",
                &serde_json::json!({"error": format!("invalid message: {e}")}),
            );
            return;
        }
    };

    if parsed.chat_id.trim().is_empty() {
        tracing::warn!("socket message missing chatId");
        return;
    }

    let images: Vec<ChatMessageFile> = parsed
        .images
        .into_iter()
        .filter_map(SocketFile::into_chat_file)
        .collect();
    let documents: Vec<ChatMessageFile> = parsed
        .documents
        .into_iter()
        .filter_map(SocketFile::into_chat_file)
        .collect();

    let chat_connection = ChatConnection {
        id: parsed.chat_id,
        chat_type: ChatType::Private,
        channel_name: SOCKET_CHANNEL_NAME.into(),
    };

    let metadata = parsed.metadata;
    let channel_msg = ChannelMessage {
        channel_name: SOCKET_CHANNEL_NAME,
        chat_connection,
        message: ChatMessage {
            object: None,
            audios: None,
            sender_id: None,
            sender_name: parsed.sender_name,
            text: parsed.text,
            images: if images.is_empty() {
                None
            } else {
                Some(images)
            },
            documents: if documents.is_empty() {
                None
            } else {
                Some(documents)
            },
            metadata,
        },
        reply: build_reply(socket),
        inject_instances: Vec::new(),
    };

    cb(channel_msg).await;
}

fn build_reply(socket: SocketRef) -> wabot_feature_chat_controller::ReplyFn {
    Box::new(move |reply: ChatMessage| {
        let socket = socket.clone();
        Box::pin(async move {
            let payload = serde_json::json!({
                "senderId": reply.sender_id,
                "senderName": reply.sender_name,
                "text": reply.text,
                "metadata": reply.metadata,
                "images": reply.images,
                "documents": reply.documents,
            });
            socket
                .emit("message", &payload)
                .map_err(|e| ChannelError::SendFailed(format!("{e:?}")))?;
            Ok::<(), ChannelError>(())
        }) as std::pin::Pin<Box<dyn std::future::Future<Output = ReplyResult> + Send>>
    })
}

/// DI helper — pair with `register_singletons!(&c, SocketChannel)`.
///
/// Requires `Arc<SocketChannelConfig>` to be registered first.
impl wabot_core::injection::IsSingleton for SocketChannel {
    fn register_in(c: &wabot_core::injection::Container) {
        c.register_singleton_factory::<SocketChannel, _>(|c2| {
            let cfg: Arc<SocketChannelConfig> = c2.resolve::<SocketChannelConfig>();
            Arc::new(SocketChannel::new((*cfg).clone()))
        });
    }
}