Files
sor/SOR.Game.12FactorPlan.md
2026-07-02 13:09:05 -04:00

19 KiB

SOR Game 12-Factor Refactor Plan

Date: 2026-06-08

Scope reviewed:

  • Server/src/SOR.Game
  • Runtime wiring in Server/src/SOR.Host
  • Shared infrastructure in Server/src/SOR.Database, SOR.Shared, networking abstractions, Dockerfile, and server architecture docs

Reference: https://12factor.net/

Executive Summary

SOR.Game already has a useful service-module boundary and dependency injection entry point, and the host already supports process-level service selection through ENABLED_SERVICES. Those are strong foundations for a 12-Factor-compatible backend.

The main issues are inside the game module shape and runtime behavior:

  • GameEngine.cs, AbilitySystem.cs, GameMessages.cs, and GameHandlerBase.cs carry too many responsibilities.
  • Several handlers contain orchestration, persistence, serialization, and push logic that should live behind services.
  • Some runtime state is process-local (VoteSessionService, RuleSuggestionService, GameActivityRegistry) or exposed through static singleton references.
  • Startup cleanup is embedded in app boot instead of being available as an explicit one-off operational process.
  • Config is mostly environment-ready, but defaults and service-specific options are not consistently typed or validated.
  • Health checks are liveness-only and do not yet reflect Redis, NATS, or database readiness.
  • There is no visible test project under Server/tests, even though the architecture doc expects service tests.

The plan below breaks the work into phases that improve structure first, then operational conformance.

Current Structure Observations

Strong Foundations

  • One repository contains the server codebase and service modules.
  • Directory.Packages.props centralizes NuGet versions.
  • Directory.Build.props sets deterministic builds, nullable references, warnings as errors, and common target framework.
  • SOR.Host is the single deployable runtime and uses ENABLED_SERVICES to select modules.
  • SOR.Game registers itself through AddGameService.
  • Redis, NATS, EF Core, and client push are represented as injected infrastructure.
  • Dockerfile.host uses a build stage and runtime stage, exposes port 8080, and runs as a non-root user.
  • Game spectators are already backed by Redis, which supports horizontal scale better than in-process memory.

Main Structural Problems

  • GameEngine.cs is a large static rules engine mixing serialization, initialization, draw/play/move/attack/sacrifice/end-turn flow, DTO projection, deck validation, ELO calculation, and helper parsing.
  • AbilitySystem.cs is extremely large and likely combines parsing, validation, target resolution, execution, triggers, animations, pending prompts, and state mutation.
  • GameHandlerBase.cs contains static helpers for pushing state, finalizing games, spectator handling, activity broadcasting, and ranking updates.
  • Handler classes often directly use EF Core, JSON serialization, push delivery, and game state mutation instead of delegating to focused application services.
  • GameMessages.cs is a large message contract file; DTOs and request/response contracts are not grouped by workflow.
  • Static singleton references (GameActivityRegistry.Instance, SpectatorRegistryService.Instance) make the code harder to test and reduce process-model clarity.
  • VoteSessionService, RuleSuggestionService, and GameActivityRegistry are process-local. That means behavior can diverge across pods if game traffic is handled by more than one game process.
  • GameStartupCleanupService performs operational repair during process startup. The behavior is useful, but 12-Factor admin-process guidance points toward a one-off task that can be run independently from normal web/process boot.

Target Architecture

Keep SOR.Game as the service module, but make its internal shape closer to this:

Server/src/SOR.Game/
  ServiceRegistration.cs
  Configuration/
    GameOptions.cs
    GameTimerOptions.cs
    GameCleanupOptions.cs
  Contracts/
    Commands/
    Responses/
    Pushes/
    Dtos/
  Application/
    Lobbies/
    Sessions/
    Turns/
    Actions/
    Spectating/
    Activity/
    Ranking/
  Domain/
    State/
    Rules/
    Abilities/
    Combat/
    Board/
    Randomness/
  Persistence/
    IGameSessionRepository.cs
    ICustomLobbyRepository.cs
    IGamePresetRepository.cs
    EfGameSessionRepository.cs
    EfCustomLobbyRepository.cs
    EfGamePresetRepository.cs
  RuntimeState/
    IVoteSessionStore.cs
    RedisVoteSessionStore.cs
    IRuleSuggestionStore.cs
    RedisRuleSuggestionStore.cs
    IGameActivitySubscriptionStore.cs
    RedisGameActivitySubscriptionStore.cs
  Operations/
    GameStartupCleanupJob.cs
    GameSessionRepairJob.cs
  Handlers/
    GameReadyHandler.cs
    ...

