About arc42

arc42, the template for documentation of software and system architecture.

Template Version 8.2 EN. (based upon AsciiDoc version), January 2023

Created, maintained and © by Dr. Peter Hruschka, Dr. Gernot Starke and contributors. See https://arc42.org.


Note

This version of the template contains some help and explanations. It is used for familiarization with arc42 and the understanding of the concepts. For documentation of your own system you use better the plain version.

1. Introduction and Goals

Describes the relevant requirements and the driving forces that software architects and development team must consider.

1.1. Requirements Overview

YOVI is a gaming suite developed for Micrati based on "Game Y". The system allows users to play hexagonal board games against the computer and provides an interface for external bots.

Key functional requirements include:

  • Core Gameplay: Implementation of classic Game Y with variable board sizes.

  • AI Strategies: Support for multiple machine strategies and selectable difficulty levels.

  • User Management: Registration and match history tracking (win/loss stats).

  • External Access: A fully documented API for bot interaction using YEN notation.

  • Public Availability: The system must be deployed and accessible via the web.

1.2. Quality Goals

Contents

The top three (max five) quality goals for the architecture whose fulfillment is of highest importance to the major stakeholders. We really mean quality goals for the architecture. Don’t confuse them with project goals. They are not necessarily identical.

Consider this overview of potential topics (based upon the ISO 25010 standard):

Categories of Quality Requirements
Motivation

You should know the quality goals of your most important stakeholders, since they will influence fundamental architectural decisions. Make sure to be very concrete about these qualities, avoid buzzwords. If you as an architect do not know how the quality of your work will be judged…​

Form

A table with quality goals and concrete scenarios, ordered by priorities

The following table presents the top five quality goals for the YOVI architecture, ordered by priority. These goals have been identified based on stakeholder expectations and the ISO 25010 quality model. They represent the most critical quality attributes that will guide architectural decisions throughout the project and serve as the primary criteria for evaluating the success of the system.

Priority Quality Goal Concrete Scenario

1

Performance Efficiency

The Rust engine must respond to move validation and AI suggestions in under 200ms, ensuring a smooth gameplay experience even during peak usage.

2

Compatibility (Interoperability)

The system must allow external bots to connect via a well-documented JSON API (YEN notation), enabling third-party developers to create their own game clients.

3

Functional Suitability

The Rust engine must accurately implement all "Game Y" rules, and the web frontend must cover all user stories including registration, gameplay, and statistics.

4

Maintainability

The architecture must keep Rust logic independent from the TypeScript layer, with clear ADRs and >80% code coverage, allowing evaluators and future developers to understand and modify the system.

5

Transferability

The complete system must be deployable with a single Docker command, ensuring evaluators can easily install and test the application on any modern environment.

1.3. Stakeholders

Contents

Explicit overview of stakeholders of the system, i.e. all person, roles or organizations that

  • should know the architecture

  • have to be convinced of the architecture

  • have to work with the architecture or with code

  • need the documentation of the architecture for their work

  • have to come up with decisions about the system or its development

Motivation

You should know all parties involved in development of the system or affected by the system. Otherwise, you may get nasty surprises later in the development process. These stakeholders determine the extent and the level of detail of your work and its results.

Form

Table with role names, person names, and their expectations with respect to the architecture and its documentation.

This section provides an explicit overview of the stakeholders of the system. Stakeholders include all persons, roles, or organizations that should know the architecture, need to be convinced of it, have to work with the architecture or codebase, require the documentation for their work, or are involved in making decisions about the system and its development. We have identified the following stakeholders related to our project:

Category Stakeholder Impact Influence Key Interests & Expectations

1. Primary Owners

Micrati

Critical

High

Successful delivery of the YOVI suite based on "Game Y".

2. End Users

Human Players

High

Medium

Smooth UX, web-based matches, and accurate statistics.

Bot Developers

Medium

Medium

Robust external API and clear technical documentation.

3. Technical Team

Project Team

Critical

High

Proper implementation of TypeScript and Rust subsystems.

Architects

High

High

Structural integrity, ADR maintenance, and quality attributes.

DevOps/SysAdmin

Medium

Medium

Seamless CI/CD, deployment, and system monitoring.

4. External

Competing Teams

Low

Low

Interoperability and compatibility for optional matches.

5. Academic

Evaluators

Critical

High

Test coverage, documentation quality, and project management.

2. Architecture Constraints

Requirements that constrain the freedom of design and implementation.

Constraint Description

Programming Languages

The Web application must be implemented in TypeScript; the logic/strategy module must be in Rust.

Data Exchange

Communication must use JSON messages following the YEN notation standard.

