wabot_feature_socket_controller/
server.rs1use socketioxide::SocketIo;
4use tower_http::cors::CorsLayer;
5
6#[derive(Debug, Clone)]
8pub struct SocketServerConfig {
9 pub bind_addr: String,
10 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 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
48pub fn socket_layer() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
54 SocketIo::new_layer()
55}
56
57pub 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 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}