Skip to main content

wabot_feature_socket_controller/
server.rs

1//! Serving the socket namespaces.
2
3use socketioxide::SocketIo;
4use tower_http::cors::CorsLayer;
5
6/// Where the Socket.IO server listens, and who may connect.
7#[derive(Debug, Clone)]
8pub struct SocketServerConfig {
9    pub bind_addr: String,
10    /// `Access-Control-Allow-Origin`. `None` sends no CORS headers,
11    /// which is right for a same-origin deployment and wrong for a
12    /// browser client on another host — so it is a decision the app
13    /// makes rather than a permissive default.
14    pub cors_origin: Option<String>,
15}
16
17impl Default for SocketServerConfig {
18    fn default() -> Self {
19        Self {
20            bind_addr: "0.0.0.0:3001".into(),
21            cors_origin: None,
22        }
23    }
24}
25
26impl SocketServerConfig {
27    pub fn new(bind_addr: impl Into<String>) -> Self {
28        Self {
29            bind_addr: bind_addr.into(),
30            ..Default::default()
31        }
32    }
33
34    /// Read `WABOT_SOCKET_BIND` / `WABOT_SOCKET_CORS_ORIGIN`.
35    pub fn from_env() -> Self {
36        Self {
37            bind_addr: wabot_core::env::string_or("WABOT_SOCKET_BIND", "0.0.0.0:3001"),
38            cors_origin: wabot_core::env::string("WABOT_SOCKET_CORS_ORIGIN"),
39        }
40    }
41
42    pub fn with_cors_origin(mut self, origin: impl Into<String>) -> Self {
43        self.cors_origin = Some(origin.into());
44        self
45    }
46}
47
48/// A fresh Socket.IO layer and its handle.
49///
50/// Attach controllers to the handle, then mount the layer on a router
51/// — either this crate's [`run_socket_controllers`] or your own, if
52/// the process already serves HTTP and you want one listener.
53pub fn socket_layer() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
54    SocketIo::new_layer()
55}
56
57/// Serve the socket layer on its own listener.
58pub async fn run_socket_controllers(
59    layer: socketioxide::layer::SocketIoLayer,
60    config: SocketServerConfig,
61) -> std::io::Result<()> {
62    let mut app = axum::Router::new().layer(layer);
63
64    if let Some(origin) = &config.cors_origin {
65        let cors = if origin == "*" {
66            CorsLayer::permissive()
67        } else {
68            match origin.parse::<axum::http::HeaderValue>() {
69                Ok(value) => CorsLayer::new()
70                    .allow_origin(value)
71                    .allow_methods(tower_http::cors::Any)
72                    .allow_headers(tower_http::cors::Any),
73                Err(error) => {
74                    return Err(std::io::Error::new(
75                        std::io::ErrorKind::InvalidInput,
76                        format!("invalid CORS origin {origin:?}: {error}"),
77                    ))
78                }
79            }
80        };
81        app = app.layer(cors);
82    }
83
84    let listener = tokio::net::TcpListener::bind(&config.bind_addr).await?;
85    tracing::info!("socket server listening on {}", config.bind_addr);
86    axum::serve(listener, app).await
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn the_default_sends_no_cors_headers() {
95        // A permissive default would let any page on the internet open
96        // a socket to a service that never thought about it.
97        assert!(SocketServerConfig::default().cors_origin.is_none());
98    }
99
100    #[tokio::test]
101    async fn a_malformed_cors_origin_fails_the_boot() {
102        let error = run_socket_controllers(
103            socket_layer().0,
104            SocketServerConfig::new("127.0.0.1:0").with_cors_origin("not a header value\n"),
105        )
106        .await
107        .unwrap_err();
108        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
109    }
110}