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

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