v1.0.0 — Hexagonal architecture rewrite
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:
2026-08-18 01:41:40 +02:00
parent e9bea5e1e5
commit f652785acb
85 changed files with 4240 additions and 3736 deletions

View 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 }

View 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)
}

View File

@@ -0,0 +1,7 @@
[package]
name = "config-env"
version.workspace = true
edition.workspace = true
[dependencies]
config = { workspace = true }

View 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),
}
}

View 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 }

View File

@@ -0,0 +1,3 @@
mod routes;
pub use routes::build_router;

View 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
})
}

View 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 }

View 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()),
);
}

View 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;
});
}

View 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 }

View 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}"),
}
}

View 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)
}

View 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(),
}
}
}

View File

@@ -0,0 +1,8 @@
[package]
name = "api-types"
version.workspace = true
edition.workspace = true
[dependencies]
domain = { workspace = true }
serde = { workspace = true }

View File

@@ -0,0 +1,27 @@
use domain::PixelUpdate;
use serde::{Deserialize, Serialize};
pub mod events {
pub const CANVAS_STATE: &str = "canvas_state";
pub const PIXEL_UPDATED: &str = "pixel-updated";
pub const PLACE_PIXEL: &str = "place-pixel";
pub const CURRENT_SOLDIERS: &str = "current_soldiers";
pub const ERROR: &str = "error";
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PixelUpdatePayload {
pub x: u32,
pub y: u32,
pub color: u32,
}
impl From<PixelUpdate> for PixelUpdatePayload {
fn from(update: PixelUpdate) -> Self {
Self {
x: update.position().x(),
y: update.position().y(),
color: update.color().as_u32(),
}
}
}

View File

@@ -0,0 +1,10 @@
[package]
name = "application"
version.workspace = true
edition.workspace = true
[dependencies]
domain = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }

View File

@@ -0,0 +1,9 @@
use std::sync::Arc;
use domain::Color;
use crate::AppState;
pub fn execute(state: &AppState) -> Arc<[Color]> {
state.canvas().pixels()
}

View File

@@ -0,0 +1,4 @@
pub mod get_state;
pub mod place_pixel;
pub mod restore_snapshot;
pub mod save_snapshot;

View File

@@ -0,0 +1,29 @@
use domain::{BroadcastEvent, Color, PixelUpdate, Position};
use crate::{AppState, ApplicationError};
pub struct Command<'a> {
pub user_id: &'a str,
pub position: Position,
pub color: Color,
}
pub enum Outcome {
Placed(PixelUpdate),
CooldownActive,
}
pub fn execute(state: &AppState, command: Command<'_>) -> Result<Outcome, ApplicationError> {
if state.cooldowns().is_on_cooldown(command.user_id) {
return Ok(Outcome::CooldownActive);
}
state
.canvas()
.place_pixel(command.position, command.color)?;
state.cooldowns().record(command.user_id);
let update = PixelUpdate::new(command.position, command.color);
state
.broadcaster()
.publish(BroadcastEvent::PixelUpdated(update));
Ok(Outcome::Placed(update))
}

View File

@@ -0,0 +1,14 @@
use crate::{AppState, ApplicationError};
pub fn execute(state: &AppState) -> Result<bool, ApplicationError> {
let Some(persistence) = state.persistence() else {
return Ok(false);
};
match persistence.load_latest()? {
Some(pixels) => {
state.canvas().restore(pixels)?;
Ok(true)
}
None => Ok(false),
}
}

View File

@@ -0,0 +1,10 @@
use crate::{AppState, ApplicationError};
pub fn execute(state: &AppState) -> Result<(), ApplicationError> {
let Some(persistence) = state.persistence() else {
return Ok(());
};
let pixels = state.canvas().pixels();
persistence.save(&pixels)?;
Ok(())
}

View File