Interface Architecture

The Rust module must be exposed as a basic web service interface (stateless).

Project Management

Mandatory use of GitHub Issues for task tracking and ADRs for documenting architectural decisions.

Infrastructure

The system must be deployed to a public cloud provider using automated CI/CD.

3. Context and Scope

3.1. Business context

03 1 business context
Figure 1. Business Context Diagram
Actor Input Output

Player

  • Size of the board

  • Difficulty

  • Movements

  • Email & Password

  • Result of the game

  • Game History

  • Statistics

  • Ranking

External bot (Claude)

  • Petitions through play()

  • Answer with the next movement (in YEN notation), obtained by querying Claude AI

External bot (Minimax)

  • Petitions through play()

  • Answer with the next movement (in YEN notation), obtained by applying minimax algorithm

3.2. Technical Context

Protocol Format

Webapp ↔ Users Service

HTTP

JSON

Webapp ↔ GameY

HTTP

JSON (YEN notation)

Users Service ↔ Database

Direct connection (driver de BD)

Structured Data

4. Solution Strategy

Contents

A short summary and explanation of the fundamental decisions and solution strategies.

4.1. Strategic Decisions

Goal / Problem Decision Rationale

Database Technology

SQL (PostgreSQL)

A relational database ensures data integrity for users and matches. PostgreSQL offers flexibility and robustness for long-term storage.

Backend Architecture

Component-based & Layered

Organized into independent components with layers (entry-points, domain, data-access) to ensure maintainability and separation of concerns.

Game Logic Engine

Rust

High-performance engine to handle Game Y logic. It allows the implementation of complex AI strategies without sacrificing response time.

Frontend Technology

Web Application (React)

The user interface is developed as a web application. The team prioritized Quality of Life (QoL) features such as Hints and Undo button, while discarding complex media features like video chat.

AI Levels

Selectable Difficulty

The system provides multiple difficulty levels. This satisfies the requirement of having more than one machine strategy (e.g., Random vs. Minimax).

User Interaction

Text-based Chat

A lightweight text chat is implemented to enhance social interaction between players without the technical overhead of video/audio streaming.

Security

Hashing & Env Variables

Encryption for passwords and environment variables for secrets to follow security best practices.

Ranking System

Winrate Metric

Focuses on the win/loss ratio to provide a simple but competitive ranking for the leaderboard.

Game State Persistence

Dedicated 'game_saves' table

To prevent database saturation and optimize network traffic, the matches table is only accessed at the start and end of a game. Turn-by-turn data and manual saves are isolated in a dedicated game_saves table, keeping the main matches metadata clean and fast.

4.2. Organizational & Development Strategy

Decisions regarding team coordination and workflow to ensure project quality:

  • Task Distribution: Work is divided into fixed sub-groups of 2-3 people (Frontend, Backend, Rust/Docs) to ensure code reviews and knowledge sharing.

  • GitHub Workflow:

    • Pull Requests are reviewed by the sub-group (Frontend/Backend) NOT related to the topic itself, ensuring shared understanding of project upgrades among team members.

  • Documentation: Developed collaboratively and consolidated in specific sessions.

5. Building Block View

The building block view shows the static decomposition of the system into building blocks (modules, components, subsystems, classes, interfaces, etc.) as well as their dependencies. In analogy to a house, this is the floor plan.

5.1. Whitebox Overall System

YOVI Level 1 Overview Diagram
Motivation

The YOVI system follows the Separation of Concerns principle. It uses a modern React frontend for user interaction, a Node.js microservice for user data management, and a high-performance Rust engine for game logic. This hybrid architecture ensures scalability and runtime efficiency.

Contained Building Blocks
Name Responsibility

YOVI Web Client

React-based frontend. Visualizes the game board, manages user registration, and provides a REST API for bot interactions.

Users API (Node.js)

Node.js backend managing user profiles, authentication, and game history metrics.

GameY Service (Rust)

Rust-based engine that validates Game Y rules, checks win conditions, and generates AI moves.

PostgreSQL Database

Relational database for persistent storage of user profiles and match statistics.

Important Interfaces
  • YEN Notation: Standard JSON format carrying board states between the YOVI Web Client and GameY Service.

  • REST API (Internal): Endpoints enabling communication between the YOVI Web Client and Users API.

5.1.1. YOVI Web Client (Black Box)

Purpose/Responsibility

Providing the user interface and system access for human players and external bots.

Interface(s)

Web GUI (HTML/CSS/TS), External Bot REST API (JSON).

Directory/File Location

/webapp

Fulfilled Requirements

Web frontend, Bot interaction API, User registration.

5.1.2. Users API (Black Box)

Purpose/Responsibility

Managing user information and game metrics through database communication.

Interface(s)

Internal REST API (Node.js/Express over Port 3000).

Directory/File Location

/users

Fulfilled Requirements

Registration system, Match history, Win/Loss statistics.

5.1.3. Gamey Service (Black Box)

Purpose/Responsibility

Execution of Game Y rules and providing AI strategies at multiple difficulty levels.

Interface(s)

YEN Service Interface (JSON/HTTP over Port 4000).

Quality Characteristics

High calculation speed (Rust), Memory safety, and high concurrency.

Directory/File Location

/gamey

Fulfilled Requirements

Rule validation, Next move suggestions, Multiple AI strategies.


5.2. 5.2 Level 2

5.2.1. 5.2.1 White Box GameY Service

Since the GameY Service handles the core logic of Game Y, its internal structure is detailed to show the decoupling of rules and strategies.

GameY Service White Box Diagram

Contained Building Blocks (Black Boxes):

Name Responsibility

Web Interface

The REST controller that receives YEN-encoded requests from the Webapp.

Core Logic

The engine’s core that validates Game Y rules and determines game outcomes.

Strategy Registry

Manages various AI difficulty levels and provides next-move suggestions.

YEN Parser

Translates between JSON-based YEN notation and internal Rust data structures.

5.2.2. 5.2.2 White Box Webapp

The Webapp is the primary interface for users. Its internal architecture separates visual components from communication logic.

Webapp White Box Diagram

Contained Building Blocks (Black Boxes):

React Components React views including the Game Board, Register Form, and Statistics dashboard.

Client State

Centralized client-side store maintaining the current game state and user session.

REST Services Client

Orchestrates asynchronous HTTP communication with Users API and GameY Service.

Important Interfaces
  • External Bot API: A direct endpoint in the API Client that allows bot actors to interact with the system without using the GUI.

  • Service Connectors: Outbound connections from the API Client to external microservices (Users/Gamey).

6. Runtime View

6.1. User Login

This diagram represents the action of the user login

Login

6.2. User Signup

This diagrams represent the action of signing up

Signup

6.3. User plays the game

This diagram shows the execution of a game

Game

6.4. Asking for a hint

This diagram represents the user asking for a hint

Asking for Hint

7. Deployment View

Content

The deployment view describes:

  1. technical infrastructure used to execute your system, with infrastructure elements like geographical locations, environments, computers, processors, channels and net topologies as well as other infrastructure elements and

  2. mapping of (software) building blocks to that infrastructure elements.

Often systems are executed in different environments, e.g. development environment, test environment, production environment. In such cases you should document all relevant environments.

Especially document a deployment view if your software is executed as distributed system with more than one computer, processor, server or container or when you design and construct your own hardware processors and chips.

From a software perspective it is sufficient to capture only those elements of an infrastructure that are needed to show a deployment of your building blocks. Hardware architects can go beyond that and describe an infrastructure to any level of detail they need to capture.

Motivation

Software does not run without hardware. This underlying infrastructure can and will influence a system and/or some cross-cutting concepts. Therefore, there is a need to know the infrastructure.

Form

Maybe a highest level deployment diagram is already contained in section 3.2. as technical context with your own infrastructure as ONE black box. In this section one can zoom into this black box using additional deployment diagrams:

  • UML offers deployment diagrams to express that view. Use it, probably with nested diagrams, when your infrastructure is more complex.

  • When your (hardware) stakeholders prefer other kinds of diagrams rather than a deployment diagram, let them use any kind that is able to show nodes and channels of the infrastructure.

Further Information

See Deployment View in the arc42 documentation.

7.1. Infrastructure Level 1

Describe (usually in a combination of diagrams, tables, and text):

  • distribution of a system to multiple locations, environments, computers, processors, .., as well as physical connections between them

  • important justifications or motivations for this deployment structure

  • quality and/or performance features of this infrastructure

  • mapping of software artifacts to elements of this infrastructure

For multiple environments or alternative deployments please copy and adapt this section of arc42 for all relevant environments.

Infrastructure Level 1 Overview
Motivation

The system is designed as a distributed web application. A central server hosts all the application logic and data (backend, game engine, database), while users access the game via standard web browsers. This centralized structure ensures data consistency and simplifies updates.

Quality and/or Performance Features
  • Scalability: The server uses Docker, allowing easy scaling of resources if the number of players increases.

  • Accessibility: Users do not need to install any specific software; a web browser is sufficient.

  • Availability: The server is accessible 24/7 via the internet.

