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