Skip to main content

caelix_socketio/
lib.rs

1//! Socket.IO support for Caelix's Axum runtime.
2//!
3//! This crate intentionally has no Actix dependency. It is exposed through
4//! `caelix::socket_io` only when the `socketio` feature selects Axum.
5
6use caelix_core::{Container, HttpException, Result};
7use serde::Serialize;
8
9pub use socketioxide::layer::SocketIoLayer;
10pub use socketioxide::{
11    SocketIo,
12    extract::{AckSender, Data, SocketRef},
13};
14
15/// The Socket.IO server handle registered as a first-class Caelix provider by
16/// [`caelix_axum::Application::with_socket_io`].
17#[derive(Clone)]
18pub struct SocketIoHandle {
19    io: SocketIo,
20}
21
22impl SocketIoHandle {
23    /// Builds the Tower layer and its matching injectable handle exactly once.
24    pub fn build() -> (SocketIoLayer, Self) {
25        let (layer, io) = SocketIo::builder().build_layer();
26        (layer, Self { io })
27    }
28
29    pub fn io(&self) -> &SocketIo {
30        &self.io
31    }
32}
33
34/// Implemented by `#[gateway("/namespace")]` for Socket.IO gateways.
35#[doc(hidden)]
36pub trait SocketIoGateway: Send + Sync + 'static {
37    fn register_socket_io(io: &SocketIo, container: &Container) -> Result<()>;
38}
39
40/// Serializable failure payload used for both acknowledgement replies and the
41/// mandatory `"error"` event emitted for failed handlers.
42#[derive(Serialize)]
43pub struct SocketIoError {
44    pub error: String,
45    pub message: String,
46}
47
48impl From<HttpException> for SocketIoError {
49    fn from(exception: HttpException) -> Self {
50        Self {
51            error: exception.error.to_owned(),
52            message: exception.message,
53        }
54    }
55}