The goal is not to add layers for their own sake. The goal is to make handlers thin, make game rules testable without the host, and move horizontally shared runtime state into attached services.

12-Factor Gap Map

I. Codebase

Status: Mostly aligned.

Current state:

  • One repo contains server projects.
  • Deploy behavior is selected by config (ENABLED_SERVICES), not by code forks.

Plan:

  • Keep one repo and one SOR.Host deployable for now.
  • Document each deploy type as a process formation: gateway, game, ai, auth, content, all for local development.
  • Add a clear ownership map for SOR.Game subdomains after the refactor.

II. Dependencies

Status: Mostly aligned.

Current state:

  • NuGet versions are centrally declared.
  • Docker restore is explicit.

Plan:

  • Keep central package management.
  • Add a dependency audit task for game: identify direct dependencies from SOR.Game to concrete infrastructure and move them behind interfaces where they are not pure domain concerns.
  • Avoid adding new cross-module references from SOR.Game; prefer SOR.Networking.Abstractions, SOR.Shared, and explicit service contracts.

III. Config

Status: Partially aligned.

Current state:

  • Connection strings and service URLs can be overridden via environment variables.
  • appsettings.json contains local defaults and placeholder secrets.
  • Game-specific constants are scattered in services and handlers.

Plan:

  • Add typed options for game configuration:
    • Game:Timers
    • Game:Cleanup
    • Game:RulesDefaults
    • Game:RuntimeState
    • Game:Activity
  • Validate options at startup with ValidateOnStart.
  • Move hardcoded operational values into config where appropriate:
    • startup cleanup stale threshold
    • spectator TTL
    • inactivity thresholds
    • turn timer settings
    • activity subscription TTL
  • Keep secrets and production values out of committed JSON; use environment variables or secret providers.

IV. Backing Services

Status: Partially aligned.

Current state:

  • PostgreSQL, Redis, NATS, CDN, and Keycloak are treated as configurable resources.
  • Some game runtime state is still in memory.

Plan:

  • Replace process-local runtime state with Redis-backed stores where behavior must survive pod changes:
    • preset votes
    • rule suggestions
    • game activity subscribers
  • Keep only truly per-process concerns in memory.
  • Define Redis keys in SOR.Shared.Redis.RedisKeys.
  • Define NATS subjects in SOR.Shared.Nats.NatsSubjects.
  • Add readiness checks for required attached resources per enabled service.

V. Build, Release, Run

Status: Mostly aligned, with release gaps.

Current state:

  • Docker build and runtime stages are separate.
  • Runtime config is injected at run time.
  • Database migrations are present, but operational application of migrations is not clearly separated from runtime.

Plan:

  • Preserve Docker build/release separation.
  • Define a release checklist:
    • restore/build/test
    • publish container
    • run migrations as a one-off process
    • start runtime process formation
  • Avoid doing schema migration or repair work as implicit web process startup behavior.

VI. Processes

Status: Needs work.

Current state:

  • Game process can run independently via ENABLED_SERVICES=game.
  • Some mutable state is process-local or static.

Plan:

  • Make game handlers and domain logic stateless between requests.
  • Move shared ephemeral state into Redis.
  • Remove static service lookups by converting static helper flows into injected services.
  • Keep game state persistence in PostgreSQL, with Redis only for fast ephemeral coordination and push fanout.

VII. Port Binding

Status: Mostly aligned.

Current state:

  • Host binds via ASP.NET Core/Kestrel.
  • Docker exposes 8080.
  • Auth gRPC loopback binding is configured when co-located.

Plan:

  • Keep HTTP/WebSocket port binding in SOR.Host.
  • Ensure process-specific deploys have clear ports and health endpoints.
  • Avoid hidden runtime dependencies on external web servers.

VIII. Concurrency

Status: Partially aligned.

Current state:

  • Service selection supports multiple process types.
  • NATS and Redis are available for cross-process coordination.
  • In-process vote/suggestion/activity state makes multi-pod game scaling risky.

Plan:

  • Define process types explicitly:
    • web/gateway
    • game-worker
    • ai-worker
    • matchmaking-worker
    • admin
    • maintenance
  • Add a concurrency model for game sessions:
    • one command per session at a time
    • optimistic concurrency or distributed lock for session state mutation
    • idempotent command handling where clients may retry
  • Move timers and inactivity monitors to a model that can run safely with multiple game workers.

IX. Disposability

Status: Partially aligned.

Current state:

  • Hosted services use ASP.NET Core lifetime hooks.
  • Startup cleanup handles some previous-process failure modes.
  • Graceful shutdown behavior for game timers and in-flight game commands is not clearly isolated.

Plan:

  • Ensure hosted services honor cancellation tokens consistently.
  • Make session mutation operations transactionally safe so termination between state save and finalize can be repaired.
  • Move cleanup/repair into idempotent jobs callable as admin processes.
  • Keep startup fast; avoid large database scans during normal app boot.

X. Dev/Prod Parity

Status: Partially aligned.

Current state:

  • Local defaults exist for Redis, NATS, PostgreSQL, Keycloak, CDN, and WebSocket settings.
  • ENABLED_SERVICES=all is convenient for development but differs from scaled production process formation.

Plan:

  • Add a local compose/dev profile that runs Redis, NATS, PostgreSQL, and host process formations similarly to production.
  • Document local development modes:
    • single-process all
    • production-like split process formation
  • Keep config names identical across dev/staging/prod; only values should differ.

XI. Logs

Status: Partially aligned.

Current state:

  • Serilog writes to console, which is correct for event streams.
  • GameEngine.Attack still writes directly with Console.WriteLine.
  • Ability logging uses a static logger initializer.

Plan:

  • Replace direct console writes with injected or passed logging abstractions.
  • Remove static logger initialization from domain code over time.
  • Keep all logs structured.
  • Audit noisy Debug logs, especially ability/game action logs, so production can tune volume through config.

XII. Admin Processes

Status: Needs work.

Current state:

  • SOR.Tools exists and can be the home for one-off tasks.
  • GameStartupCleanupService does repair work during process startup.
  • EF migrations exist but the production execution path is not fully documented here.

Plan:

  • Move game cleanup/repair operations into explicit one-off tasks under SOR.Tools or a dedicated SOR.Operations project.
  • Add commands:
    • game cleanup-stale-initializing
    • game repair-ghost-active
    • db migrate --context GameDbContext
    • game reconcile-session --session-id ...
  • Keep runtime startup focused on starting the service, not performing maintenance.

Refactor Phases

Phase 0: Baseline and Safety Net

Deliverables:

  • Add Server/tests/SOR.Game.Tests.
  • Add unit tests around current behavior before moving code:
    • deck validation
    • turn-limit winner calculation
    • ELO delta calculation
    • board generation edge cases
    • attack/sacrifice/end-turn golden scenarios
    • ability trigger and pending-prompt scenarios
  • Add serialization round-trip tests for GameState and key game DTOs.
  • Add a small integration test harness for handler-to-DbContext flows using test configuration.

Acceptance:

  • Tests cover the high-risk behaviors before large file movement.
  • No behavior changes are required in this phase.

Phase 1: Split Contracts and DTOs

Deliverables:

  • Split GameMessages.cs into workflow-focused files under Contracts/.
  • Keep public type names stable to avoid client or handler churn.
  • Group by domain:
    • session messages
    • lobby messages
    • action messages
    • ability prompt messages
    • spectator messages
    • activity messages
    • ranking/outcome messages

Acceptance:

  • Build passes.
  • Existing message type names and serialized shapes remain compatible.

Phase 2: Introduce Application Services

Deliverables:

  • Create focused application services:
    • GameSessionService
    • GameLobbyService
    • GameActionService
    • GameStatePushService
    • GameFinalizationService
    • GameRankingService
    • GameActivityService
  • Move static helper logic out of GameHandlerBase.
  • Handlers become thin command adapters:
    • parse request
    • call application service
    • return response

Acceptance:

  • Handler classes no longer directly coordinate game finalization, ranking updates, spectator lookup, and state fanout.
  • Static singleton service references are removed from new paths.

Phase 3: Introduce Persistence Interfaces

Deliverables:

  • Add repositories for game persistence:
    • sessions
    • lobbies
    • presets
    • board templates
    • player decks/read models needed by game start
  • Centralize JSON field serialization/deserialization for lobby/session extra-player data and rules snapshots.
  • Keep EF Core implementations internal.