Mapping of Building Blocks to Infrastructure
  • Client Device: Runs the Frontend Application (React) inside the browser.

  • External Bot Device: Runs custom bot scripts developed by third parties.

  • YOVI Server: Runs the Backend (Users Service), Game Engine (Rust), and Database.

7.2. Infrastructure Level 2

Here you can include the internal structure of (some) infrastructure elements from level 1.

Please copy the structure from level 1 for each selected element.

7.2.1. Docker Host (Server)

Docker Host Detail

This diagram illustrates the internal structure of the Server. The entire system is containerized using Docker, which ensures consistency across development and production environments.

  • Docker Host: The physical or virtual server running the Docker Engine.

  • WebApp Container: Hosts the React frontend application. It acts as the entry point for users and external bots. It forwards API requests to the backend services.

  • Users Service Container: A Node.js/Express application that handles user authentication and history management. It is not directly accessible from the outside; it only accepts requests from the WebApp.

  • GameY Service Container: The core game engine written in Rust. It processes game logic and validates moves. Like the Users Service, it is internal and accessed via the WebApp.

  • Database Container: A PostgreSQL instance used for persistent storage of user data and game history. It is strictly isolated and only accessible by the Users Service via TCP port 5432.

7.2.2. Client Device

User Device Detail

This diagram illustrates the client-side deployment.

  • Client Device: Represents the physical hardware (PC or Mobile) used by the player.

  • Web Browser: The execution environment (e.g., Chrome, Firefox) that renders the application.

  • YOVI Web Client: The React/TypeScript application artifact downloaded from the server and executed within the browser.

7.2.3. External Bot Device

External Bot Device Detail

This diagram illustrates the deployment of an external bot that interacts with the YOVI system. Unlike human players, bots do not use a web browser; instead, they run as standalone scripts or applications.

  • External Bot Device: Represents any machine (local computer or server) hosting a third-party bot.

  • Bot Runtime: The environment required to execute the bot logic (e.g., Python Interpreter, Java Virtual Machine, or Node.js Runtime).

  • Bot Application: The actual code developed by third parties (or the development team for testing). It communicates with the YOVI System exclusively via the HTTP/REST API (JSON) provided by the Web Application.

8. Cross-cutting Concepts

This section outlines the principal regulations, patterns, and solution ideas that apply across multiple building blocks of the YOVI system. By establishing these rules, we ensure conceptual integrity and consistency throughout the architecture.

YOVI Crosscutting Concepts Concept Map

8.1. 8.1 Inter-Component Communication & YEN Notation

Communication between the decoupled subsystems (YOVI Web Client, Users API, and GameY Service) relies entirely on lightweight, stateless REST APIs exchanging JSON payloads.

A core crosscutting domain concept is the YEN (Y-Game Extended Notation). It is the standardized format for representing the game board, turn state, and player layout.

  • Impact: The React frontend must serialize board states into YEN, the external bots must read/write YEN, and the Rust engine’s YEN Parser must deserialize it to evaluate the core logic. Having a single source of truth for game notation ensures consistency across the TypeScript and Rust boundaries.

8.2. 8.2 Microservices & Containerization Pattern

The system strictly follows a microservices architectural style to separate the high-performance CPU-bound tasks (GameY Service) from I/O-bound tasks (Users API).

  • Impact: To maintain consistency in deployment and operation, all core components are packaged into isolated Docker containers (WebApp, Users API, GameY Service, and PostgreSQL). This containerization concept simplifies deployment to the Docker Host Server and ensures uniform environment configurations across development, testing, and production.

8.3. 8.3 Security & Authentication

Security is managed uniformly at the entry points of the system to protect user profiles and ensure fair play in the leaderboards.

  • Human Players: The YOVI Web Client communicates with the Users API to authenticate players (e.g., via JSON Web Tokens - JWT). This token is required for all state-altering requests, such as updating match history.

  • External Bots: External scripts/applications interacting with the External Bot API must use bot-specific identifiers or API keys. This prevents system abuse and accurately tracks bot performance metrics.

8.4. 8.4 User Experience (UX) & Internationalization (i18n)

To fulfill the optional system requirements, the presentation layer follows specific UX and localization patterns.

  • Responsive Design: The Web Client components are styled using responsive paradigms to support seamless gameplay on both PC and mobile devices.

Further Information

See Concepts in the arc42 documentation.

=== Ranking System Concept

==== Overview

The Game Y ranking system provides competitive leaderboard functionality that automatically tracks player performance across all matches. It uses a score-based ranking model where players are positioned based on their win-loss records.

==== Architecture

