wabot-feature-socket-controller 0.1.0

Socket.IO controller framework — port of wabot-ts feature/socket-controller, built on socketioxide.
Documentation
//! Serving the socket namespaces.

use socketioxide::SocketIo;
use tower_http::cors::CorsLayer;

/// Where the Socket.IO server listens, and who may connect.
#[derive(Debug, Clone)]
pub struct SocketServerConfig {
    pub bind_addr: String,
    /// `Access-Control-Allow-Origin`. `None` sends no CORS headers,
    /// which is right for a same-origin deployment and wrong for a
    /// browser client on another host — so it is a decision the app
    /// makes rather than a permissive default.
    pub cors_origin: Option<String>,
}

impl Default for SocketServerConfig {
    fn default() -> Self {
        Self {
            bind_addr: "0.0.0.0:3001".into(),
            cors_origin: None,
        }
    }
}

impl SocketServerConfig {
    pub fn new(bind_addr: impl Into<String>) -> Self {
        Self {
            bind_addr: bind_addr.into(),
            ..Default::default()
        }
    }

    /// Read `WABOT_SOCKET_BIND` / `WABOT_SOCKET_CORS_ORIGIN`.
    pub fn from_env() -> Self {
        Self {
            bind_addr: wabot_core::env::string_or("WABOT_SOCKET_BIND", "0.0.0.0:3001"),
            cors_origin: wabot_core::env::string("WABOT_SOCKET_CORS_ORIGIN"),
        }
    }

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

/// A fresh Socket.IO layer and its handle.
///
/// Attach controllers to the handle, then mount the layer on a router
/// — either this crate's [`run_socket_controllers`] or your own, if
/// the process already serves HTTP and you want one listener.
pub fn socket_layer() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
    SocketIo::new_layer()
}

/// Serve the socket layer on its own listener.
pub async fn run_socket_controllers(
    layer: socketioxide::layer::SocketIoLayer,
    config: SocketServerConfig,
) -> std::io::Result<()> {
    let mut app = axum::Router::new().layer(layer);

    if let Some(origin) = &config.cors_origin {
        let cors = if origin == "*" {
            CorsLayer::permissive()
        } else {
            match origin.parse::<axum::http::HeaderValue>() {
                Ok(value) => CorsLayer::new()
                    .allow_origin(value)
                    .allow_methods(tower_http::cors::Any)
                    .allow_headers(tower_http::cors::Any),
                Err(error) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        format!("invalid CORS origin {origin:?}: {error}"),
                    ))
                }
            }
        };
        app = app.layer(cors);
    }

    let listener = tokio::net::TcpListener::bind(&config.bind_addr).await?;
    tracing::info!("socket server listening on {}", config.bind_addr);
    axum::serve(listener, app).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_default_sends_no_cors_headers() {
        // A permissive default would let any page on the internet open
        // a socket to a service that never thought about it.
        assert!(SocketServerConfig::default().cors_origin.is_none());
    }

    #[tokio::test]
    async fn a_malformed_cors_origin_fails_the_boot() {
        let error = run_socket_controllers(
            socket_layer().0,
            SocketServerConfig::new("127.0.0.1:0").with_cors_origin("not a header value\n"),
        )
        .await
        .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
    }
}