Acceptance:

  • Application services can be unit tested without EF Core.
  • Repeated JSON option setup and ad hoc parsing are reduced.

Phase 4: Split Domain Rules

Deliverables:

  • Split GameEngine into smaller pure domain components:
    • GameStateSerializer
    • GameInitializer
    • DeckValidator
    • TurnService
    • CardPlayRules
    • MovementRules
    • CombatResolver
    • GameOutcomeResolver
    • EloCalculator
    • GameStateProjector
  • Introduce an injectable randomness abstraction for shuffling and random tile selection.
  • Keep pure rule methods free of EF Core, Redis, NATS, client push, and host dependencies.

Acceptance:

  • Domain classes can be tested directly.
  • Game command behavior remains compatible with current persisted GameState JSON.

Phase 5: Split Ability System

Deliverables:

  • Split AbilitySystem by responsibility:
    • model parsing and polymorphic conversion
    • trigger matching
    • condition evaluation
    • target resolution
    • cost resolution
    • effect execution
    • pending prompt creation
    • animation/event projection
  • Create golden tests for representative ability cards before and after the split.

Acceptance:

  • Ability behavior remains compatible.
  • New ability logic can be changed without editing one giant file.

Phase 6: Externalize Runtime State

Deliverables:

  • Replace process-local stores with interfaces:
    • IVoteSessionStore
    • IRuleSuggestionStore
    • IGameActivitySubscriptionStore
  • Implement Redis-backed stores with TTLs.
  • Keep in-memory implementations only for tests or single-process local development if needed.

Acceptance:

  • Multiple game pods can observe the same vote/suggestion/activity state.
  • Runtime state expires without requiring process cleanup.

Phase 7: Operational Jobs and Admin Processes

Deliverables:

  • Move startup cleanup logic into reusable job classes.
  • Add one-off commands in SOR.Tools:
    • cleanup stale initializing sessions
    • repair ghost active sessions
    • migrate database contexts
  • Make GameStartupCleanupService optional via config, then phase it down once operational jobs are in place.

Acceptance:

  • Maintenance tasks can be run independently of normal service startup.
  • Jobs are idempotent and safe to retry.

Phase 8: Config, Health, and Release Hardening

Deliverables:

  • Add typed options and startup validation.
  • Add per-service health checks:
    • Redis
    • NATS
    • relevant database contexts
    • optional external services per enabled module
  • Define readiness vs liveness behavior.
  • Document process formations and release steps.

Acceptance:

  • A missing required config value fails fast.
  • /health remains cheap liveness.
  • Readiness endpoint reflects backing service availability.

Suggested Milestone Order

  1. Create test project and golden tests for existing game behavior.
  2. Split GameMessages.cs into contract groups.
  3. Extract push/finalization/ranking from GameHandlerBase.
  4. Introduce application services and repositories.
  5. Split GameEngine.
  6. Split AbilitySystem.
  7. Redis-back runtime state currently held in singleton dictionaries.
  8. Move startup cleanup into one-off admin jobs.
  9. Add typed config, validation, and readiness checks.
  10. Update architecture docs after implementation stabilizes.

Risk Register

Risk Why It Matters Mitigation
Ability regressions AbilitySystem is large and likely encodes many card-specific edge cases. Golden tests before splitting, small mechanical moves first.
Game state compatibility Persisted StateJson must keep loading existing active sessions. Serialization round-trip tests and version-tolerant DTO changes.
Multi-pod races Multiple game workers can process commands for one session. Add per-session command serialization or optimistic concurrency.
In-memory vote/suggestion loss Current process-local state disappears on restart or cross-pod routing. Move to Redis with TTL.
Startup repair side effects Large cleanup during app boot can slow or destabilize deploys. Move to idempotent admin jobs.
Static service references Harder testing and hidden runtime coupling. Replace with injected application services.

Definition of Done

The refactor is complete when:

  • SOR.Game handlers are thin adapters.
  • Core game and ability rules are testable without ASP.NET Core, EF Core, Redis, or NATS.
  • Shared ephemeral state required for correctness is stored in Redis or another backing service.
  • Runtime startup is fast and does not rely on implicit maintenance work.
  • Maintenance tasks can be run as one-off admin processes.
  • Config values are environment-driven, typed, and validated.
  • Logs are structured event streams with no direct Console.WriteLine in game logic.
  • Health/readiness checks reflect the backing services required by the enabled process type.
  • The production process model can scale game workers without changing code.