v1.0.0 — Hexagonal architecture rewrite
All checks were successful
CI / ci (push) Successful in 7m16s
All checks were successful
CI / ci (push) Successful in 7m16s
Restructure the monolithic 252-line main.rs into a 10-crate workspace with clean hexagonal architecture, swappable adapters, and a production- ready deployment pipeline. Backend architecture: - domain: Canvas, Color/Position/PixelUpdate value objects, port traits (CanvasStore, CanvasPersistence, EventBroadcaster), BroadcastEvent - application: use cases (place_pixel, get_state, save/restore snapshot, connect/disconnect), AppState with Arc snapshot cache - config: AppConfig structs + ConfigSource trait - api-types: shared DTOs, event name constants - adapters: config-env, canvas-file, http-axum (rust-embed), socketio, websocket — all behind port traits, swappable via feature flags - server: composition root with graceful shutdown (SIGTERM/SIGINT) Frontend: - Transport abstraction: Socket.IO and native WebSocket via VITE_TRANSPORT - Canvas zoom/pan with mouse wheel, pinch-to-zoom, and +/- buttons - ImageData rendering (~50x faster than fillRect loop) - Touch support, responsive CSS scaling, mobile-friendly layout - OG/Twitter Card meta tags for rich link previews Production: - Docker: musl static build on scratch — 2.73MB image - CI workflows for Gitea and GitHub Actions (fmt, clippy, test, Docker push) - deploy.sh for private registry - 39 unit tests across domain and application - Zero unwraps, zero unsafe, graceful error handling with tracing - Periodic canvas snapshots with rotation, restored on startup - All config via environment variables with typed defaults
This commit is contained in:
9
crates/adapters/canvas-file/Cargo.toml
Normal file
9
crates/adapters/canvas-file/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "canvas-file"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
config = { workspace = true }
|
||||
domain = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
158
crates/adapters/canvas-file/src/lib.rs
Normal file
158
crates/adapters/canvas-file/src/lib.rs
Normal file
@@ -0,0 +1,158 @@
|
||||
use std::fs;
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use config::SnapshotConfig;
|
||||
use domain::ports::CanvasPersistence;
|
||||
use domain::{Color, DomainError};
|
||||
use tracing::{error, info};
|
||||
|
||||
pub struct FileCanvasPersistence {
|
||||
directory: PathBuf,
|
||||
max_snapshots: usize,
|
||||
}
|
||||
|
||||
impl FileCanvasPersistence {
|
||||
pub fn new(config: &SnapshotConfig) -> Result<Self, DomainError> {
|
||||
let directory = PathBuf::from(&config.directory);
|
||||
fs::create_dir_all(&directory).map_err(|err| {
|
||||
DomainError::Persistence(format!(
|
||||
"Failed to create snapshot directory '{}': {err}",
|
||||
directory.display()
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(Self {
|
||||
directory,
|
||||
max_snapshots: config.max_snapshots,
|
||||
})
|
||||
}
|
||||
|
||||
fn snapshot_path(&self, index: usize) -> PathBuf {
|
||||
self.directory.join(format!("canvas_{index}.bin"))
|
||||
}
|
||||
|
||||
fn latest_index_path(&self) -> PathBuf {
|
||||
self.directory.join("latest")
|
||||
}
|
||||
|
||||
fn read_latest_index(&self) -> Option<usize> {
|
||||
let path = self.latest_index_path();
|
||||
fs::read_to_string(&path)
|
||||
.ok()
|
||||
.and_then(|content| content.trim().parse().ok())
|
||||
}
|
||||
|
||||
fn write_latest_index(&self, index: usize) -> Result<(), DomainError> {
|
||||
let path = self.latest_index_path();
|
||||
fs::write(&path, index.to_string())
|
||||
.map_err(|err| DomainError::Persistence(format!("Failed to write latest index: {err}")))
|
||||
}
|
||||
|
||||
fn rotate_and_cleanup(&self, new_index: usize) {
|
||||
if self.max_snapshots == 0 {
|
||||
return;
|
||||
}
|
||||
let oldest_to_keep = new_index.saturating_sub(self.max_snapshots - 1);
|
||||
for stale_index in 0..oldest_to_keep {
|
||||
let stale_path = self.snapshot_path(stale_index);
|
||||
if stale_path.exists()
|
||||
&& let Err(err) = fs::remove_file(&stale_path)
|
||||
{
|
||||
error!(
|
||||
"Failed to remove old snapshot '{}': {err}",
|
||||
stale_path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasPersistence for FileCanvasPersistence {
|
||||
fn save(&self, pixels: &[Color]) -> Result<(), DomainError> {
|
||||
let next_index = self.read_latest_index().map(|i| i + 1).unwrap_or(0);
|
||||
let path = self.snapshot_path(next_index);
|
||||
|
||||
write_pixels_to_file(&path, pixels)?;
|
||||
self.write_latest_index(next_index)?;
|
||||
self.rotate_and_cleanup(next_index);
|
||||
|
||||
info!(
|
||||
"Saved canvas snapshot #{next_index} to '{}'",
|
||||
path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_latest(&self) -> Result<Option<Vec<Color>>, DomainError> {
|
||||
let Some(index) = self.read_latest_index() else {
|
||||
info!("No canvas snapshots found");
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let path = self.snapshot_path(index);
|
||||
if !path.exists() {
|
||||
info!("Snapshot file '{}' not found", path.display());
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let pixels = read_pixels_from_file(&path)?;
|
||||
info!(
|
||||
"Loaded canvas snapshot #{index} from '{}' ({} pixels)",
|
||||
path.display(),
|
||||
pixels.len()
|
||||
);
|
||||
Ok(Some(pixels))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_pixels_to_file(path: &Path, pixels: &[Color]) -> Result<(), DomainError> {
|
||||
let file = fs::File::create(path).map_err(|err| {
|
||||
DomainError::Persistence(format!(
|
||||
"Failed to create snapshot '{}': {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
for color in pixels {
|
||||
writer
|
||||
.write_all(&color.as_u32().to_ne_bytes())
|
||||
.map_err(|err| {
|
||||
DomainError::Persistence(format!(
|
||||
"Failed to write snapshot '{}': {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
}
|
||||
writer.flush().map_err(|err| {
|
||||
DomainError::Persistence(format!(
|
||||
"Failed to flush snapshot '{}': {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_pixels_from_file(path: &Path) -> Result<Vec<Color>, DomainError> {
|
||||
let bytes = fs::read(path).map_err(|err| {
|
||||
DomainError::Persistence(format!(
|
||||
"Failed to read snapshot '{}': {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
|
||||
if bytes.len() % 4 != 0 {
|
||||
return Err(DomainError::Persistence(format!(
|
||||
"Snapshot '{}' has invalid size: {} bytes (not a multiple of 4)",
|
||||
path.display(),
|
||||
bytes.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let pixels = bytes
|
||||
.chunks_exact(4)
|
||||
.map(|chunk| Color::new(u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])))
|
||||
.collect();
|
||||
|
||||
Ok(pixels)
|
||||
}
|
||||
7
crates/adapters/config-env/Cargo.toml
Normal file
7
crates/adapters/config-env/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "config-env"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
config = { workspace = true }
|
||||
70
crates/adapters/config-env/src/lib.rs
Normal file
70
crates/adapters/config-env/src/lib.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use config::{
|
||||
AppConfig, BroadcastConfig, CanvasConfig, ConfigError, ConfigSource, CooldownConfig,
|
||||
RateLimitConfig, ServerConfig, SnapshotConfig,
|
||||
};
|
||||
|
||||
const DEFAULT_ADDRESS: &str = "0.0.0.0";
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
const DEFAULT_CANVAS_WIDTH: u32 = 500;
|
||||
const DEFAULT_CANVAS_HEIGHT: u32 = 500;
|
||||
const DEFAULT_COOLDOWN_SECS: u64 = 10;
|
||||
const DEFAULT_RATE_LIMIT_BURST: u32 = 10;
|
||||
const DEFAULT_RATE_LIMIT_PER_SECOND: u64 = 10;
|
||||
const DEFAULT_BROADCAST_CAPACITY: usize = 1024;
|
||||
const DEFAULT_SNAPSHOT_INTERVAL_SECS: u64 = 300;
|
||||
const DEFAULT_SNAPSHOT_MAX: usize = 5;
|
||||
const DEFAULT_SNAPSHOT_DIR: &str = "snapshots/";
|
||||
|
||||
pub struct EnvConfigSource;
|
||||
|
||||
impl ConfigSource for EnvConfigSource {
|
||||
fn load(&self) -> Result<AppConfig, ConfigError> {
|
||||
Ok(AppConfig {
|
||||
server: ServerConfig {
|
||||
address: env_or("ADDRESS", DEFAULT_ADDRESS),
|
||||
port: parse_env("PORT", DEFAULT_PORT)?,
|
||||
enable_cors: parse_bool_env("ENABLE_CORS", true),
|
||||
},
|
||||
canvas: CanvasConfig {
|
||||
width: parse_env("CANVAS_WIDTH", DEFAULT_CANVAS_WIDTH)?,
|
||||
height: parse_env("CANVAS_HEIGHT", DEFAULT_CANVAS_HEIGHT)?,
|
||||
},
|
||||
cooldown: CooldownConfig {
|
||||
placement_secs: parse_env("COOLDOWN_SECS", DEFAULT_COOLDOWN_SECS)?,
|
||||
},
|
||||
rate_limit: RateLimitConfig {
|
||||
burst_size: parse_env("RATE_LIMIT_BURST", DEFAULT_RATE_LIMIT_BURST)?,
|
||||
per_second: parse_env("RATE_LIMIT_PER_SECOND", DEFAULT_RATE_LIMIT_PER_SECOND)?,
|
||||
},
|
||||
broadcast: BroadcastConfig {
|
||||
channel_capacity: parse_env("BROADCAST_CAPACITY", DEFAULT_BROADCAST_CAPACITY)?,
|
||||
},
|
||||
snapshot: SnapshotConfig {
|
||||
enabled: parse_bool_env("SNAPSHOT_ENABLED", true),
|
||||
interval_secs: parse_env("SNAPSHOT_INTERVAL_SECS", DEFAULT_SNAPSHOT_INTERVAL_SECS)?,
|
||||
max_snapshots: parse_env("SNAPSHOT_MAX", DEFAULT_SNAPSHOT_MAX)?,
|
||||
directory: env_or("SNAPSHOT_DIR", DEFAULT_SNAPSHOT_DIR),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn env_or(key: &str, default: &str) -> String {
|
||||
std::env::var(key).unwrap_or_else(|_| default.to_string())
|
||||
}
|
||||
|
||||
fn parse_bool_env(key: &str, default: bool) -> bool {
|
||||
std::env::var(key)
|
||||
.map(|value| value == "true")
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
fn parse_env<T: std::str::FromStr>(key: &str, default: T) -> Result<T, ConfigError> {
|
||||
match std::env::var(key) {
|
||||
Ok(value) => value.parse().map_err(|_| ConfigError::InvalidValue {
|
||||
field: key.to_string(),
|
||||
reason: format!("'{value}' is not a valid {}", std::any::type_name::<T>()),
|
||||
}),
|
||||
Err(_) => Ok(default),
|
||||
}
|
||||
}
|
||||
12
crates/adapters/http-axum/Cargo.toml
Normal file
12
crates/adapters/http-axum/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "http-axum"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
config = { workspace = true }
|
||||
axum = { workspace = true }
|
||||
rust-embed = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tower-http = { workspace = true }
|
||||
tower_governor = { workspace = true }
|
||||
3
crates/adapters/http-axum/src/lib.rs
Normal file
3
crates/adapters/http-axum/src/lib.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
mod routes;
|
||||
|
||||
pub use routes::build_router;
|
||||
80
crates/adapters/http-axum/src/routes.rs
Normal file
80
crates/adapters/http-axum/src/routes.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::{StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Router, routing::get};
|
||||
use config::RateLimitConfig;
|
||||
use rust_embed::Embed;
|
||||
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
|
||||
const RATE_LIMIT_CLEANUP_INTERVAL_SECS: u64 = 1;
|
||||
|
||||
#[derive(Embed)]
|
||||
#[folder = "$CARGO_MANIFEST_DIR/../../../painter-js/dist/"]
|
||||
struct StaticAssets;
|
||||
|
||||
async fn serve_static(path: axum::extract::Path<String>) -> Response {
|
||||
let path = path.0;
|
||||
serve_embedded_file(&path)
|
||||
}
|
||||
|
||||
async fn serve_index() -> Response {
|
||||
serve_embedded_file("index.html")
|
||||
}
|
||||
|
||||
fn serve_embedded_file(path: &str) -> Response {
|
||||
match StaticAssets::get(path) {
|
||||
Some(file) => {
|
||||
let content_type = file.metadata.mimetype();
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, content_type.to_string())],
|
||||
file.data,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
None => serve_embedded_file("index.html"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_router(
|
||||
enable_cors: bool,
|
||||
rate_limit_config: &RateLimitConfig,
|
||||
) -> Result<Router, String> {
|
||||
let rate_governor = Arc::new(
|
||||
GovernorConfigBuilder::default()
|
||||
.burst_size(rate_limit_config.burst_size)
|
||||
.per_second(rate_limit_config.per_second)
|
||||
.finish()
|
||||
.ok_or("Invalid rate limit configuration")?,
|
||||
);
|
||||
|
||||
let governor = rate_governor.limiter().clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(
|
||||
RATE_LIMIT_CLEANUP_INTERVAL_SECS,
|
||||
))
|
||||
.await;
|
||||
governor.retain_recent();
|
||||
}
|
||||
});
|
||||
|
||||
let router = Router::new()
|
||||
.route("/check/", get(|| async { "OK" }))
|
||||
.route("/{*path}", get(serve_static))
|
||||
.fallback(get(serve_index))
|
||||
.layer(GovernorLayer::new(rate_governor));
|
||||
|
||||
Ok(if enable_cors {
|
||||
router.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any),
|
||||
)
|
||||
} else {
|
||||
router
|
||||
})
|
||||
}
|
||||
13
crates/adapters/socketio/Cargo.toml
Normal file
13
crates/adapters/socketio/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "socketio"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
application = { workspace = true }
|
||||
api-types = { workspace = true }
|
||||
domain = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
socketioxide = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
109
crates/adapters/socketio/src/handlers.rs
Normal file
109
crates/adapters/socketio/src/handlers.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use api_types::{self, PixelUpdatePayload};
|
||||
use application::AppState;
|
||||
use application::canvas::place_pixel;
|
||||
use domain::{BroadcastEvent, BroadcastSubscription, Color, Position};
|
||||
use socketioxide::extract::{Data, SocketRef};
|
||||
use tracing::info;
|
||||
|
||||
pub async fn on_connect(socket: SocketRef, state: Arc<AppState>) {
|
||||
info!("Socket connected: {:?} {:?}", socket.ns(), socket.id);
|
||||
|
||||
let subscription = state.broadcaster().subscribe();
|
||||
|
||||
send_canvas_state(&socket, &state);
|
||||
register_soldier(&state, &socket);
|
||||
spawn_broadcast_forwarder(socket.clone(), subscription);
|
||||
register_place_pixel_handler(&socket, state.clone());
|
||||
register_disconnect_handler(&socket, state);
|
||||
}
|
||||
|
||||
fn send_canvas_state(socket: &SocketRef, state: &AppState) {
|
||||
let canvas_pixels = application::canvas::get_state::execute(state);
|
||||
let pixel_values = Color::collect_as_u32(&canvas_pixels);
|
||||
socket
|
||||
.emit(api_types::events::CANVAS_STATE, &pixel_values)
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn register_soldier(state: &AppState, socket: &SocketRef) {
|
||||
let socket_id = socket.id.to_string();
|
||||
application::soldiers::connect::execute(state, socket_id);
|
||||
}
|
||||
|
||||
fn spawn_broadcast_forwarder(socket: SocketRef, mut subscription: BroadcastSubscription) {
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = subscription.recv().await {
|
||||
if forward_broadcast_event(&socket, &event).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn forward_broadcast_event(socket: &SocketRef, event: &BroadcastEvent) -> Result<(), ()> {
|
||||
match event {
|
||||
BroadcastEvent::PixelUpdated(update) => {
|
||||
let payload = PixelUpdatePayload::from(*update);
|
||||
socket
|
||||
.emit(api_types::events::PIXEL_UPDATED, &payload)
|
||||
.map_err(|_| ())
|
||||
}
|
||||
BroadcastEvent::SoldierCountChanged(count) => socket
|
||||
.emit(api_types::events::CURRENT_SOLDIERS, count)
|
||||
.map_err(|_| ()),
|
||||
}
|
||||
}
|
||||
|
||||
fn register_place_pixel_handler(socket: &SocketRef, state: Arc<AppState>) {
|
||||
socket.on(
|
||||
api_types::events::PLACE_PIXEL,
|
||||
move |socket: SocketRef, Data::<PixelUpdatePayload>(payload)| async move {
|
||||
handle_place_pixel(&socket, &state, payload);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn handle_place_pixel(socket: &SocketRef, state: &AppState, payload: PixelUpdatePayload) {
|
||||
let position = Position::new(payload.x, payload.y);
|
||||
let color = Color::new(payload.color);
|
||||
|
||||
info!("Received pixel update: {position} color={}", color.as_u32());
|
||||
|
||||
let socket_id = socket.id.to_string();
|
||||
let command = place_pixel::Command {
|
||||
user_id: &socket_id,
|
||||
position,
|
||||
color,
|
||||
};
|
||||
|
||||
match place_pixel::execute(state, command) {
|
||||
Ok(place_pixel::Outcome::Placed(_)) => {}
|
||||
Ok(place_pixel::Outcome::CooldownActive) => {
|
||||
emit_error(socket, domain::COOLDOWN_MESSAGE);
|
||||
}
|
||||
Err(err) => {
|
||||
emit_error(socket, &err.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn register_disconnect_handler(socket: &SocketRef, state: Arc<AppState>) {
|
||||
socket.on_disconnect(move |socket: SocketRef| async move {
|
||||
handle_disconnect(&socket, &state);
|
||||
});
|
||||
}
|
||||
|
||||
fn handle_disconnect(socket: &SocketRef, state: &AppState) {
|
||||
info!("Socket disconnected: {:?}", socket.id);
|
||||
let socket_id = socket.id.to_string();
|
||||
application::soldiers::disconnect::execute(state, &socket_id);
|
||||
}
|
||||
|
||||
fn emit_error(socket: &SocketRef, message: &str) {
|
||||
let _ = socket.emit(
|
||||
api_types::events::ERROR,
|
||||
&serde_json::Value::String(message.to_string()),
|
||||
);
|
||||
}
|
||||
12
crates/adapters/socketio/src/lib.rs
Normal file
12
crates/adapters/socketio/src/lib.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
mod handlers;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use application::AppState;
|
||||
use socketioxide::{SocketIo, extract::SocketRef};
|
||||
|
||||
pub fn setup_namespaces(io: &SocketIo, state: Arc<AppState>) {
|
||||
io.ns("/", move |socket: SocketRef| async move {
|
||||
handlers::on_connect(socket, state).await;
|
||||
});
|
||||
}
|
||||
14
crates/adapters/websocket/Cargo.toml
Normal file
14
crates/adapters/websocket/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "websocket"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
application = { workspace = true }
|
||||
domain = { workspace = true }
|
||||
axum = { workspace = true, features = ["ws"] }
|
||||
futures = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
163
crates/adapters/websocket/src/handler.rs
Normal file
163
crates/adapters/websocket/src/handler.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::response::IntoResponse;
|
||||
use domain::{BroadcastEvent, BroadcastSubscription, Color, Position};
|
||||
use futures::{SinkExt, StreamExt, stream::SplitSink};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::WsState;
|
||||
use crate::messages::{ClientMessage, ServerMessage};
|
||||
use application::AppState;
|
||||
use application::canvas::place_pixel;
|
||||
|
||||
type WsSender = SplitSink<WebSocket, Message>;
|
||||
|
||||
pub async fn ws_upgrade(
|
||||
ws: WebSocketUpgrade,
|
||||
State(state): State<Arc<WsState>>,
|
||||
) -> impl IntoResponse {
|
||||
ws.on_upgrade(|socket| handle_connection(socket, state))
|
||||
}
|
||||
|
||||
async fn handle_connection(socket: WebSocket, state: Arc<WsState>) {
|
||||
let (mut sender, mut receiver) = socket.split();
|
||||
|
||||
let connection_id = state
|
||||
.connection_counter
|
||||
.fetch_add(1, Ordering::Relaxed)
|
||||
.to_string();
|
||||
|
||||
info!("WebSocket connected: {connection_id}");
|
||||
|
||||
// Subscribe before snapshotting to avoid missing updates
|
||||
let subscription = state.app_state.broadcaster().subscribe();
|
||||
|
||||
if !send_canvas_snapshot(&mut sender, &state.app_state).await {
|
||||
return;
|
||||
}
|
||||
|
||||
application::soldiers::connect::execute(&state.app_state, connection_id.clone());
|
||||
|
||||
let (error_sender, error_receiver) = mpsc::unbounded_channel::<String>();
|
||||
|
||||
let mut send_task = tokio::spawn(run_send_loop(sender, subscription, error_receiver));
|
||||
|
||||
let app_state = state.app_state.clone();
|
||||
let recv_connection_id = connection_id.clone();
|
||||
let mut recv_task = tokio::spawn(async move {
|
||||
while let Some(Ok(message)) = receiver.next().await {
|
||||
if let Message::Text(text) = message {
|
||||
handle_client_message(&app_state, &error_sender, &recv_connection_id, &text);
|
||||
} else if let Message::Close(_) = message {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
tokio::select! {
|
||||
_ = &mut send_task => recv_task.abort(),
|
||||
_ = &mut recv_task => send_task.abort(),
|
||||
}
|
||||
|
||||
info!("WebSocket disconnected: {connection_id}");
|
||||
application::soldiers::disconnect::execute(&state.app_state, &connection_id);
|
||||
}
|
||||
|
||||
async fn send_canvas_snapshot(sender: &mut WsSender, state: &AppState) -> bool {
|
||||
let pixels = application::canvas::get_state::execute(state);
|
||||
let bytes = Color::collect_as_bytes(&pixels);
|
||||
sender.send(Message::Binary(bytes.into())).await.is_ok()
|
||||
}
|
||||
|
||||
async fn run_send_loop(
|
||||
mut sender: WsSender,
|
||||
mut subscription: BroadcastSubscription,
|
||||
mut error_receiver: mpsc::UnboundedReceiver<String>,
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(event) = subscription.recv() => {
|
||||
let Some(json) = serialize_broadcast_event(&event) else { continue };
|
||||
if sender.send(Message::Text(json.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some(error_json) = error_receiver.recv() => {
|
||||
if sender.send(Message::Text(error_json.into())).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
else => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_broadcast_event(event: &BroadcastEvent) -> Option<String> {
|
||||
let message = match event {
|
||||
BroadcastEvent::PixelUpdated(update) => ServerMessage::from(*update),
|
||||
BroadcastEvent::SoldierCountChanged(count) => {
|
||||
ServerMessage::CurrentSoldiers { count: *count }
|
||||
}
|
||||
};
|
||||
serde_json::to_string(&message)
|
||||
.inspect_err(|err| error!("Failed to serialize broadcast event: {err}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
fn handle_client_message(
|
||||
state: &AppState,
|
||||
error_sender: &mpsc::UnboundedSender<String>,
|
||||
connection_id: &str,
|
||||
text: &str,
|
||||
) {
|
||||
let Ok(message) = serde_json::from_str::<ClientMessage>(text) else {
|
||||
return;
|
||||
};
|
||||
|
||||
match message {
|
||||
ClientMessage::PlacePixel { x, y, color } => {
|
||||
handle_place_pixel(state, error_sender, connection_id, x, y, color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_place_pixel(
|
||||
state: &AppState,
|
||||
error_sender: &mpsc::UnboundedSender<String>,
|
||||
connection_id: &str,
|
||||
x: u32,
|
||||
y: u32,
|
||||
color: u32,
|
||||
) {
|
||||
let command = place_pixel::Command {
|
||||
user_id: connection_id,
|
||||
position: Position::new(x, y),
|
||||
color: Color::new(color),
|
||||
};
|
||||
|
||||
match place_pixel::execute(state, command) {
|
||||
Ok(place_pixel::Outcome::Placed(_)) => {}
|
||||
Ok(place_pixel::Outcome::CooldownActive) => {
|
||||
send_error(error_sender, domain::COOLDOWN_MESSAGE);
|
||||
}
|
||||
Err(err) => {
|
||||
send_error(error_sender, &err.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_error(error_sender: &mpsc::UnboundedSender<String>, message: &str) {
|
||||
let error_message = ServerMessage::Error {
|
||||
message: message.to_string(),
|
||||
};
|
||||
match serde_json::to_string(&error_message) {
|
||||
Ok(json) => {
|
||||
let _ = error_sender.send(json);
|
||||
}
|
||||
Err(err) => error!("Failed to serialize error message: {err}"),
|
||||
}
|
||||
}
|
||||
24
crates/adapters/websocket/src/lib.rs
Normal file
24
crates/adapters/websocket/src/lib.rs
Normal file
@@ -0,0 +1,24 @@
|
||||
mod handler;
|
||||
mod messages;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
use application::AppState;
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
pub(crate) struct WsState {
|
||||
app_state: Arc<AppState>,
|
||||
connection_counter: AtomicU64,
|
||||
}
|
||||
|
||||
pub fn build_router(state: Arc<AppState>) -> Router {
|
||||
let ws_state = Arc::new(WsState {
|
||||
app_state: state,
|
||||
connection_counter: AtomicU64::new(0),
|
||||
});
|
||||
|
||||
Router::new()
|
||||
.route("/ws", get(handler::ws_upgrade))
|
||||
.with_state(ws_state)
|
||||
}
|
||||
30
crates/adapters/websocket/src/messages.rs
Normal file
30
crates/adapters/websocket/src/messages.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use domain::PixelUpdate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ClientMessage {
|
||||
#[serde(rename = "place-pixel")]
|
||||
PlacePixel { x: u32, y: u32, color: u32 },
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ServerMessage {
|
||||
#[serde(rename = "pixel-updated")]
|
||||
PixelUpdated { x: u32, y: u32, color: u32 },
|
||||
#[serde(rename = "current_soldiers")]
|
||||
CurrentSoldiers { count: usize },
|
||||
#[serde(rename = "error")]
|
||||
Error { message: String },
|
||||
}
|
||||
|
||||
impl From<PixelUpdate> for ServerMessage {
|
||||
fn from(update: PixelUpdate) -> Self {
|
||||
Self::PixelUpdated {
|
||||
x: update.position().x(),
|
||||
y: update.position().y(),
|
||||
color: update.color().as_u32(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user