Skip to content

Conversation

@JRamonAlves
Copy link
Owner

@JRamonAlves JRamonAlves commented Feb 2, 2026

Summary by CodeRabbit

  • New Features

    • REST API for chess game management with endpoints for creating games, retrieving game state, applying moves, and listing legal moves.
    • Support for FEN notation, move validation, and game status tracking (ongoing, checkmate, stalemate, draw).
    • Move history tracking in both standard and algebraic notation formats.
  • Chores

    • Updated package configuration and added web framework dependencies.
    • Optimized release build profile for improved performance.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Feb 2, 2026

📝 Walkthrough

Walkthrough

The codebase undergoes a major architectural transformation, replacing a custom chess library with an Axum-based REST API service. The old modular design (Casa, Jogador, Peca traits, Posicao, Tabuleiro) is removed entirely, and game logic now delegates to the shakmaty chess library via a new in-memory game store with UUID-based game sessions and RESTful endpoints.

Changes

Cohort / File(s) Summary
Project Manifest
Cargo.toml
Crate renamed from chess_rust to chess-api; added web service dependencies (axum, tokio, serde, tower-http); removed old binary target; added release profile optimizations (lto, codegen-units, opt-level).
Removed Chess Library Architecture
casa.rs, jogador.rs, tabuleiro.rs, posicao.rs
Deleted core domain types: Casa, Jogador, Tabuleiro, and position enums (Linha, Coluna, Posicao) that formed the old custom chess abstraction.
Removed Piece Trait & Implementations
peca.rs, peca/bispo.rs, peca/cavalo.rs, peca/peao.rs, peca/rainha.rs, peca/rei.rs, peca/torre.rs
Eliminated custom Peca trait and all six piece type implementations; logic now delegated to shakmaty library.
Old Main & Module Exports
main.rs (original)
Removed top-level module declarations (casa, jogador, peca, posicao, tabuleiro), Cor enum, and main function entry point.
New REST API Server
src/main.rs (new)
Complete Axum-based REST API with in-memory game store (Arc\<RwLock\<HashMap\<Uuid, GameEntry>>>), endpoints for game CRUD and move operations, FEN support, move history tracking (UCI/SAN), game status derivation, error handling with custom ApiError type, and integration with shakmaty for chess logic.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as API Server
    participant Store as Game Store
    participant Engine as shakmaty Engine

    Client->>API: POST /games (optional FEN)
    API->>Engine: Parse FEN or use default
    Engine-->>API: Position created
    API->>Store: Create GameEntry (UUID)
    Store-->>API: Store game state
    API-->>Client: GameResponse { id, fen }

    Client->>API: POST /games/:id/moves (UCI move)
    API->>Store: Get GameEntry by id
    Store-->>API: Current Position + History
    API->>Engine: Parse UCI move string
    Engine->>Engine: Validate move legality
    Engine-->>API: Move object
    API->>Engine: Apply move to position
    Engine-->>API: New position + status
    API->>Engine: Generate SAN from move
    Engine-->>API: SAN notation
    API->>Store: Update position & history
    Store-->>API: Success
    API-->>Client: GameResponse { fen, status, legal_moves, applied_move }
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Poem

🐰 From library halls to API routes we hop,
Old pieces crumble, shakmaty takes the top,
In-memory boards with UUIDs shine,
Chess moves fly swift o'er JSON and wine,
REST endpoints flourish where Tabuleiros once stood!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: transforming a chess implementation into a REST API with Axum framework, as evidenced by the complete redesign of main.rs with API endpoints and the addition of REST-specific dependencies.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/first-version

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/main.rs`:
- Around line 22-34: The in-memory Store (type Store, AppState.store holding
GameEntry) is unbounded and can exhaust memory; add capacity and eviction
controls by replacing or wrapping Store with a bounded structure (e.g., an LRU
or size-limited HashMap) and track last_access/created timestamps on GameEntry
(add a timestamp field to GameEntry) so stale games can be expired; enforce a
max game count in the game-creation code path (check AppState.max_games before
inserting) and implement a background cleanup task that removes entries older
than AppState.ttl, and optionally add simple rate-limiting checks on the
create-game endpoint to prevent rapid creation from one client. Ensure reads
update the GameEntry timestamp so TTL reflects inactivity and use atomic
counters/locks in AppState to make max-count checks race-safe.
🧹 Nitpick comments (3)
src/main.rs (3)

136-136: CorsLayer::permissive() allows all origins.

This is overly permissive for production environments, allowing any website to make requests to your API. For development/first version this is acceptable, but before production deployment, configure specific allowed origins.


139-139: Consider making the bind address configurable.

The port is hardcoded to 3000. Consider reading from an environment variable for deployment flexibility:

♻️ Suggested improvement
-    let addr: SocketAddr = ([0, 0, 0, 0], 3000).into();
+    let port: u16 = std::env::var("PORT")
+        .ok()
+        .and_then(|p| p.parse().ok())
+        .unwrap_or(3000);
+    let addr: SocketAddr = ([0, 0, 0, 0], port).into();

322-326: Remove unnecessary comment.

The comment about "Using a trick" is misleading since pos.turn() is the straightforward, documented way to get the side to move.

♻️ Suggested cleanup
 fn side_to_move(pos: &Chess) -> Color {
-    // Using a trick: if any legal move exists for White when pos is white to move, but we can directly access via pos.turn()
-    // Shakmaty exposes the side to move via pos.turn().
     pos.turn()
 }

Comment on lines +22 to +34
type Store = Arc<RwLock<HashMap<Uuid, GameEntry>>>;

#[derive(Clone)]
struct AppState {
store: Store,
}

#[derive(Debug)]
struct GameEntry {
pos: Chess,
history_uci: Vec<String>,
history_san: Vec<String>,
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Unbounded in-memory store could lead to memory exhaustion.

The store has no size limits. A malicious actor could create unlimited games, exhausting server memory. Consider adding:

  • Maximum game count limit
  • TTL/expiration for inactive games
  • Rate limiting on game creation

This is acceptable for an initial version but should be addressed before production deployment.

🤖 Prompt for AI Agents
In `@src/main.rs` around lines 22 - 34, The in-memory Store (type Store,
AppState.store holding GameEntry) is unbounded and can exhaust memory; add
capacity and eviction controls by replacing or wrapping Store with a bounded
structure (e.g., an LRU or size-limited HashMap) and track last_access/created
timestamps on GameEntry (add a timestamp field to GameEntry) so stale games can
be expired; enforce a max game count in the game-creation code path (check
AppState.max_games before inserting) and implement a background cleanup task
that removes entries older than AppState.ttl, and optionally add simple
rate-limiting checks on the create-game endpoint to prevent rapid creation from
one client. Ensure reads update the GameEntry timestamp so TTL reflects
inactivity and use atomic counters/locks in AppState to make max-count checks
race-safe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants