18 KiB
SOR.Collection 12-Factor Refactor Plan
Date: 2026-06-10
Scope reviewed:
Server/src/SOR.Collection- Collection persistence in
Server/src/SOR.Database/Contexts/CollectionDbContext.cs - Collection entities and migrations under
Server/src/SOR.Database - Collection wiring in
Server/src/SOR.Host - Cross-module dependencies on
SOR.Catalog,SOR.Bazaar, andSOR.Auth/Identity data
Reference: https://12factor.net/
Executive Summary
SOR.Collection is a service module registered by SOR.Host when ENABLED_SERVICES includes collection. It owns player card inventory, player cosmetics, deck CRUD, deck validation, starter deck selection, and card salvage for Origin Points. It reads catalog card definitions, reads Bazaar starter decks and listings, and mutates Identity account balances/state for starter selection and salvage.
The service already has useful 12-Factor foundations:
- It is enabled through host process formation.
- Player inventory and deck state are durable in PostgreSQL through
CollectionDbContext. - Deck-card uniqueness is enforced at the database level.
- Player-cosmetic uniqueness is enforced at the database level.
- Cross-schema dependencies are explicit through registered DbContexts.
- Salvage uses a shared Postgres transaction for card deletion and Origin Point credit.
- Public message contracts are centralized in
CollectionMessages.cs.
The main gaps are structural and operational:
- Message handlers contain transport handling, validation, business rules, EF queries, mutations, transaction handling, deck validation, DTO mapping, and response mapping.
- Deck rules are compile-time constants instead of typed, validated config.
- Starter deck selection mutates collection and identity state through multiple saves without a single shared transaction boundary.
- Salvage has a transaction boundary, but its guards are checked before the transaction and can race with marketplace listing/deck changes.
- Mutating commands do not have a visible idempotency model for client retry or message redelivery.
- Deck validation lives in
CollectionHandlerBaseand mixes rule evaluation, catalog reads, warnings, persistence, and timestamps. - Collection ownership, deck count, starter selection, and salvage invariants are mostly application-level checks.
- There is no visible readiness check for Collection, Catalog, Bazaar, or Identity database dependencies.
- There is no visible
Server/tests/SOR.Collection.Testsproject.
The plan is to keep SOR.Collection as the player inventory and deck module, but split handlers into thin transport adapters backed by inventory, deck, starter-deck, salvage, validation, and repository services with typed rules, transaction safety, idempotency, observability, and dependency-aware readiness.
Current Structure Observations
Strong Foundations
AddCollectionServiceregisters collection handlers from one composition point.CollectionDbContextuses a dedicatedcollectionschema.PlayerCardrows represent individual physical card copies.DeckCardrows aggregate card definition quantities per deck.DeckCardenforces one row per card definition per deck.PlayerCosmeticenforces one row per account/cosmetic pair.DeckRulescentralizes current rule constants.CollectionHandlerBasecentralizes definition loading, art URL lookup, owned-count lookup, and deck validity refresh.- Starter deck cards are granted as non-tradeable.
- SpiritToken cards are intentionally excluded from player collections.
- Salvage checks ownership, tradeability, active marketplace listing, deck copy requirements, and catalog value before crediting Origin Points.
Main Problems
- Handler classes are the application layer.
CollectionSelectStarterDeckHandlerwrites player cards, deck rows, deck cards, deck validity, andAccount.StarterDeckSelectedAtin separate operations.CollectionSalvageCardHandlerchecks active listings and deck usage before starting its transaction.- Deck creation and clone enforce
MaxDecksPerPlayerwith a pre-count but no database-backed cap or transactional claim. - Deck add/remove/set-arch-spirit operations rely on post-mutation validity refresh instead of a dedicated deck rule service.
CollectionAddCardHandlerhas a commented-out Tier-1 ArchSpirit rejection, which makes the intended deck-building rule unclear.CollectionGetCardsHandlerclamps page size to100directly instead of usingDeckRulesor options.- Catalog filters are resolved by loading matching definition IDs, which can become expensive as the catalog grows.
- Starter deck data lives in Bazaar tables, so Collection has a direct read dependency on Bazaar for onboarding.
- Economy behavior for salvage is static and not externally configurable or auditable.
- There is no central inventory ledger/audit trail for grants, salvage, deck changes, or starter selection.
Target Collection Shape
Keep SOR.Collection as the inventory/deck service module, but split it into focused layers:
Server/src/SOR.Collection/
Configuration/
CollectionOptions.cs
DeckRulesOptions.cs
InventoryOptions.cs
SalvageOptions.cs
StarterDeckOptions.cs
CollectionOptionsValidator.cs
Bootstrap/
CollectionRegistration.cs
CollectionHandlersRegistration.cs
CollectionHealthChecks.cs
Contracts/
CollectionMessages.cs
CollectionErrors.cs
Application/
Inventory/
InventoryQueryService.cs
InventoryGrantService.cs
InventoryLedgerService.cs
Decks/
DeckCommandService.cs
DeckQueryService.cs
DeckCloneService.cs
DeckValidationService.cs
DeckRuleSet.cs
StarterDecks/
StarterDeckQueryService.cs
StarterDeckSelectionService.cs
Salvage/
SalvageService.cs
SalvageValueService.cs
Persistence/
ICollectionRepository.cs
ICatalogCardReader.cs
IStarterDeckReader.cs
IMarketplaceListingReader.cs
IOriginPointLedger.cs
ICollectionUnitOfWork.cs
CollectionTransactionRunner.cs
Idempotency/
ICollectionCommandIdempotencyStore.cs
Mapping/
CollectionDtoMapper.cs
Handlers/
CollectionGetCardsHandler.cs
CollectionCreateDeckHandler.cs
...
Desired handler shape:
- Deserialize request.
- Read authenticated account ID.
- Call one application service.
- Map domain result to
ServerMessage. - Avoid direct EF queries in handlers.
12-Factor Gap Map
1. Codebase
Mostly aligned. SOR.Collection is one module in the server codebase, but workflow logic is concentrated in handlers and helper base classes.
Plan:
- Keep one Collection module.
- Extract inventory, deck, starter deck, and salvage workflows into application services.
- Keep handlers as transport adapters.
- Add focused tests for application services and rule evaluation.
2. Dependencies
Partially aligned. Dependencies are explicit through project references and DbContext registration, but handlers depend directly on all persistence concerns.
Plan:
- Introduce repository/read-service abstractions for collection, catalog, starter decks, marketplace listings, and identity balances.
- Introduce
IOriginPointLedgershared with Bazaar or aligned with Bazaar’s ledger model. - Isolate cross-context transactions in a
CollectionTransactionRunner. - Keep catalog and bazaar dependencies read-only unless a workflow explicitly needs writes.
3. Config
Weakly aligned. Deck and collection rules are static constants.
Plan:
- Add typed
CollectionOptions. - Move deck sizes, copy limits, max decks, page sizes, starter-selection behavior, and salvage policy into options.
- Validate options at startup.
- Preserve current values as defaults.
Candidate config shape:
{
"Collection": {
"DeckRules": {
"MinDeckSize": 20,
"MaxDeckSize": 120,
"MaxCopiesPerCard": 99,
"MaxDecksPerPlayer": 20,
"AllowTierOneArchSpiritInCardList": true
},
"Inventory": {
"DefaultPageSize": 50,
"MaxPageSize": 100
},
"StarterDecks": {
"SelectionEnabled": true,
"RequireSingleSelection": true
},
"Salvage": {
"Enabled": true,
"FoilMultiplier": 2,
"RequireTradeable": true,
"BlockListedCards": true
}
}
}
4. Backing Services
Partially aligned. Collection relies on Postgres schemas for collection, catalog, bazaar, and identity data.
Plan:
- Treat Collection, Catalog, Bazaar, and Identity databases as attached backing services for active collection workflows.
- Add readiness checks for each required schema by enabled feature.
- Document that cross-context transactions require those contexts to point at the same Postgres database/connection target.
- If schemas move to separate databases later, introduce an outbox/saga pattern for cross-service mutations.
5. Build, Release, Run
Mostly aligned. Collection has no build-time assets and does not run migrations itself.
Plan:
- Keep schema migrations outside normal runtime startup.
- Treat starter deck definitions and salvage value policy as release-managed data/config.
- Add release checks for starter decks, ArchSpirit references, SpiritToken exclusions, and deck rule compatibility.
6. Processes
Mostly aligned. Collection is a request/response service module with no hosted worker today.
Plan:
- Keep runtime request handlers in the
collectionrole. - Add optional
collection-jobsrole only for future backfills, deck revalidation, inventory audits, and migration repair jobs. - Keep jobs separate from normal request workers.
7. Port Binding
Aligned through SOR.Host. Collection does not bind ports directly.
Plan:
- Keep port binding in Host/Gateway.
- Expose Collection readiness through host health checks.
- Do not add a Collection-specific listener.
8. Concurrency
Partially aligned. Some uniqueness constraints exist, but high-value flows rely on pre-checks.
Plan:
- Use transactional/conditional updates for starter deck selection.
- Move all starter selection writes into one transaction.
- Re-check salvage listing/deck/card ownership inside the transaction or use row locks/conditional deletes.
- Add idempotency for starter selection and salvage commands.
- Add retry handling for unique-constraint races and transient Postgres errors.
- Consider database constraints or serialized command handling for max deck count.
9. Disposability
Mostly aligned. Request handlers pass cancellation tokens through EF operations and there are no long-running loops.
Plan:
- Keep workflows short and cancellation-aware.
- Avoid partial writes by moving multi-context mutations into transaction runners.
- Add background jobs only with explicit cancellation and progress checkpoints.
10. Dev/Prod Parity
Partially aligned. Runtime code is consistent across environments, but starter deck data, catalog definitions, and deck rules can drift.
Plan:
- Provide local seed data for starter decks and test catalogs.
- Add validation commands for starter decks and deck rules.
- Run the same starter deck and salvage validation locally and in production-like environments.
11. Logs
Weakly aligned. There is no central structured audit/log boundary for collection mutations.
Plan:
- Add logs and metrics through application services.
- Track deck create/rename/delete/add/remove/clone, starter selection, card grants, salvage, invalid deck changes, and failed rule checks.
- Avoid logging full deck lists by default.
Suggested fields:
accountIddeckIdplayerCardIdcardDefinitionIdstarterDeckIdoriginPointsAwardedoperationerrorCodeidempotencyKey
12. Admin Processes
Partially aligned. Collection data is maintained through runtime handlers and Admin pages elsewhere, but operational jobs are not explicit.
Plan:
- Add admin/job processes for deck revalidation, inventory audit, starter deck validation, duplicate repair, and salvage policy audit.
- Add dry-run modes for repair jobs.
- Add audit views for card grants, starter selection, salvage, and deck changes.
Refactor Phases
Phase 0: Baseline Tests
Goals:
- Preserve current behavior before extraction.
Work:
- Add tests for deck create/rename/delete/clone.
- Add tests for add/remove card rules, owned-copy limits, max deck size, and copy limits.
- Add tests for ArchSpirit rules and tier-chain warnings.
- Add tests for starter deck selection.
- Add tests for salvage guards and reward calculation.
- Add tests for paged/grouped inventory queries.
Done when:
- Current collection behavior is executable and can protect refactors.
Phase 1: Typed Options
Goals:
- Move operational collection rules into validated config.
Work:
- Add
CollectionOptions,DeckRulesOptions,InventoryOptions,StarterDeckOptions, andSalvageOptions. - Replace direct constants and literal page limits with options.
- Keep
DeckRulesas a compatibility facade if needed. - Validate rule consistency at startup.
Done when:
- Deck and inventory limits can be changed without code edits.
- Current behavior is preserved by defaults.
Phase 2: Application Services and Thin Handlers
Goals:
- Make collection workflows testable without transport plumbing.
Work:
- Extract
DeckCommandService,DeckQueryService,InventoryQueryService,StarterDeckSelectionService, andSalvageService. - Extract
DeckValidationServicefromCollectionHandlerBase. - Centralize DTO mapping.
- Keep public message contracts unchanged.
Done when:
- Handlers mostly deserialize, call services, and return responses.
- Deck validation and salvage logic are independently testable.
Phase 3: Transaction Runner and Ledger
Goals:
- Make high-value collection mutations atomic and auditable.
Work:
- Add
CollectionTransactionRunnerfor collection/identity transactions. - Add or share
IOriginPointLedgerfor salvage credits. - Route starter selection, salvage, and any future grants through explicit transaction workflows.
- Add inventory ledger events for grants and destroys.
Done when:
- Starter selection cannot partially grant cards without stamping the account, or stamp the account without granting cards.
- Salvage and Origin Point credits share one audited code path.
Phase 4: Idempotency
Goals:
- Make retry/redelivery safe for high-value commands.
Work:
- Add idempotency support for starter selection, salvage, and deck mutations where duplicate application would be harmful.
- Store command result snapshots or durable command records.
- Return the original result on replay.
Done when:
- Client retry cannot grant starter cards twice, salvage twice, or duplicate deck mutations unexpectedly.
Phase 5: Concurrency and Invariant Hardening
Goals:
- Protect inventory/deck invariants under concurrent requests.
Work:
- Re-check salvage eligibility inside the transaction.
- Use conditional delete or row lock for the player card being salvaged.
- Protect max deck count under concurrent create/clone.
- Decide and enforce the Tier-1 ArchSpirit card-list rule.
- Add database constraints or repair jobs for invariants that cannot be encoded directly.
Done when:
- Concurrent starter selection, salvage, deck create, and deck edit tests pass.
- Key invariants do not rely only on optimistic pre-checks.
Phase 6: Starter Deck Data Boundary
Goals:
- Make onboarding data explicit and validated.
Work:
- Add
StarterDeckQueryServiceover Bazaar starter deck data. - Validate starter decks reference published non-token cards and a valid ArchSpirit.
- Add a release/admin validation command for starter decks.
- Document why starter decks live in Bazaar data or move starter deck read models closer to Collection if needed.
Done when:
- Bad starter deck data is caught before players can select it.
- Collection’s dependency on Bazaar starter deck tables is explicit.
Phase 7: Inventory and Deck Audit
Goals:
- Make player inventory mutations explainable.
Work:
- Add audit records for card grants, starter selection, salvage, deck changes, and repair jobs.
- Add admin/reporting queries for a player’s inventory history.
- Add metrics for deck mutations, validation failures, starter selections, salvage attempts, and salvage credits.
Done when:
- Operators can answer why a card or deck exists, changed, or was destroyed.
Phase 8: Readiness and Operations
Goals:
- Make Collection operationally visible.
Work:
- Add readiness checks for Collection, Catalog, Bazaar starter-deck reads, and Identity balance writes.
- Add runbooks for failed starter selection, salvage disputes, deck invalidation, and data repair.
- Add optional deck revalidation and inventory audit jobs.
Done when:
- Collection’s dependencies and failure modes are observable before players hit broken workflows.
Suggested Work Order
- Add baseline tests for deck rules, starter selection, and salvage.
- Add typed options with current defaults.
- Extract deck validation into
DeckValidationService. - Extract application services behind existing handlers.
- Add a transaction runner and Origin Point ledger path.
- Make starter selection atomic.
- Harden salvage concurrency and idempotency.
- Decide and enforce ArchSpirit deck-list policy.
- Add starter deck validation jobs.
- Add audit logs, metrics, readiness checks, and runbooks.
Completion Criteria
The refactor is complete when:
- Collection handlers are thin transport adapters.
- Deck, inventory, starter deck, and salvage rules are typed config.
- Deck validation is a dedicated service with tests.
- Starter selection and salvage are atomic and idempotent.
- High-value inventory changes are audited.
- Cross-schema dependencies are documented and covered by readiness checks.
- Starter deck data is validated before release.
- Concurrency tests cover starter selection, salvage, deck creation, and deck edits.
- Operators can inspect inventory mutation history and repair invalid deck/inventory states safely.
Immediate Low-Risk Next Steps
- Add
CollectionOptionswith defaults matchingDeckRules. - Add tests around
CollectionSelectStarterDeckHandlerto expose partial-write risk. - Extract
DeckValidationServicefromCollectionHandlerBasewithout changing behavior. - Add a shared transaction helper for collection/identity writes.
- Document the current assumption that Collection, Identity, Bazaar, and Catalog contexts point at the same Postgres database when shared transactions are needed.