- Updated documentation to include OSM Track Harvesting Policy with details on railway types, service filters, usage filters, and geometry guardrails. - Introduced a new script `init_demo_db.py` to automate the database setup process, including environment checks, running migrations, and loading OSM fixtures for demo data.
7.3 KiB
7.3 KiB
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:
useNetworkSnapshotorchestrates 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.2.4 OSM Track Harvesting Policy
- Railway Types: Importer requests
rail,light_rail,subway,tram,narrow_gauge, plusconstructionanddisusedvariants to capture build-state metadata. - Service Filters:
servicetags such asyard,siding,spur,crossover,industrial, ormilitaryare excluded to focus on mainline traffic. - Usage Filters: Ways flagged with
usage=militaryorusage=tourismare skipped; unspecified usage defaults to accepted. - Geometry Guardrails: Segments shorter than 75 meters are discarded and track endpoints must snap to an existing station within 350 meters or the segment is ignored during loading.
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, andtrain_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
POINTgeometry (SRID 4326) to support spatial queries; a GiST index accelerates proximity searches. - Tracks: Models line segments between stations using
LINESTRINGgeometry 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
postgisandpgcryptoextensions; 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:
.envconfiguration exposesDATABASE_URL,TEST_DATABASE_URL, andALEMBIC_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