The ranking system is implemented across three components:

  1. Backend Database Layer: Stores ranking statistics (total_matches, win_matches, score)

  2. Business Logic Layer: Calculates rankings, manages match completion, and updates player statistics

  3. Frontend Presentation Layer: Displays ranking position in user profile and global leaderboard

==== Score Calculation Formula

score = 50 * (2 * wins - total_matches)

This formula ensures: - Victory is rewarded (+2 points per win) - Matches are always counted (-1 point per match) - High win rates result in positive scores - Loss-heavy records result in negative scores

Example Calculations:
  • 10 wins, 0 losses: score = 50 * (2*10 - 10) = 500

  • 9 wins, 1 loss: score = 50 * (2*9 - 10) = 400

  • 5 wins, 5 losses: score = 50 * (2*5 - 10) = 0

  • 0 wins, 10 losses: score = 50 * (2*0 - 10) = -500

==== Data Flow: Match Completion

┌─────────────────┐
│  Game Ends      │
│  (Winner Known) │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────────┐
│ Frontend: POST /matches/finish  │
│ {matchId, winnerId}             │
└────────┬────────────────────────┘
         │
         ▼
┌──────────────────────────────┐
│  Backend Receives Match End  │
│  • Record winner             │
│  • Set status to 'finished'  │
└────────┬─────────────────────┘
         │
         ▼
┌────────────────────────────────┐
│  Check Player Rankings         │
│  • Does winner have ranking?   │
│  • Does loser have ranking?    │
└────────┬───────────────────────┘
         │
    ┌────┴────┐
    ▼         ▼
┌───────┐ ┌──────────────┐
│ New   │ │ Existing     │
│Player │ │ Player       │
└───┬───┘ └──────┬───────┘
    │            │
    ▼            ▼
┌──────────────┐ ┌──────────────────┐
│Initialize:  │ │Update:           │
│• total: 1   │ │• total += 1      │
│• wins: 1    │ │• wins += (0 or 1)│
│• score: 50  │ │• recalc score    │
└──────────────┘ └──────────────────┘
    │                    │
    └────────┬───────────┘
             │
             ▼
    ┌────────────────────┐
    │ Update Database    │
    │ Persist Rankings   │
    └────────┬───────────┘
             │
             ▼
    ┌────────────────────┐
    │ Return Success     │
    │ with Match Data    │
    └────────────────────┘

==== Integration Points

===== Match Service

The match completion flow is integrated into the matchService.finishMatch() function:

const finishMatch = async (matchId, winnerId) => {
  try {
    // 1. Update match as finished
    const match = await matchRepository.finishMatch(matchId, winnerId);

    // 2. Update both players' rankings
    const winnerRanking = await rankingService
      .updateOrInitializeRanking(winnerId, 1, 1);

    const loserRanking = await rankingService
      .updateOrInitializeRanking(loserId, 1, 0);

    return match;
  } catch (error) {
    throw new Error(`Failed to finish match: ${error.message}`);
  }
};

===== Frontend Integration

The ranking is automatically fetched and displayed when users open their profile:

// hooks/useUserProfile.ts
const { profile, ranking, ... } = useUserProfile(open);

// The ranking is fetched via: GET /ranking/me?userId={userId}
// And displayed in the ProfileOverlay component

==== API Endpoints

Get User’s Ranking Position

GET /ranking/me?userId={userId}
Response: { position: 5, totalPlayers: 127 }

Get Global Rankings

GET /ranking/global
Response: Array of all players ranked by score

Finish Match and Update Rankings

POST /matches/finish
Request: { matchId: uuid, winnerId: uuid }
Response: Updated match with winner information

==== Performance Considerations

  1. Ranking Calculation: Position is determined by O(n) query sorting all rankings by score

  2. Update Frequency: Rankings are updated immediately upon match completion

  3. Caching: Consider caching global rankings for frequently accessed data

  4. Index Strategy: Database indexes on score and user_id columns optimize queries

==== Error Handling

  1. New Players: Automatically initialize ranking on first match

  2. Network Failures: Frontend gracefully falls back to mock data

  3. Database Issues: API returns appropriate error codes (400, 404, 500)

  4. Concurrent Updates: Database constraints ensure data integrity

==== Future Enhancements

  1. Seasonal Leaderboards: Reset rankings at season boundaries

  2. ELO-Style Rating: Adjust points based on opponent strength

  3. Achievements: Award badges for ranking milestones

  4. Real-time Updates: WebSocket notifications for leaderboard changes

  5. Statistics Tracking: Detailed player statistics and analytics

    • Localization: UI components are structured to support internationalization (i18n), strictly separating hardcoded text from the views to allow dynamic switching between different languages.