@@ -0,0 +1,7 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ApplicationError {
#[error(transparent)]
Domain(#[from] domain::DomainError),
}

View File

@@ -0,0 +1,8 @@
mod errors;
mod state;
pub mod canvas;
pub mod soldiers;
pub use errors::ApplicationError;
pub use state::{AppState, InMemoryCanvasStore, InProcessBroadcaster};

View File

@@ -0,0 +1,11 @@
use domain::BroadcastEvent;
use crate::AppState;
pub fn execute(state: &AppState, user_id: String) -> usize {
let count = state.soldiers().add(user_id);
state
.broadcaster()
.publish(BroadcastEvent::SoldierCountChanged(count));
count
}

View File

@@ -0,0 +1,12 @@
use domain::BroadcastEvent;
use crate::AppState;
pub fn execute(state: &AppState, user_id: &str) -> usize {
state.cooldowns().remove(user_id);
let count = state.soldiers().remove(user_id);
state
.broadcaster()
.publish(BroadcastEvent::SoldierCountChanged(count));
count
}

View File

@@ -0,0 +1,2 @@
pub mod connect;
pub mod disconnect;

View File

@@ -0,0 +1,199 @@
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use domain::ports::{
BroadcastReceiverInner, BroadcastSubscription, CanvasPersistence, CanvasStore, EventBroadcaster,
};
use domain::{BroadcastEvent, Canvas, Color, DomainError, Position};
use tokio::sync::broadcast;
use tracing::warn;
const INITIAL_CONNECTION_CAPACITY: usize = 128;
pub struct AppState {
canvas: Box<dyn CanvasStore>,
broadcaster: Box<dyn EventBroadcaster>,
persistence: Option<Box<dyn CanvasPersistence>>,
cooldowns: CooldownTracker,
soldiers: SoldierTracker,
}
impl AppState {
pub fn new(
canvas: Box<dyn CanvasStore>,
broadcaster: Box<dyn EventBroadcaster>,
cooldown: Duration,
) -> Self {
Self {
canvas,
broadcaster,
persistence: None,
cooldowns: CooldownTracker::new(cooldown),
soldiers: SoldierTracker::new(),
}
}
pub fn with_persistence(mut self, persistence: Box<dyn CanvasPersistence>) -> Self {
self.persistence = Some(persistence);
self
}
pub fn canvas(&self) -> &dyn CanvasStore {
&*self.canvas
}
pub fn broadcaster(&self) -> &dyn EventBroadcaster {
&*self.broadcaster
}
pub fn persistence(&self) -> Option<&dyn CanvasPersistence> {
self.persistence.as_deref()
}
pub fn cooldowns(&self) -> &CooldownTracker {
&self.cooldowns
}
pub fn soldiers(&self) -> &SoldierTracker {
&self.soldiers
}
}
pub struct InProcessBroadcaster {
sender: broadcast::Sender<BroadcastEvent>,
}
impl InProcessBroadcaster {
pub fn new(sender: broadcast::Sender<BroadcastEvent>) -> Self {
Self { sender }
}
}
impl EventBroadcaster for InProcessBroadcaster {
fn publish(&self, event: BroadcastEvent) {
let _ = self.sender.send(event);
}
fn subscribe(&self) -> BroadcastSubscription {
BroadcastSubscription::new(Box::new(TokioBroadcastReceiver(self.sender.subscribe())))
}
}
struct TokioBroadcastReceiver(broadcast::Receiver<BroadcastEvent>);
impl BroadcastReceiverInner for TokioBroadcastReceiver {
fn recv_boxed(&mut self) -> Pin<Box<dyn Future<Output = Option<BroadcastEvent>> + Send + '_>> {
Box::pin(async { self.0.recv().await.ok() })
}
}
fn acquire_lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|poisoned| {
warn!("Recovered from poisoned mutex");
poisoned.into_inner()
})
}
struct CanvasState {
canvas: Canvas,
snapshot: Option<Arc<[Color]>>,
}
pub struct InMemoryCanvasStore {
state: Mutex<CanvasState>,
}
impl InMemoryCanvasStore {
pub fn new(width: u32, height: u32) -> Self {
Self {
state: Mutex::new(CanvasState {
canvas: Canvas::new(width, height),
snapshot: None,
}),
}
}
}
impl CanvasStore for InMemoryCanvasStore {
fn pixels(&self) -> Arc<[Color]> {
let mut state = acquire_lock(&self.state);
if let Some(ref cached) = state.snapshot {
return cached.clone();
}
let new_snapshot: Arc<[Color]> = Arc::from(state.canvas.pixels());
state.snapshot = Some(new_snapshot.clone());
new_snapshot
}
fn place_pixel(&self, position: Position, color: Color) -> Result<(), DomainError> {
let mut state = acquire_lock(&self.state);
state.canvas.place_pixel(position, color)?;
state.snapshot = None;
Ok(())
}
fn restore(&self, pixels: Vec<Color>) -> Result<(), DomainError> {
let mut state = acquire_lock(&self.state);
let new_canvas = Canvas::from_pixels(state.canvas.width(), state.canvas.height(), pixels)?;
state.canvas = new_canvas;
state.snapshot = None;
Ok(())
}
}
pub struct CooldownTracker {
entries: Mutex<HashMap<String, Instant>>,
cooldown: Duration,
}
impl CooldownTracker {
pub fn new(cooldown: Duration) -> Self {
Self {
entries: Mutex::new(HashMap::with_capacity(INITIAL_CONNECTION_CAPACITY)),
cooldown,
}
}
pub fn is_on_cooldown(&self, user_id: &str) -> bool {
let entries = acquire_lock(&self.entries);
entries
.get(user_id)
.map(|last| last.elapsed() < self.cooldown)
.unwrap_or(false)
}
pub fn record(&self, user_id: &str) {
acquire_lock(&self.entries).insert(user_id.to_string(), Instant::now());
}
pub fn remove(&self, user_id: &str) {
acquire_lock(&self.entries).remove(user_id);
}
}
pub struct SoldierTracker {
connected: Mutex<HashSet<String>>,
}
impl SoldierTracker {
pub fn new() -> Self {
Self {
connected: Mutex::new(HashSet::with_capacity(INITIAL_CONNECTION_CAPACITY)),
}
}
pub fn add(&self, user_id: String) -> usize {
let mut connected = acquire_lock(&self.connected);
connected.insert(user_id);
connected.len()
}
pub fn remove(&self, user_id: &str) -> usize {
let mut connected = acquire_lock(&self.connected);
connected.remove(user_id);
connected.len()
}
}

View File

@@ -0,0 +1,109 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use application::{AppState, InMemoryCanvasStore};
use domain::ports::{
BroadcastReceiverInner, BroadcastSubscription, CanvasPersistence, EventBroadcaster,
};
use domain::{BroadcastEvent, Color, DomainError};
#[derive(Clone)]
pub struct SpyBroadcaster {
events: Arc<Mutex<Vec<BroadcastEvent>>>,
}
impl SpyBroadcaster {
pub fn new() -> Self {
Self {
events: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn events(&self) -> Vec<BroadcastEvent> {
self.events.lock().unwrap().clone()
}
pub fn event_count(&self) -> usize {
self.events.lock().unwrap().len()
}
}
impl EventBroadcaster for SpyBroadcaster {
fn publish(&self, event: BroadcastEvent) {
self.events.lock().unwrap().push(event);
}
fn subscribe(&self) -> BroadcastSubscription {
BroadcastSubscription::new(Box::new(NoopReceiver))
}
}
struct NoopReceiver;
impl BroadcastReceiverInner for NoopReceiver {
fn recv_boxed(&mut self) -> Pin<Box<dyn Future<Output = Option<BroadcastEvent>> + Send + '_>> {
Box::pin(async { None })
}
}
pub struct FakePersistence {
saved: Arc<Mutex<Vec<Vec<Color>>>>,
to_load: Mutex<Option<Vec<Color>>>,
}
impl FakePersistence {
pub fn empty() -> Self {
Self {
saved: Arc::new(Mutex::new(Vec::new())),
to_load: Mutex::new(None),
}
}
pub fn with_snapshot(pixels: Vec<Color>) -> Self {
Self {
saved: Arc::new(Mutex::new(Vec::new())),
to_load: Mutex::new(Some(pixels)),
}
}
pub fn saved_ref(&self) -> Arc<Mutex<Vec<Vec<Color>>>> {
self.saved.clone()
}
}
impl CanvasPersistence for FakePersistence {
fn save(&self, pixels: &[Color]) -> Result<(), DomainError> {
self.saved.lock().unwrap().push(pixels.to_vec());
Ok(())
}
fn load_latest(&self) -> Result<Option<Vec<Color>>, DomainError> {
Ok(self.to_load.lock().unwrap().clone())
}
}
pub fn test_state() -> (Arc<AppState>, SpyBroadcaster) {
test_state_sized(10, 10)
}
pub fn test_state_sized(width: u32, height: u32) -> (Arc<AppState>, SpyBroadcaster) {
let spy = SpyBroadcaster::new();
let state = AppState::new(
Box::new(InMemoryCanvasStore::new(width, height)),
Box::new(spy.clone()),
Duration::from_secs(10),
);
(Arc::new(state), spy)
}
pub fn test_state_no_cooldown() -> (Arc<AppState>, SpyBroadcaster) {
let spy = SpyBroadcaster::new();
let state = AppState::new(
Box::new(InMemoryCanvasStore::new(10, 10)),
Box::new(spy.clone()),
Duration::ZERO,
);
(Arc::new(state), spy)
}

View File

@@ -0,0 +1,91 @@
mod common;
use application::canvas::place_pixel::{Command, Outcome};
use domain::{BroadcastEvent, Color, Position};
macro_rules! place {
($state:expr, $user:expr, $x:expr, $y:expr, $color:expr) => {
application::canvas::place_pixel::execute(
&$state,
Command {
user_id: $user,
position: Position::new($x, $y),
color: Color::new($color),
},
)
};
}
#[test]
fn successful_placement_returns_update() {
let (state, _) = common::test_state();
let result = place!(state, "user-1", 3, 4, 0xFF0000).unwrap();
let Outcome::Placed(update) = result else {
panic!("expected Placed outcome");
};
assert_eq!(update.position(), Position::new(3, 4));
assert_eq!(update.color(), Color::new(0xFF0000));
}
#[test]
fn placement_updates_canvas() {
let (state, _) = common::test_state();
place!(state, "user-1", 5, 5, 0xAA).unwrap();
let pixels = application::canvas::get_state::execute(&state);
let idx = 5 * 10 + 5;
assert_eq!(pixels[idx], Color::new(0xAA));
}
#[test]
fn placement_publishes_broadcast_event() {
let (state, spy) = common::test_state();
place!(state, "user-1", 0, 0, 0xFF).unwrap();
let events = spy.events();
assert_eq!(events.len(), 1);
assert!(matches!(events[0], BroadcastEvent::PixelUpdated(_)));
}
#[test]
fn cooldown_blocks_rapid_placement() {
let (state, _) = common::test_state();
place!(state, "user-1", 0, 0, 0xFF).unwrap();
let result = place!(state, "user-1", 1, 1, 0xAA).unwrap();
assert!(matches!(result, Outcome::CooldownActive));
}
#[test]
fn cooldown_is_per_user() {
let (state, _) = common::test_state();
place!(state, "user-1", 0, 0, 0xFF).unwrap();
let result = place!(state, "user-2", 1, 1, 0xAA).unwrap();
assert!(matches!(result, Outcome::Placed(_)));
}
#[test]
fn zero_cooldown_allows_rapid_placement() {
let (state, _) = common::test_state_no_cooldown();
place!(state, "user-1", 0, 0, 0xFF).unwrap();
let result = place!(state, "user-1", 1, 1, 0xAA).unwrap();
assert!(matches!(result, Outcome::Placed(_)));
}
#[test]
fn out_of_bounds_returns_error() {
let (state, _) = common::test_state();
assert!(place!(state, "user-1", 99, 99, 0xFF).is_err());
}
#[test]
fn failed_placement_does_not_trigger_cooldown() {
let (state, _) = common::test_state();
let _ = place!(state, "user-1", 99, 99, 0xFF);
let result = place!(state, "user-1", 0, 0, 0xFF).unwrap();
assert!(matches!(result, Outcome::Placed(_)));
}

View File

@@ -0,0 +1,75 @@
mod common;
use std::sync::Arc;
use application::AppState;
use domain::Color;
fn state_with_persistence(persistence: common::FakePersistence) -> Arc<AppState> {
let spy = common::SpyBroadcaster::new();
let state = AppState::new(
Box::new(application::InMemoryCanvasStore::new(10, 10)),
Box::new(spy),
std::time::Duration::from_secs(10),
)
.with_persistence(Box::new(persistence));
Arc::new(state)
}
#[test]
fn save_snapshot_persists_current_canvas() {
let persistence = common::FakePersistence::empty();
let saved_ref = persistence.saved_ref();
let state = state_with_persistence(persistence);
application::canvas::place_pixel::execute(
&state,
application::canvas::place_pixel::Command {
user_id: "user",
position: domain::Position::new(0, 0),
color: Color::new(0xFF),
},
)
.unwrap();
application::canvas::save_snapshot::execute(&state).unwrap();
let snapshots = saved_ref.lock().unwrap();
assert_eq!(snapshots.len(), 1);
assert_eq!(snapshots[0][0], Color::new(0xFF));
assert_eq!(snapshots[0].len(), 100);
}
#[test]
fn restore_snapshot_loads_canvas() {
let mut snapshot = vec![Color::white(); 100];
snapshot[0] = Color::new(0xDEAD);
snapshot[99] = Color::new(0xBEEF);
let state = state_with_persistence(common::FakePersistence::with_snapshot(snapshot));
let restored = application::canvas::restore_snapshot::execute(&state).unwrap();
assert!(restored);
let pixels = application::canvas::get_state::execute(&state);
assert_eq!(pixels[0], Color::new(0xDEAD));
assert_eq!(pixels[99], Color::new(0xBEEF));
}
#[test]
fn restore_returns_false_when_no_snapshot() {
let state = state_with_persistence(common::FakePersistence::empty());
assert!(!application::canvas::restore_snapshot::execute(&state).unwrap());
}
#[test]
fn save_without_persistence_is_noop() {
let (state, _) = common::test_state();
assert!(application::canvas::save_snapshot::execute(&state).is_ok());
}
#[test]
fn restore_without_persistence_returns_false() {
let (state, _) = common::test_state();
assert!(!application::canvas::restore_snapshot::execute(&state).unwrap());
}

View File

@@ -0,0 +1,96 @@
mod common;
use domain::BroadcastEvent;
#[test]
fn connect_increments_count() {
let (state, _) = common::test_state();
assert_eq!(
application::soldiers::connect::execute(&state, "a".into()),
1
);
assert_eq!(
application::soldiers::connect::execute(&state, "b".into()),
2
);
assert_eq!(
application::soldiers::connect::execute(&state, "c".into()),
3
);
}
#[test]
fn disconnect_decrements_count() {
let (state, _) = common::test_state();
application::soldiers::connect::execute(&state, "a".into());
application::soldiers::connect::execute(&state, "b".into());
assert_eq!(application::soldiers::disconnect::execute(&state, "a"), 1);
assert_eq!(application::soldiers::disconnect::execute(&state, "b"), 0);
}
#[test]
fn disconnect_unknown_user_is_harmless() {
let (state, _) = common::test_state();
application::soldiers::connect::execute(&state, "a".into());
assert_eq!(
application::soldiers::disconnect::execute(&state, "unknown"),
1
);
}
#[test]
fn connect_publishes_soldier_count() {
let (state, spy) = common::test_state();
application::soldiers::connect::execute(&state, "a".into());
let events = spy.events();
assert_eq!(events.len(), 1);
assert!(matches!(events[0], BroadcastEvent::SoldierCountChanged(1)));
}
#[test]
fn disconnect_publishes_soldier_count() {
let (state, spy) = common::test_state();
application::soldiers::connect::execute(&state, "a".into());
application::soldiers::disconnect::execute(&state, "a");
let events = spy.events();
assert_eq!(events.len(), 2);
assert!(matches!(events[1], BroadcastEvent::SoldierCountChanged(0)));
}
#[test]
fn disconnect_clears_cooldown() {
let (state, _) = common::test_state();
application::soldiers::connect::execute(&state, "user-1".into());
application::canvas::place_pixel::execute(
&state,
application::canvas::place_pixel::Command {
user_id: "user-1",
position: domain::Position::new(0, 0),
color: domain::Color::new(0xFF),
},
)
.unwrap();
application::soldiers::disconnect::execute(&state, "user-1");
// Reconnect with same ID — cooldown should be gone
application::soldiers::connect::execute(&state, "user-1".into());
let result = application::canvas::place_pixel::execute(
&state,
application::canvas::place_pixel::Command {
user_id: "user-1",
position: domain::Position::new(1, 1),
color: domain::Color::new(0xAA),
},
)
.unwrap();
assert!(matches!(
result,
application::canvas::place_pixel::Outcome::Placed(_)
));
}

7
crates/config/Cargo.toml Normal file
View File

@@ -0,0 +1,7 @@
[package]
name = "config"
version.workspace = true
edition.workspace = true
[dependencies]
thiserror = { workspace = true }

61
crates/config/src/lib.rs Normal file
View File

@@ -0,0 +1,61 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("invalid value for '{field}': {reason}")]
InvalidValue { field: String, reason: String },
#[error("failed to load config: {0}")]
LoadFailed(String),
}
#[derive(Debug, Clone)]
pub struct AppConfig {
pub server: ServerConfig,
pub canvas: CanvasConfig,
pub cooldown: CooldownConfig,
pub rate_limit: RateLimitConfig,
pub broadcast: BroadcastConfig,
pub snapshot: SnapshotConfig,
}
#[derive(Debug, Clone)]
pub struct ServerConfig {
pub address: String,
pub port: u16,
pub enable_cors: bool,
}
#[derive(Debug, Clone)]
pub struct CanvasConfig {
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone)]
pub struct CooldownConfig {
pub placement_secs: u64,
}
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
pub burst_size: u32,
pub per_second: u64,
}
#[derive(Debug, Clone)]
pub struct BroadcastConfig {
pub channel_capacity: usize,
}
#[derive(Debug, Clone)]
pub struct SnapshotConfig {
pub enabled: bool,
pub interval_secs: u64,
pub max_snapshots: usize,
pub directory: String,
}
pub trait ConfigSource {
fn load(&self) -> Result<AppConfig, ConfigError>;
}

