Add unit tests for station service and enhance documentation
Some checks failed
Backend CI / lint-and-test (push) Failing after 37s

- Introduced unit tests for the station service, covering creation, updating, and archiving of stations.
- Added detailed building block view documentation outlining the architecture of the Rail Game system.
- Created runtime view documentation illustrating key user interactions and system behavior.
- Developed concepts documentation detailing domain models, architectural patterns, and security considerations.
- Updated architecture documentation to reference new detailed sections for building block and runtime views.
This commit is contained in:
2025-10-11 18:52:25 +02:00
parent 2b9877a9d3
commit 615b63ba76
18 changed files with 1662 additions and 443 deletions

130
docs/08_Concepts.md Normal file
View File

@@ -0,0 +1,130 @@
# 8. Concepts
### 8.1 Domain Concepts
#### 8.1.1 Railway Network Model
The core domain concept is the railway network, consisting of:
- **Tracks**: Linear segments connecting geographical points, stored as spatial geometries
- **Stations**: Key points on the network where trains can stop, load/unload passengers or cargo
- **Trains**: Movable entities that follow routes along tracks according to schedules
- **Schedules**: Time-based plans for train movements and operations
Railway networks are user-created and managed, built upon real-world geographical data from OpenStreetMap.
#### 8.1.2 Game Economy
Resource management drives gameplay:
- **Currency**: Earned through network operations and achievements
- **Resources**: Required for building and upgrading railway components
- **Scoring**: Based on network efficiency, passenger satisfaction, and operational success
#### 8.1.3 Simulation Engine
Dynamic simulation of train operations:
- **Route Calculation**: Pathfinding algorithms to determine optimal train routes
- **Schedule Optimization**: Balancing train frequencies with network capacity
- **Real-time Updates**: Live position tracking and status reporting
#### 8.1.4 Network Snapshot Contract
- **Shared Models**: The backend uses immutable Pydantic models with camelCase aliases that mirror TypeScript interfaces in `frontend/src/types/domain.ts`.
- **Snapshot Service**: Until persistence exists, a service synthesises demo stations, tracks, and trains to keep the client workflow functional.
- **Client Hook**: `useNetworkSnapshot` orchestrates fetch status (idle/loading/success/error) and pushes data into the React view layer.
### 8.2 Architectural Concepts
#### 8.2.1 Client-Server Architecture
- **Frontend**: Browser-based React SPA handling user interactions and UI rendering
- **Backend**: RESTful API server processing business logic and data operations
- **Separation of Concerns**: Clear boundaries between presentation, business logic, and data layers
#### 8.2.2 Spatial Data Handling
- **PostGIS Integration**: Extension of PostgreSQL for geographical and spatial operations
- **Coordinate Systems**: Use of standard geographical projections (e.g., WGS84)
- **Spatial Queries**: Efficient querying of railway elements within geographical bounds
#### 8.2.3 Real-time Communication
- **WebSocket Protocol**: For live updates during train simulations
- **Fallback Mechanisms**: Polling as alternative when WebSockets unavailable
- **Event-Driven Updates**: Push notifications for game state changes
### 8.3 User Interface Concepts
#### 8.3.1 Component-Based Architecture
- **React Components**: Modular, reusable UI elements
- **State Management**: Centralized state using Redux or Context API
- **Responsive Design**: Adaptive layouts for various screen sizes and devices
#### 8.3.2 Map Interaction
- **Leaflet Integration**: Interactive mapping library for geographical visualization
- **Layer Management**: Overlaying user railways on base OpenStreetMap tiles
- **Gesture Handling**: Mouse, keyboard, and touch interactions for map navigation and editing
#### 8.3.3 Game Interface Patterns
- **Toolbar**: Contextual tools for building and editing railway elements
- **Modal Dialogs**: For configuration, confirmation, and detailed information display
- **Dashboard**: Overview of user progress, resources, and network statistics
### 8.4 Security Concepts
#### 8.4.1 Authentication and Authorization
- **JWT Tokens**: Stateless authentication for API requests
- **OAuth Integration**: Support for third-party authentication providers
- **Role-Based Access**: Differentiated permissions for users and administrators
#### 8.4.2 Data Protection
- **Input Validation**: Sanitization of all user inputs to prevent injection attacks
- **HTTPS Encryption**: Secure communication between client and server
- **Data Privacy**: Compliance with privacy regulations for user data handling
### 8.5 Persistence Concepts
#### 8.5.1 Database Design
- **Schema Overview**: Core tables include `users`, `stations`, `tracks`, `trains`, and `train_schedules`, each backed by UUID primary keys and timestamp metadata for auditing.
- **Users**: Holds account metadata (`username`, `email`, `role`, hashed password) with JSON-ready preference storage and soft defaults for player roles.
- **Stations**: Stores OpenStreetMap references, station codes, and a `POINT` geometry (`SRID 4326`) to support spatial queries; a GiST index accelerates proximity searches.
- **Tracks**: Models line segments between stations using `LINESTRING` geometry plus operational attributes (length, speed limits, status, bidirectionality) and a uniqueness constraint on station pairs.
- **Trains & Schedules**: Captures rolling stock capabilities and their ordered stop plans (`sequence_index`, arrival/departure timestamps, dwell times) with cascading foreign keys for clean deletions.
- **Spatial Extensions**: Alembic migrations provision `postgis` and `pgcrypto` extensions; geometry columns use GeoAlchemy2 bindings for seamless ORM interactions.
#### 8.5.2 Data Access Patterns
- **ORM Layer**: SQLAlchemy 2.0 declarative models (see `backend/app/db/models.py`) expose typed entities that will feed repository and service layers.
- **Session Management**: A centralized engine/session factory (`backend/app/db/session.py`) pulls the database URL from environment-managed settings and keeps pooling under application control.
- **Environment Separation**: `.env` configuration exposes `DATABASE_URL`, `TEST_DATABASE_URL`, and `ALEMBIC_DATABASE_URL`, allowing the runtime, tests, and migration tooling to target different Postgres instances.
- **Schema Evolution**: Alembic configuration (`backend/alembic.ini`, `backend/migrations/`) provides repeatable migrations—the initial revision creates the PostGIS-enabled schema and GiST indexes.
- **Transaction Management**: Service-layer dependencies will acquire short-lived sessions (`SessionLocal`) ensuring explicit commit/rollback boundaries around game operations.
### 8.6 Development and Deployment Concepts
#### 8.6.1 Testing Strategy
- **Unit Testing**: Individual component and function testing
- **Integration Testing**: API endpoint and database interaction validation
- **End-to-End Testing**: Complete user workflow verification across browsers
#### 8.6.2 Deployment Pipeline
- **Containerization**: Docker for consistent environments
- **CI/CD**: Automated testing and deployment workflows
- **Static Hosting**: CDN-based delivery of frontend assets
#### 8.6.3 Performance Optimization
- **Lazy Loading**: On-demand loading of components and data
- **Caching Layers**: Redis for frequently accessed data
- **Asset Optimization**: Minification and compression of static resources