== Architecture Decisions

This section contains the most important architectural decisions made during the design and development of the YOVI system, following the Michael Nygard ADR (Architecture Decision Record) structure.


=== ADR-001: Database Technology Selection Status: Accepted

Context: The GAME Y project requires persistent data storage to support game-related information (users, matches, etc.). At this early stage of the project, a decision about the database technology is needed to guide further architectural and implementation decisions.

Decision: The team decided to use a SQL-based relational database as the persistence technology for the project.

Consequences:

  • The data model will follow a strict relational structure.

  • The backend architecture will be designed to interact with a SQL database.

  • This decision may limit flexibility compared to NoSQL alternatives, but it provides strong data consistency and maturity of tooling.


=== ADR-002: Backend Structure Status: Accepted

Context: After selecting the SQL database, we needed to define how to organize the source code of the backend service (Users API).

Decision: The system is implemented as a Modular Monolith. This approach was chosen to minimize infrastructure complexity and deployment overhead for the current scope of the project, while the internal modular structure ensures a clear path to microservices if future scalability requires it. The "big picture" of the backend is divided into independent components, and each component is split into 3 layers: entry-points, domain, and data-access.

Consequences:

  • High Cohesion: All code related to a specific feature is located in one folder.

  • Maintainability: It is easier to make changes without affecting other parts of the system.

  • Scalability: If a component becomes too large or complex, it can be easily extracted/divided since it is already isolated.


=== ADR-003: PostgreSQL as DBMS Status: Accepted

Context: To develop the database layer, we had to choose a specific Database Management System (DBMS).

Decision: After analyzing the needs of the application, the team decided to use PostgreSQL as the DBMS because it offers several advantages:

  • It is free and open-source.

  • It supports both relational and non-relational (JSONB) data types, which could be useful in the future if we need to use a hybrid approach.

Consequences:

  • Ensures robustness, reliability, and data integrity.

  • Provides excellent performance and concurrency handling.


=== ADR-004: Selection of Mock Database for Testing Status: Accepted

Context: With the migration to a Cloud-hosted PostgreSQL database, relying on a live connection for every test introduces latency and risks data pollution during concurrent development. We need a fast, isolated way to validate our 3-layer backend logic.

Decision: The team decided to implement a Mock Database strategy using in-memory technologies (such as H2, SQLite :memory:, or mocking frameworks) for unit and integration tests.

Consequences:

  • Test Isolation: Each test runs in a clean environment, preventing interference between team members.

  • Execution Speed: In-memory operations are significantly faster than remote Cloud DB calls.

  • Development Independence: Components can be tested even without an active internet connection.

  • Maintenance: Requires additional effort to keep mock data schemas synchronized with the production PostgreSQL schema.


=== ADR-005: Backend Programming Paradigm Status: Accepted

Context: We must choose which paradigm we are going to use to develop the backend to ensure consistency between the different modules.

Decision: The team decided to adopt the functional programming paradigm for implementing the modules instead of the Object-Oriented Paradigm (OOP). The backend relies heavily on pure functions and immutable data.

Consequences:

  • Easier testing: Using functions that do not depend on internal state reduces issues when testing the app and ensures predictable behavior.

  • Extinction of unintended side effects.

  • Easier maintenance: Since we do not have complex inheritance hierarchies, it is easier to understand what each isolated function does.


=== ADR-006: Separation of Matches and Game Saves Status: Accepted

Context: We initially considered tracking game history and board positions directly within the matches table. However, updating the database on every single turn would overload the server and create a bottleneck.

Decision: We will create a dedicated game_saves table. The matches table will only be queried/updated at the start and end of a game. The active game state will only be stored in game_saves when the user explicitly clicks the "Save" button or exits the match.

Consequences:

  • Massively reduces database load and network traffic.

  • Keeps the matches table clean and strictly for historical tracking.

  • Introduces slightly more complex logic in the backend to manage two tables instead of one.


=== ADR-007: Polyglot Architecture (TypeScript & Rust) Status: Accepted

Context: The project requires a scalable web interface, a user management system, and a highly performant game engine to evaluate moves and execute AI bot strategies.

Decision: The system is implemented using a polyglot approach. The YOVI Web Client and Users API are developed in TypeScript (React and Node.js) to leverage the vast web ecosystem. The GameY Service (evaluation and strategy module) is implemented in Rust to guarantee memory safety and high calculation speed for the AI.

Consequences:

  • Maximizes the performance of the AI engine while keeping web development agile.

  • Increases cognitive load on the development team, as they must maintain codebases and tooling for two entirely different programming ecosystems.