7
crates/domain/Cargo.toml Normal file
View File

@@ -0,0 +1,7 @@
[package]
name = "domain"
version.workspace = true
edition.workspace = true
[dependencies]
thiserror = { workspace = true }

View File

@@ -0,0 +1,57 @@
use crate::{Color, DomainError, PixelUpdate, Position};
pub struct Canvas {
pixels: Vec<Color>,
width: u32,
height: u32,
}
impl Canvas {
pub fn new(width: u32, height: u32) -> Self {
Self {
pixels: vec![Color::white(); (width * height) as usize],
width,
height,
}
}
pub fn from_pixels(width: u32, height: u32, pixels: Vec<Color>) -> Result<Self, DomainError> {
let expected = (width * height) as usize;
if pixels.len() != expected {
return Err(DomainError::InvalidCanvasData {
expected_width: width,
expected_height: height,
actual: pixels.len(),
});
}
Ok(Self {
pixels,
width,
height,
})
}
pub fn place_pixel(
&mut self,
position: Position,
color: Color,
) -> Result<PixelUpdate, DomainError> {
if position.x() >= self.width || position.y() >= self.height {
return Err(DomainError::PixelOutOfBounds(position));
}
self.pixels[(position.y() * self.width + position.x()) as usize] = color;
Ok(PixelUpdate::new(position, color))
}
pub fn pixels(&self) -> &[Color] {
&self.pixels
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
}

View File

@@ -0,0 +1,21 @@
use thiserror::Error;
use crate::Position;
#[derive(Debug, Error)]
pub enum DomainError {
#[error("pixel position {0} is out of bounds")]
PixelOutOfBounds(Position),
#[error(
"invalid canvas dimensions: expected {expected_width}x{expected_height}, got {actual} pixels"
)]
InvalidCanvasData {
expected_width: u32,
expected_height: u32,
actual: usize,
},
#[error("persistence error: {0}")]
Persistence(String),
}

