use socketioxide::SocketIo;
use tower_http::cors::CorsLayer;
#[derive(Debug, Clone)]
pub struct SocketServerConfig {
pub bind_addr: String,
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()
}
}
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
}
}
pub fn socket_layer() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
SocketIo::new_layer()
}
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() {
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);
}
}