=== ADR-008: Stateless Game Engine Communication (YEN & JSON) Status: Accepted

Context: Because the frontend and the game engine are decoupled and written in different languages, they need a standardized, language-agnostic way to exchange complex board layouts and game states.

Decision: Communication between the Web Client/Bots and the Rust Game Engine is strictly done via stateless JSON messages over HTTP, utilizing the standard YEN (Y-Game Extended Notation) for board representation. The Rust module acts as a stateless REST service (basic web service interface).

Consequences:

  • Ensures perfect decoupling; the Rust engine does not need to store active sessions in its memory.

  • Makes it extremely easy for external third-party bots to integrate with the API.

  • Requires serialization/deserialization overhead for every move.


=== ADR-009: Cloud Infrastructure & CI/CD Status: Accepted

Context: To fulfill the requirement of making the application publicly accessible and easily maintainable, we need a reliable deployment strategy that minimizes manual intervention.

Decision: The system will be deployed to a public cloud provider utilizing Docker containerization. Furthermore, all deployments will be handled via automated CI/CD pipelines (Continuous Integration and Continuous Deployment).

Consequences:

  • Guarantees that the code running in production exactly matches the tested codebase.

  • Allows rapid, zero-downtime updates to the web application and game engine.

  • Requires an initial time investment to write and configure the pipeline scripts (e.g., GitHub Actions).

== Quality Requirements

Content

This section contains all quality requirements as quality tree with scenarios. The most important ones have already been described in section 1.2. (quality goals).

=== Quality Tree

The following quality tree provides a high-level overview of the quality attributes that are most important for the GAME Y system, broken down into specific evaluation areas and prioritized to guide architectural decisions.

  • Quality

  • Usability

  • Accessibility (Colorblind support) → See [US-1]

  • Internationalization (Multi-language) → See [US-2]

  • Performance

  • AI Response Time (Bot algorithms) → See [PE-1]

  • UI Responsiveness (Hexagonal grid rendering) → See [PE-2]

  • Security

  • Data Privacy (Password encryption with Bcrypt) → See [SE-1]

  • Input Validation (Registration integrity) → See [SE-2]

  • Maintainability & Testability

  • Automated Testing (E2E & Integration with Playwright) → See [MT-1]

  • Architectural Cleanliness (Layer separation) → See [MT-2]

=== Quality Scenarios

The following tables describe specific scenarios that concretize the quality requirements. They detail how the system should react to specific stimuli to ensure the architectural goals are met.

==== Usability Scenarios

ID Quality Attribute Scenario Description

US-1

Accessibility

Stimulus: A colorblind user accesses the settings menu and toggles the "Colorblind mode".
Response: The system immediately updates the color palette across the entire UI (e.g., changing player colors to Orange and White/Blue) without requiring a page reload.

US-2

Internationalization

Stimulus: A user selects a different language (e.g., Turkish or English) from the language dialog.
Response: The system applies the selected i18n translation strings instantaneously to all text elements in the interface using the Translation Provider.

==== Performance Scenarios

ID Quality Attribute Scenario Description

PE-1

AI Response Time

Stimulus: A player confirms their move in a match against the bot.
Response: The AI algorithm calculates the counter-move and updates the board state in under 3 seconds to keep the gameplay fluid and engaging.

PE-2

UI Responsiveness

Stimulus: A user navigates from the Main Menu to the Profile Overlay or Game Preview.
Response: The modal opens smoothly and renders the hexagonal grid or user data within 500 milliseconds.

==== Security Scenarios

ID Quality Attribute Scenario Description

SE-1

Data Privacy

Stimulus: A new user registers using the Sign-Up form.
Response: The backend uses the bcrypt library to securely hash the password before storing it in the PostgreSQL database, ensuring plain-text passwords are never saved.

SE-2

Input Integrity

Stimulus: A user attempts to register with an email or username that already exists.
Response: The backend database and API layer reject the insertion, returning a clear validation error to prevent duplicate accounts.

==== Maintainability & Testability Scenarios

ID Quality Attribute Scenario Description

MT-1

Automated Testing

Stimulus: A developer modifies the game logic or user registration workflow.
Response: Automated End-to-End (E2E) tests using Playwright and Cucumber spin up isolated Docker databases, execute user flows, and report success or failure, preventing regressions.

MT-2

Architecture

Stimulus: A developer needs to add a new feature to fetch user match history.
Response: The developer can cleanly implement this by adding a specific Query in the Data Access layer (Repository) and validating logic in the Domain layer (Service), adhering to the established layered architecture.

== Risks and Technical Debt