View File

@@ -0,0 +1,7 @@
use crate::PixelUpdate;
#[derive(Debug, Clone, Copy)]
pub enum BroadcastEvent {
PixelUpdated(PixelUpdate),
SoldierCountChanged(usize),
}

13
crates/domain/src/lib.rs Normal file
View File

@@ -0,0 +1,13 @@
pub mod canvas;
pub mod errors;
pub mod events;
pub mod ports;
pub mod value_objects;
pub use canvas::Canvas;
pub use errors::DomainError;
pub use events::BroadcastEvent;
pub use ports::BroadcastSubscription;
pub use value_objects::{Color, PixelUpdate, Position};
pub const COOLDOWN_MESSAGE: &str = "You can only place one pixel per minute";

View File

@@ -0,0 +1,39 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use crate::{BroadcastEvent, Color, DomainError, Position};
pub trait CanvasStore: Send + Sync {
fn pixels(&self) -> Arc<[Color]>;
fn place_pixel(&self, position: Position, color: Color) -> Result<(), DomainError>;
fn restore(&self, pixels: Vec<Color>) -> Result<(), DomainError>;
}
pub trait CanvasPersistence: Send + Sync {
fn save(&self, pixels: &[Color]) -> Result<(), DomainError>;
fn load_latest(&self) -> Result<Option<Vec<Color>>, DomainError>;
}
pub trait EventBroadcaster: Send + Sync {
fn publish(&self, event: BroadcastEvent);
fn subscribe(&self) -> BroadcastSubscription;
}
pub trait BroadcastReceiverInner: Send {
fn recv_boxed(&mut self) -> Pin<Box<dyn Future<Output = Option<BroadcastEvent>> + Send + '_>>;
}
pub struct BroadcastSubscription {
inner: Box<dyn BroadcastReceiverInner>,
}
impl BroadcastSubscription {
pub fn new(inner: Box<dyn BroadcastReceiverInner>) -> Self {
Self { inner }
}
pub async fn recv(&mut self) -> Option<BroadcastEvent> {
self.inner.recv_boxed().await
}
}

