8.7 KiB
8.7 KiB
Model/Service Architecture Implementation Plan
Overview
This document outlines the implementation plan for building a unified model/service architecture across the Paper Dynasty application, with primary focus on the Discord bot component which serves as the local cache for API data during gameplay.
Current State Analysis
PostgreSQL Models (Discord Bot)
- Location:
in_game/gameplay_models.py - Framework: SQLModel-based with ~20+ domain models
- Core Entities:
Game,Team,Player,Card,Lineup,Play,ManagerAi - Features: Complex relationships, proper foreign keys, cascading deletes
- Purpose: Local cache for API data during gameplay sessions
Existing Service Patterns
- API Layer:
api_calls.py- HTTP requests to FastAPI backend - Data Cache:
in_game/data_cache.py- Dataclass wrappers for API responses - Query Layer:
in_game/gameplay_queries.py- SQLModel query functions - Legacy DB:
db_calls_gameplay.py- Peewee-based patterns (to be deprecated)
Current Data Flow
FastAPI Database → HTTP API → Local PostgreSQL Cache → Game Logic
Proposed Architecture
Directory Structure
models/ # Domain models (refactored from gameplay_models.py)
├── base.py # Base model classes and mixins
├── game.py # Game-related models
├── player.py # Player/Card models
├── team.py # Team models
└── stats.py # Statistics models
services/ # Business logic layer
├── base.py # Base service class with common patterns
├── game_service.py # Game management operations
├── team_service.py # Team operations
├── card_service.py # Card/Player operations
└── cache_service.py # Data synchronization with API
repositories/ # Data access layer
├── base.py # Base repository with CRUD operations
├── game_repo.py # Game-specific queries
├── team_repo.py # Team-specific queries
└── player_repo.py # Player/Card queries
Implementation Phases
Phase 1: Service Layer Foundation (Weeks 1-2)
Objectives:
- Create base service/repository classes
- Extract existing
gameplay_queries.pyinto proper service modules - Establish consistent patterns for dependency injection
Tasks:
- Create
services/base.pywith common service patterns - Create
repositories/base.pywith CRUD operations - Extract game operations from
gameplay_queries.py→services/game_service.py - Extract team operations →
services/team_service.py - Extract player/card operations →
services/card_service.py - Create comprehensive unit tests for new service layer
Files to Create:
services/__init__.pyservices/base.pyservices/game_service.pyservices/team_service.pyservices/card_service.pyrepositories/__init__.pyrepositories/base.pyrepositories/game_repo.pyrepositories/team_repo.pyrepositories/player_repo.py
Success Criteria:
- All existing queries moved to appropriate services
- Service classes follow consistent patterns
- 100% test coverage for new service layer
- No breaking changes to existing cog functionality
Phase 2: Model Refactoring (Weeks 3-4)
Objectives:
- Refactor existing models with base classes
- Add proper validation and optimize relationships
- Implement model mixins for shared behavior
Tasks:
- Create
models/base.pywith base model classes - Split
gameplay_models.pyinto logical modules:models/game.py- Game, Play, GameCardsetLinkmodels/team.py- Team, Lineup, RosterLinkmodels/player.py- Player, Card, PositionRatingmodels/stats.py- BattingCard, PitchingCard, Scouting models
- Add base mixins for common fields (timestamps, soft deletes)
- Optimize database indexes and constraints
- Update all imports across the codebase
- Run full test suite to ensure no regressions
Files to Modify:
in_game/gameplay_models.py→ Split intomodels/directory- All files importing from
gameplay_models.py - Database migration files
Success Criteria:
- Models follow consistent inheritance patterns
- All relationships properly defined with optimized queries
- Database performance maintained or improved
- Zero test failures after refactoring
Phase 3: Service Integration (Weeks 5-6)
Objectives:
- Replace direct SQLModel queries in cogs with service calls
- Implement proper transaction management and error handling
- Add caching strategies at service level
Tasks:
- Refactor
cogs/gameplay.pyto use service layer - Refactor
cogs/players/modules to use services - Refactor
command_logic/logic_gameplay.py - Implement service dependency injection in cogs
- Add comprehensive error handling with proper exception types
- Implement service-level caching for frequently accessed data
- Add logging and monitoring to service operations
Files to Modify:
cogs/gameplay.pycogs/players/*.pycommand_logic/logic_gameplay.pyin_game/ai_manager.pyin_game/game_helpers.py
Success Criteria:
- No direct database access in cogs (all through services)
- Proper error handling and transaction management
- Improved performance through service-level caching
- All existing functionality preserved
Phase 4: API Synchronization & Optimization (Weeks 7-8)
Objectives:
- Build unified data sync service for API ↔ PostgreSQL cache
- Implement background sync tasks and health checks
- Add performance monitoring and optimization
Tasks:
- Create
services/cache_service.pyfor API synchronization - Implement background tasks for data freshness
- Add conflict resolution for concurrent modifications
- Create health check endpoints for data consistency
- Implement performance monitoring and alerting
- Add database connection pooling optimization
- Create data migration utilities for schema changes
Files to Create:
services/cache_service.pyservices/sync_service.pymonitoring/health_checks.pymonitoring/performance_metrics.py
Success Criteria:
- Automatic data synchronization with API
- Health monitoring and alerting in place
- Performance metrics collection
- Zero data consistency issues
Migration Strategy
Backwards Compatibility
- All changes will maintain backwards compatibility during transition
- Original
gameplay_models.pywill remain until Phase 2 completion - Gradual migration with feature flags for rollback capability
Testing Strategy
- Comprehensive unit tests for all new service classes
- Integration tests for service layer interactions
- Performance tests to ensure no regressions
- Load tests for cache synchronization under heavy gameplay
Rollback Plan
- Each phase can be independently rolled back
- Feature flags allow selective activation of new architecture
- Database migrations are reversible
- Monitoring alerts for performance degradation
Benefits
Separation of Concerns
- Clear boundaries between models, business logic, and data access
- Easier to reason about and maintain code
- Reduced coupling between components
Testability
- Service layer can be easily mocked and tested
- Better unit test coverage and reliability
- Faster test execution with mocked dependencies
Maintainability
- Centralized business logic and consistent patterns
- Easier onboarding for new developers
- Reduced code duplication
Performance
- Optimized queries and caching strategies
- Better database connection management
- Reduced API calls through intelligent caching
Scalability
- Easy to extend with new features and models
- Prepared for microservice architecture if needed
- Better resource utilization
Timeline
- Total Duration: 8 weeks
- Phase 1: Weeks 1-2 (Foundation)
- Phase 2: Weeks 3-4 (Model Refactoring)
- Phase 3: Weeks 5-6 (Service Integration)
- Phase 4: Weeks 7-8 (Optimization)
Risk Mitigation
Technical Risks
- Database Performance: Continuous monitoring during migration
- Data Consistency: Comprehensive testing and validation
- Breaking Changes: Gradual migration with backwards compatibility
Timeline Risks
- Scope Creep: Clear phase boundaries and success criteria
- Testing Overhead: Automated testing pipeline
- Integration Issues: Early integration testing and validation
Success Metrics
- Zero downtime during migration
- Performance maintained or improved (< 5% regression acceptable)
- 100% test coverage for new architecture
- Reduced average development time for new features by 30%
- Improved code maintainability score (SonarQube metrics)
This plan serves as the foundation for modernizing the Paper Dynasty architecture while maintaining stability and performance during the transition.