Content

A list of identified technical risks and technical debt, ordered by priority.

=== Risk Mitigation Table

Risk Proactive Measure Contingent Measure

Team Attrition

Maintain clean code using ESLint/Prettier and updated arc42 documentation so any member can take over.

Redistribute tasks among remaining members; focus on MVP features (Game & Login).

Rust Learning Curve

Develop small Proof-of-Concepts (POCs) for YEN parsing and AI logic early in the development cycle.

Use simpler AI strategies (e.g., Random Move) or move logic to TypeScript if Rust becomes a bottleneck.

Integration Failures (TS <→ Rust)

Define a shared JSON Schema for YEN validation between the Frontend and the Bot runner.

Hold emergency integration meetings to align data formats and parsers.

Deployment Failures

Configure and test CI/CD pipelines (GitHub Actions) early to ensure Docker images build correctly.

Perform manual deployments to alternative providers (e.g., Fly.io or Render) or local staging.

Scalability of AI

Optimize Bot algorithms (Minimax/Alpha-Beta) to ensure they don’t exceed the 2-second timeout.

Implement a "Time-Out" safeguard that forces the bot to play a safe heuristic move if time expires.

External API Dependency

Abstract the User Management API calls behind a Service Layer to isolate changes.

Create Mock Providers to allow offline development if the backend API is down.

=== Technical Debt

  • AI Complexity & Heuristics: Due to time constraints, the initial version of the bot uses basic heuristics for board evaluation. Implementing more advanced search algorithms (like Monte Carlo Tree Search) is documented as technical debt for future iterations.

  • Test Coverage (UI & Edge Cases): While core logic is tested, reaching 100% coverage for complex UI interactions and rare network failure edge cases is a pending goal. We prioritized "Happy Path" E2E tests using Playwright over exhaustive unit testing of presentational components.

  • YEN Robustness: The current parser assumes valid JSON input for bot moves. Comprehensive validation and "Sanitizing" for malformed or malicious JSON from external bots is yet to be fully implemented, representing a security and stability debt.

  • Database Migration Management: The current setup relies on manual schema adjustments or basic scripts. Implementing a robust migration tool (like Flyway or Liquibase) to manage PostgreSQL versioning is considered debt to be addressed as the data model grows.

  • Code Duplication in Translation Files: Some i18n keys are duplicated across similar modals (e.g., "Cancel" buttons). A refactor to centralize common UI strings is planned to improve maintenance.

== Glossary

Term Definition

ADR

Architectural Decision Record. A short text document that captures a significant architecture decision, its context, and its consequences.

API

Application Programming Interface. The set of protocols and definitions used by the Webapp to communicate with the Users and Gamey microservices.

CI/CD

Continuous Integration / Continuous Deployment. The automated process of integrating code changes and deploying them to the production environment via GitHub Actions.

Colorblind Mode

An accessibility feature that adjusts the game’s color palette to ensure high contrast for users with color vision deficiencies.

Docker

A containerization platform used to package and run the system components (Webapp, Users, Gamey, DB) in isolated environments.

Game Y

The specific hexagonal strategic board game that serves as the core domain for the YOVI suite.

Gamey Engine

The high-performance microservice developed in Rust responsible for game rules, move validation, and AI calculations.

Hexagonal Board

The game’s playing surface, composed of hexagonal cells as required by the Game Y specification.

Hint

A Quality of Life (QoL) feature where the Gamey Engine suggests the optimal next move to the player.

i18n

Internationalization. The process of designing the software so it can be adapted to various languages (e.g., Asturian, Turkish, English) without engineering changes.

JSON

JavaScript Object Notation. The lightweight data-interchange format used for all internal and external communication.

Micrati

The organization acting as the primary stakeholder and client for the development of the YOVI system.

Minimax

A decision-making algorithm used by the AI to determine the best move by minimizing the possible loss for a worst-case scenario.

Playwright

A testing framework used for End-to-End (E2E) testing to simulate user behavior in the browser.

PostgreSQL

The relational database management system used to store user profiles, match history, and leaderboard statistics.

Rust

A systems programming language focused on safety and performance, used for the core Gamey logic.

TypeScript

A strongly typed superscript of JavaScript used for the Frontend (React) and the Users Service (Node.js).

Users Service

The Node.js microservice dedicated to managing user authentication, registration, and persistent statistics.

Webapp

The React-based frontend that provides the User Interface and exposes the REST API for external bots.

Winrate

The primary metric used for the ranking system, calculated as the ratio of games won to total games played.

YEN Notation

The specific JSON-based communication standard defined for this project to exchange board states and moves between services.