View File

@@ -0,0 +1,76 @@
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Color(u32);
impl Color {
pub fn new(value: u32) -> Self {
Self(value)
}
pub fn as_u32(self) -> u32 {
self.0
}
pub fn white() -> Self {
Self(0xFFFFFFFF)
}
pub fn collect_as_u32(colors: &[Color]) -> Vec<u32> {
colors.iter().map(|color| color.as_u32()).collect()
}
pub fn collect_as_bytes(colors: &[Color]) -> Vec<u8> {
colors
.iter()
.flat_map(|color| color.as_u32().to_ne_bytes())
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
x: u32,
y: u32,
}
impl Position {
pub fn new(x: u32, y: u32) -> Self {
Self { x, y }
}
pub fn x(self) -> u32 {
self.x
}
pub fn y(self) -> u32 {
self.y
}
}
impl fmt::Display for Position {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
#[derive(Debug, Clone, Copy)]
pub struct PixelUpdate {
position: Position,
color: Color,
}
impl PixelUpdate {
pub fn new(position: Position, color: Color) -> Self {
Self { position, color }
}
pub fn position(self) -> Position {
self.position
}
pub fn color(self) -> Color {
self.color
}
}

View File

@@ -0,0 +1,125 @@
use domain::{Canvas, Color, DomainError, Position};
macro_rules! pos {
($x:expr, $y:expr) => {
Position::new($x, $y)
};
}
macro_rules! color {
($v:expr) => {
Color::new($v)
};
}
macro_rules! assert_pixel {
($canvas:expr, $x:expr, $y:expr, $expected:expr) => {{
let (x, y): (u32, u32) = ($x, $y);
let idx = y as usize * $canvas.width() as usize + x as usize;
let expected = color!($expected);
assert_eq!($canvas.pixels()[idx], expected, "pixel at ({x}, {y})");
}};
}
fn small_canvas() -> Canvas {
Canvas::new(10, 10)
}
#[test]
fn new_canvas_is_all_white() {
let canvas = small_canvas();
assert_eq!(canvas.pixels().len(), 100);
assert!(canvas.pixels().iter().all(|&c| c == Color::white()));
}
#[test]
fn dimensions_match_construction() {
let canvas = Canvas::new(42, 17);
assert_eq!(canvas.width(), 42);
assert_eq!(canvas.height(), 17);
assert_eq!(canvas.pixels().len(), 42 * 17);
}
#[test]
fn place_pixel_updates_correct_position() {
let mut canvas = small_canvas();
let update = canvas.place_pixel(pos!(3, 4), color!(0xFF0000)).unwrap();
assert_pixel!(canvas, 3, 4, 0xFF0000);
assert_eq!(update.position(), pos!(3, 4));
assert_eq!(update.color(), color!(0xFF0000));
}
#[test]
fn place_pixel_does_not_affect_neighbors() {
let mut canvas = small_canvas();
canvas.place_pixel(pos!(5, 5), color!(0xFF)).unwrap();
for (x, y) in [(4, 5), (6, 5), (5, 4), (5, 6)] {
assert_pixel!(canvas, x, y, 0xFFFFFFFF);
}
}
#[test]
fn place_pixel_overwrites_previous() {
let mut canvas = small_canvas();
canvas.place_pixel(pos!(0, 0), color!(0xAA)).unwrap();
canvas.place_pixel(pos!(0, 0), color!(0xBB)).unwrap();
assert_pixel!(canvas, 0, 0, 0xBB);
}
#[test]
fn place_pixel_at_boundary() {
let mut canvas = small_canvas();
assert!(canvas.place_pixel(pos!(9, 9), color!(0xFF)).is_ok());
assert!(canvas.place_pixel(pos!(0, 0), color!(0xFF)).is_ok());
assert!(canvas.place_pixel(pos!(9, 0), color!(0xFF)).is_ok());
assert!(canvas.place_pixel(pos!(0, 9), color!(0xFF)).is_ok());
}
#[test]
fn place_pixel_out_of_bounds() {
let mut canvas = small_canvas();
for (x, y) in [(10, 0), (0, 10), (10, 10), (100, 100)] {
let result = canvas.place_pixel(pos!(x, y), color!(0xFF));
assert!(
matches!(result, Err(DomainError::PixelOutOfBounds(_))),
"({x}, {y}) should be out of bounds"
);
}
}
#[test]
fn from_pixels_with_correct_size() {
let pixels = vec![color!(0xAA); 25];
let canvas = Canvas::from_pixels(5, 5, pixels).unwrap();
assert_eq!(canvas.width(), 5);
assert_eq!(canvas.height(), 5);
assert!(canvas.pixels().iter().all(|&c| c == color!(0xAA)));
}
#[test]
fn from_pixels_with_wrong_size() {
let too_few = vec![color!(0); 10];
let too_many = vec![color!(0); 30];
for pixels in [too_few, too_many] {
assert!(
matches!(
Canvas::from_pixels(5, 5, pixels),
Err(DomainError::InvalidCanvasData { .. })
),
"should reject pixel vec that doesn't match dimensions"
);
}
}
#[test]
fn from_pixels_preserves_content() {
let mut pixels = vec![Color::white(); 9];
pixels[4] = color!(0xFF0000); // center pixel of 3x3
let canvas = Canvas::from_pixels(3, 3, pixels).unwrap();
assert_pixel!(canvas, 1, 1, 0xFF0000);
assert_pixel!(canvas, 0, 0, 0xFFFFFFFF);
}

View File

@@ -0,0 +1,69 @@
use domain::{Color, PixelUpdate, Position};
#[test]
fn color_roundtrips_through_u32() {
for value in [0, 0xFF, 0xFF0000, 0xFFFFFFFF, 0xDEADBEEF] {
assert_eq!(Color::new(value).as_u32(), value);
}
}
#[test]
fn color_white_is_full_alpha() {
assert_eq!(Color::white().as_u32(), 0xFFFFFFFF);
}
#[test]
fn color_equality() {
assert_eq!(Color::new(42), Color::new(42));
assert_ne!(Color::new(1), Color::new(2));
}
#[test]
fn collect_as_u32_preserves_values() {
let colors = [Color::new(1), Color::new(2), Color::new(3)];
assert_eq!(Color::collect_as_u32(&colors), vec![1, 2, 3]);
}
#[test]
fn collect_as_bytes_length() {
let colors = vec![Color::white(); 10];
assert_eq!(Color::collect_as_bytes(&colors).len(), 40);
}
#[test]
fn collect_as_bytes_roundtrips() {
let original = vec![Color::new(0x01020304), Color::new(0xAABBCCDD)];
let bytes = Color::collect_as_bytes(&original);
let restored: Vec<Color> = bytes
.chunks_exact(4)
.map(|c| Color::new(u32::from_ne_bytes([c[0], c[1], c[2], c[3]])))
.collect();
assert_eq!(original, restored);
}
#[test]
fn position_accessors() {
let pos = Position::new(42, 17);
assert_eq!(pos.x(), 42);
assert_eq!(pos.y(), 17);
}
#[test]
fn position_display() {
assert_eq!(Position::new(3, 7).to_string(), "(3, 7)");
}
#[test]
fn position_equality() {
assert_eq!(Position::new(1, 2), Position::new(1, 2));
assert_ne!(Position::new(1, 2), Position::new(2, 1));
}
#[test]
fn pixel_update_carries_position_and_color() {
let pos = Position::new(5, 10);
let color = Color::new(0xFF00FF);
let update = PixelUpdate::new(pos, color);
assert_eq!(update.position(), pos);
assert_eq!(update.color(), color);
}

26
crates/server/Cargo.toml Normal file
View File

@@ -0,0 +1,26 @@
[package]
name = "server"
version.workspace = true
edition.workspace = true
[features]
default = ["socketio"]
socketio = ["dep:socketio", "dep:socketioxide"]
websocket = ["dep:websocket"]
[dependencies]
application = { workspace = true }
canvas-file = { workspace = true }
config = { workspace = true }
config-env = { workspace = true }
axum = { workspace = true }
domain = { workspace = true }
http-axum = { workspace = true }
dotenv = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
socketio = { workspace = true, optional = true }
socketioxide = { workspace = true, optional = true }
websocket = { workspace = true, optional = true }

133
crates/server/src/main.rs Normal file
View File

@@ -0,0 +1,133 @@
#[cfg(not(any(feature = "socketio", feature = "websocket")))]
compile_error!("Enable either the `socketio` or `websocket` feature");
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use application::{AppState, InMemoryCanvasStore, InProcessBroadcaster};
use canvas_file::FileCanvasPersistence;
use config::{AppConfig, ConfigSource};
use config_env::EnvConfigSource;
use domain::BroadcastEvent;
use tokio::signal;
use tokio::sync::broadcast;
use tracing::{error, info, warn};
use tracing_subscriber::FmtSubscriber;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv::dotenv().ok();
tracing::subscriber::set_global_default(FmtSubscriber::new())?;
let config = EnvConfigSource.load()?;
let state = build_state(&config)?;
if config.snapshot.enabled {
if let Err(err) = application::canvas::restore_snapshot::execute(&state) {
warn!("Failed to restore canvas snapshot: {err}");
}
spawn_snapshot_scheduler(state.clone(), config.snapshot.interval_secs);
}
let app = build_app(state.clone(), &config)?;
let server_address = format!("{}:{}", config.server.address, config.server.port);
info!("Starting server on {server_address}");
let listener = tokio::net::TcpListener::bind(server_address).await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(shutdown_signal())
.await?;
info!("Shutting down gracefully...");
if config.snapshot.enabled {
info!("Saving final canvas snapshot...");
if let Err(err) = application::canvas::save_snapshot::execute(&state) {
error!("Failed to save final snapshot: {err}");
}
}
info!("Server stopped");
Ok(())
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("Failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("Failed to install SIGTERM handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
() = ctrl_c => info!("Received Ctrl+C"),
() = terminate => info!("Received SIGTERM"),
}
}
fn build_state(config: &AppConfig) -> Result<Arc<AppState>, Box<dyn std::error::Error>> {
let (broadcast_tx, _) = broadcast::channel::<BroadcastEvent>(config.broadcast.channel_capacity);
let canvas_store = InMemoryCanvasStore::new(config.canvas.width, config.canvas.height);
let broadcaster = InProcessBroadcaster::new(broadcast_tx);
let cooldown = Duration::from_secs(config.cooldown.placement_secs);
let mut state = AppState::new(Box::new(canvas_store), Box::new(broadcaster), cooldown);
if config.snapshot.enabled {
let persistence = FileCanvasPersistence::new(&config.snapshot)?;
state = state.with_persistence(Box::new(persistence));
}
Ok(Arc::new(state))
}
fn spawn_snapshot_scheduler(state: Arc<AppState>, interval_secs: u64) {
let interval = Duration::from_secs(interval_secs);
info!("Snapshot scheduler started (every {interval_secs}s)");
tokio::spawn(async move {
loop {
tokio::time::sleep(interval).await;
if let Err(err) = application::canvas::save_snapshot::execute(&state) {
error!("Failed to save canvas snapshot: {err}");
}
}
});
}
#[cfg(feature = "socketio")]
fn build_app(
state: Arc<AppState>,
config: &AppConfig,
) -> Result<axum::Router, Box<dyn std::error::Error>> {
let (layer, io) = socketioxide::SocketIo::new_layer();
socketio::setup_namespaces(&io, state);
let router = http_axum::build_router(config.server.enable_cors, &config.rate_limit)?;
Ok(router.layer(layer))
}
#[cfg(feature = "websocket")]
fn build_app(
state: Arc<AppState>,
config: &AppConfig,
) -> Result<axum::Router, Box<dyn std::error::Error>> {
let ws_router = websocket::build_router(state);
let http_router = http_axum::build_router(config.server.enable_cors, &config.rate_limit)?;
Ok(ws_router.merge(http_router))
}