feat(arena-colosseum): playable bracket + rank-match promotion (phase 2)

Closes 4 more arena-colosseum spec shapes (6/16 → 10/16): the dual-prefix
battle URLs (colosseum_battle/* and colosseum_rank_battle/*) for both
do_matching and per-match finish, plus the bracket-end /finish + /retire
pair on /arena_colosseum.

* ColosseumProgressionService: pure-logic decisions for win-threshold
  advancement, 3008 promotion trigger, and per-round reward bundles.
  Extends ColosseumRoundsConfig with FinishRewards/RetireRewards per
  round + a top-level ChampionRewards list.
* MatchContextBuilder.BuildForColosseumAsync: lifts the registered deck
  via IDeckRepository (NOT viewer-graph) per project_ef_nav_include_pitfall.
* ArenaColosseumBattleController: dual route prefixes off one controller
  via explicit absolute [HttpPost("/...")] routes — does NOT extend
  SVSimController's [Route("[controller]")]. Same pattern as FreeBattle.
  URL-vs-IsRankMatching mismatch returns 400 with a phase-mismatch error;
  no-deck triggers the standard 3001 matchmaking-illegal state. 3008
  flips run.IsRankMatching exactly once via the progression service.
* /arena_colosseum/finish + /retire share FinishResponse (rewards +
  reward_list + colosseum_status). Champion finish appends ChampionRewards
  and surfaces colosseum_status.is_champion = true. Both delete the run
  row after granting via IInventoryTransaction.GrantAsync.
* DI: ModePolicy entries for "colosseum_battle" and "colosseum_rank_battle".
* Tests: 8 progression-service unit tests (pure logic), 5 battle-controller
  HTTP tests, 5 bracket-terminate HTTP tests, 2 full-bracket E2E walks
  (champion path + retire mid-round). Full suite: 1331/1331.
This commit is contained in:
gamer147
2026-06-13 12:32:56 -04:00
parent 110867358c
commit cbee0f9a50
16 changed files with 1436 additions and 2 deletions

View File

@@ -0,0 +1,175 @@
using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SVSim.BattleNode.Bridge;
using SVSim.Database.Repositories.Viewer;
using SVSim.EmulatedEntrypoint.Constants;
using SVSim.EmulatedEntrypoint.Matching;
using SVSim.EmulatedEntrypoint.Models.Dtos.ArenaColosseum;
using SVSim.EmulatedEntrypoint.Security;
using SVSim.EmulatedEntrypoint.Security.SteamSessionAuthentication;
using SVSim.EmulatedEntrypoint.Services;
using SVSim.EmulatedEntrypoint.Services.ArenaColosseum;
namespace SVSim.EmulatedEntrypoint.Controllers;
/// <summary>
/// Per-match URLs for the Colosseum bracket — the dual <c>colosseum_battle/*</c> +
/// <c>colosseum_rank_battle/*</c> route family. Does NOT extend <see cref="SVSimController"/>'s
/// <c>[Route("[controller]")]</c> because we need explicit absolute routes for two prefixes
/// off one controller (same pattern as <see cref="FreeBattleController"/>).
/// <para>
/// The URL is the bracket-phase signal per do-matching.md §"server-side bidirectional
/// mapping"; <see cref="ViewerArenaColosseumRun.IsRankMatching"/> flips to true once the
/// node has signalled <c>matching_state == 3008</c> on a prior <c>do_matching</c>.
/// </para>
/// </summary>
[ApiController]
[Authorize(AuthenticationSchemes = SteamAuthenticationConstants.SchemeName)]
public sealed class ArenaColosseumBattleController : ControllerBase
{
/// <summary>Per FinishTaskBase.IsEffectiveErrorCode — code 3502 ("battle already finished")
/// is tolerated as a non-error retry, parsed the same as 1.</summary>
private const int BattleAlreadyFinishedResultCode = 3502;
private readonly IMatchContextBuilder _ctxBuilder;
private readonly IMatchingResolver _resolver;
private readonly IArenaColosseumRunRepository _runs;
private readonly IColosseumProgressionService _progression;
private readonly ILogger<ArenaColosseumBattleController> _log;
public ArenaColosseumBattleController(
IMatchContextBuilder ctxBuilder,
IMatchingResolver resolver,
IArenaColosseumRunRepository runs,
IColosseumProgressionService progression,
ILogger<ArenaColosseumBattleController> log)
{
_ctxBuilder = ctxBuilder;
_resolver = resolver;
_runs = runs;
_progression = progression;
_log = log;
}
private bool TryGetViewerId(out long viewerId)
{
viewerId = 0;
var claim = User.Claims.FirstOrDefault(c => c.Type == ShadowverseClaimTypes.ViewerIdClaim)?.Value;
return claim is not null && long.TryParse(claim, out viewerId);
}
[HttpPost("/colosseum_battle/do_matching")]
public Task<IActionResult> DoMatchingPreRank(
[FromBody] ColosseumDoMatchingRequestDto req, CancellationToken ct)
=> DoMatchingInternal(isRankUrl: false, req, ct);
[HttpPost("/colosseum_rank_battle/do_matching")]
public Task<IActionResult> DoMatchingPostRank(
[FromBody] ColosseumDoMatchingRequestDto req, CancellationToken ct)
=> DoMatchingInternal(isRankUrl: true, req, ct);
[HttpPost("/colosseum_battle/finish")]
public Task<IActionResult> FinishPreRank(
[FromBody] ColosseumBattleFinishRequestDto req, CancellationToken ct)
=> FinishInternal(isRankUrl: false, req, ct);
[HttpPost("/colosseum_rank_battle/finish")]
public Task<IActionResult> FinishPostRank(
[FromBody] ColosseumBattleFinishRequestDto req, CancellationToken ct)
=> FinishInternal(isRankUrl: true, req, ct);
private async Task<IActionResult> DoMatchingInternal(
bool isRankUrl, ColosseumDoMatchingRequestDto req, CancellationToken ct)
{
if (!TryGetViewerId(out var vid)) return Unauthorized();
var run = await _runs.GetByViewerIdAsync(vid);
if (run is null)
{
return BadRequest(new { error = "arena_colosseum_no_active_run" });
}
if (isRankUrl != run.IsRankMatching)
{
return BadRequest(new
{
error = "colosseum_url_phase_mismatch",
is_rank_matching = run.IsRankMatching,
requested_rank_url = isRankUrl,
});
}
MatchContext ctx;
try
{
ctx = await _ctxBuilder.BuildForColosseumAsync(vid);
}
catch (InvalidOperationException ex)
{
_log.LogWarning(ex,
"Colosseum BuildForColosseumAsync failed for viewer {Vid}; returning 3001.", vid);
return Ok(new Models.Dtos.FreeBattle.DoMatchingResponseDto
{
MatchingState = 3001,
NodeServerUrl = "",
});
}
var mode = isRankUrl ? "colosseum_rank_battle" : "colosseum_battle";
var resolution = await _resolver.ResolveAsync(mode, new BattlePlayer(vid, ctx), ct);
// Promotion: server flips IsRankMatching once on the 3008 signal. Subsequent battle
// URLs must use the rank prefix. (Plan §"matching_state == 3008 is the promotion trigger".)
if (_progression.ShouldPromoteToRankMatching(run, resolution.MatchingState))
{
run.IsRankMatching = true;
await _runs.UpsertAsync(run);
}
return Ok(new Models.Dtos.FreeBattle.DoMatchingResponseDto
{
MatchingState = resolution.MatchingState,
BattleId = resolution.BattleId,
NodeServerUrl = resolution.NodeServerUrl,
});
}
private async Task<IActionResult> FinishInternal(
bool isRankUrl, ColosseumBattleFinishRequestDto req, CancellationToken ct)
{
if (!TryGetViewerId(out var vid)) return Unauthorized();
var run = await _runs.GetByViewerIdAsync(vid);
if (run is null)
{
return BadRequest(new { error = "arena_colosseum_no_active_run" });
}
// Match-result tracking: 1 = win, 2 = loss, 0 = draw/abort. Record_list mirrors
// ColosseumTopTask.battle_results.result_list (1=win, 0=loss). is_retire surfaces
// as a non-counted result — does not advance the bracket.
bool counts = req.IsRetire == 0;
if (counts)
{
bool isWin = req.BattleResult == 1;
run.BattleCountThisRound += 1;
if (isWin) run.WinCount += 1;
else run.LossCount += 1;
var resultList = ParseIntList(run.ResultListJson);
resultList.Add(isWin ? 1 : 0);
run.ResultListJson = JsonSerializer.Serialize(resultList);
await _runs.UpsertAsync(run);
}
// result_code 3502 ("battle already finished") is the idempotent-retry tolerance per
// FinishTaskBase.IsEffectiveErrorCode. Server emits standard data; the translation
// middleware sets the wire result_code via data_headers from the response envelope.
return Ok(new ColosseumBattleFinishResponseDto { BattleResult = req.BattleResult });
}
private static List<int> ParseIntList(string json) =>
string.IsNullOrEmpty(json)
? new()
: JsonSerializer.Deserialize<List<int>>(json) ?? new();
}

View File

@@ -12,6 +12,7 @@ using SVSim.EmulatedEntrypoint.Models.Dtos.Common.ArenaTwoPick;
using SVSim.EmulatedEntrypoint.Models.Dtos.Requests;
using SVSim.EmulatedEntrypoint.Models.Dtos.Requests.ArenaColosseum;
using SVSim.EmulatedEntrypoint.Models.Dtos.Responses.ArenaColosseum;
using SVSim.EmulatedEntrypoint.Services.ArenaColosseum;
namespace SVSim.EmulatedEntrypoint.Controllers;
@@ -28,17 +29,20 @@ public class ArenaColosseumController : SVSimController
private readonly IArenaColosseumRunRepository _runs;
private readonly IInventoryService _inventory;
private readonly IDeckRepository _decks;
private readonly IColosseumProgressionService _progression;
public ArenaColosseumController(
IGameConfigService config,
IArenaColosseumRunRepository runs,
IInventoryService inventory,
IDeckRepository decks)
IDeckRepository decks,
IColosseumProgressionService progression)
{
_config = config;
_runs = runs;
_inventory = inventory;
_decks = decks;
_progression = progression;
}
[HttpPost("top")]
@@ -247,6 +251,104 @@ public class ArenaColosseumController : SVSimController
return Ok(new { });
}
[HttpPost("finish")]
public async Task<IActionResult> Finish([FromBody] BaseRequest _)
{
if (!TryGetViewerId(out var vid)) return Unauthorized();
var run = await _runs.GetByViewerIdAsync(vid);
if (run is null) return BadRequest(new { error = "no_active_run" });
var rounds = _config.Get<ColosseumRoundsConfig>();
var decision = _progression.DecideAdvancement(run, rounds);
if (!decision.IsBracketEnd)
{
return BadRequest(new { error = "bracket_not_finished" });
}
run.IsChampion = decision.IsChampion;
var rewardEntries = _progression.BuildFinishRewards(run, rounds);
var (wireRewards, wireRewardList) = await GrantRewardsAsync(vid, rewardEntries);
await _runs.DeleteAsync(vid);
return Ok(new FinishResponse
{
Rewards = wireRewards,
RewardList = wireRewardList,
ColosseumStatus = new ColosseumOwnStatus
{
NowRoundId = run.RoundId,
IsChampion = decision.IsChampion ? true : null,
ColosseumName = decision.IsChampion ? rounds.Rounds.Count > 0
? _config.Get<ColosseumSeasonConfig>().ColosseumName
: null : null,
},
});
}
[HttpPost("retire")]
public async Task<IActionResult> Retire([FromBody] BaseRequest _)
{
if (!TryGetViewerId(out var vid)) return Unauthorized();
var run = await _runs.GetByViewerIdAsync(vid);
if (run is null) return BadRequest(new { error = "no_active_run" });
var rounds = _config.Get<ColosseumRoundsConfig>();
var rewardEntries = _progression.BuildRetireRewards(run, rounds);
var (wireRewards, wireRewardList) = await GrantRewardsAsync(vid, rewardEntries);
await _runs.DeleteAsync(vid);
return Ok(new FinishResponse
{
Rewards = wireRewards,
RewardList = wireRewardList,
ColosseumStatus = new ColosseumOwnStatus
{
NowRoundId = run.RoundId,
RestEntryNum = 0,
},
});
}
/// <summary>
/// Grant the bundle through <c>IInventoryTransaction.GrantAsync</c> per
/// <c>feedback_reward_grant_service</c> — single dispatch table for every UserGoodsType.
/// Returns the two wire forms (rich <c>rewards</c> receipt + wallet-delta <c>reward_list</c>).
/// </summary>
private async Task<(List<ColosseumReceivedReward>, List<RewardEntryDto>)> GrantRewardsAsync(
long viewerId, IReadOnlyList<ColosseumRoundsConfig.RewardEntry> bundle)
{
var receipts = new List<ColosseumReceivedReward>();
var deltas = new List<RewardEntryDto>();
if (bundle.Count == 0) return (receipts, deltas);
await using var tx = await _inventory.BeginAsync(viewerId);
foreach (var entry in bundle)
{
var granted = await tx.GrantAsync(entry.Type, entry.DetailId, entry.Count);
receipts.Add(new ColosseumReceivedReward
{
RewardNumber = entry.Count,
RewardType = (int)entry.Type,
RewardDetailId = entry.DetailId,
Name = entry.Name,
});
// GrantAsync returns one or more (RewardType, RewardId, RewardNum) tuples — the
// post-state-total semantics are owned by the inventory commit, which the wallet-delta
// reflection inherits via tx.CommitAsync below.
var first = granted.FirstOrDefault();
deltas.Add(new RewardEntryDto
{
RewardType = first is null ? (int)entry.Type : (int)first.RewardType,
RewardId = first?.RewardId ?? entry.DetailId,
RewardNum = first?.RewardNum ?? entry.Count,
});
}
await tx.CommitAsync();
return (receipts, deltas);
}
private static int ResolveServerRoundId(ColosseumSeasonConfig season) => 1;
private async Task<RewardEntryDto> DebitCrystalAsync(IInventoryTransaction tx, int cost)

View File

@@ -0,0 +1,33 @@
using System.Text.Json.Serialization;
using MessagePack;
using SVSim.EmulatedEntrypoint.Models.Dtos.Requests;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.ArenaColosseum;
/// <summary>
/// <c>POST /colosseum_battle/do_matching</c> + <c>POST /colosseum_rank_battle/do_matching</c>.
/// Standard <c>DoMatchingParam</c> wire shape — same fields as rank/free-battle's variant.
/// Per do-matching.md, post-promotion the client forces <c>need_init = 0</c>, but the
/// server tolerates either value (URL is the routing signal).
/// </summary>
[MessagePackObject]
public sealed class ColosseumDoMatchingRequestDto : BaseRequest
{
[JsonPropertyName("need_init")] [Key("need_init")]
public int NeedInit { get; set; }
[JsonPropertyName("card_master_hash")] [Key("card_master_hash")]
public string? CardMasterHash { get; set; }
[JsonPropertyName("log")] [Key("log")]
public int Log { get; set; }
[JsonPropertyName("use_stage_select")] [Key("use_stage_select")]
public int UseStageSelect { get; set; }
[JsonPropertyName("excluded_field_id_list")] [Key("excluded_field_id_list")]
public List<long> ExcludedFieldIdList { get; set; } = new();
[JsonPropertyName("is_default_skin")] [Key("is_default_skin")]
public int IsDefaultSkin { get; set; }
}

View File

@@ -0,0 +1,49 @@
using System.Text.Json.Serialization;
using MessagePack;
using SVSim.EmulatedEntrypoint.Models.Dtos.Requests;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.ArenaColosseum;
/// <summary>
/// <c>POST /colosseum_battle/finish</c> + <c>POST /colosseum_rank_battle/finish</c> request
/// body — the per-match finish, NOT the bracket-end <c>/arena_colosseum/finish</c>.
/// Standard <c>BattleFinishParam</c> shape inherited from <c>FinishTaskBase</c>.
/// </summary>
[MessagePackObject]
public sealed class ColosseumBattleFinishRequestDto : BaseRequest
{
[JsonPropertyName("battle_result")] [Key("battle_result")]
public int BattleResult { get; set; }
[JsonPropertyName("is_retire")] [Key("is_retire")]
public int IsRetire { get; set; }
[JsonPropertyName("recovery_data")] [Key("recovery_data")]
public string? RecoveryData { get; set; }
[JsonPropertyName("class_id")] [Key("class_id")]
public int ClassId { get; set; }
[JsonPropertyName("total_turn")] [Key("total_turn")]
public int TotalTurn { get; set; }
[JsonPropertyName("evolve_count")] [Key("evolve_count")]
public int EvolveCount { get; set; }
[JsonPropertyName("enemy_evolve_count")] [Key("enemy_evolve_count")]
public int EnemyEvolveCount { get; set; }
}
/// <summary>
/// <c>colosseum_battle/finish</c> response. Per battle-finish.md, the client maps this to
/// <c>ColosseumBattleFinishDetail</c> which is an empty <c>MatchFinishBase</c> subclass —
/// no Colosseum-specific fields beyond the shared rank-battle-finish superset. Phase 2 v1
/// emits the minimum required to keep the client's <c>BattleFinishResponsProcessing</c>
/// happy.
/// </summary>
[MessagePackObject(keyAsPropertyName: true)]
public sealed class ColosseumBattleFinishResponseDto
{
[JsonPropertyName("battle_result")] [Key("battle_result")]
public int BattleResult { get; set; }
}

View File

@@ -0,0 +1,26 @@
using System.Text.Json.Serialization;
using MessagePack;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.ArenaColosseum;
/// <summary>
/// Per-entry shape for the <c>rewards</c> array on <c>/finish</c> + <c>/retire</c>. Richer
/// than <c>RewardEntryDto</c> (which is the <c>reward_list</c> shape) — carries a display
/// name. Distinct from the wallet-delta block: client renders <c>rewards</c> in the
/// post-bracket popup while <c>reward_list</c> drives the silent wallet update.
/// </summary>
[MessagePackObject]
public sealed class ColosseumReceivedReward
{
[JsonPropertyName("reward_number")] [Key("reward_number")]
public int RewardNumber { get; set; }
[JsonPropertyName("reward_type")] [Key("reward_type")]
public int RewardType { get; set; }
[JsonPropertyName("reward_detail_id")] [Key("reward_detail_id")]
public long RewardDetailId { get; set; }
[JsonPropertyName("name")] [Key("name")]
public string Name { get; set; } = "";
}

View File

@@ -0,0 +1,27 @@
using System.Text.Json.Serialization;
using MessagePack;
using SVSim.EmulatedEntrypoint.Models.Dtos.ArenaColosseum;
using SVSim.EmulatedEntrypoint.Models.Dtos.Common.ArenaTwoPick;
namespace SVSim.EmulatedEntrypoint.Models.Dtos.Responses.ArenaColosseum;
/// <summary>
/// <c>POST /arena_colosseum/finish</c> and <c>POST /arena_colosseum/retire</c>. Wire-identical
/// shape per finish.md §"Wire-shared with /retire" — endpoints differ in side-effects only:
/// /finish emits per-round-completion + champion bonus and marks the entry champion;
/// /retire emits the round-capped consolation. The client renders <c>rewards</c> in the
/// post-bracket popup, applies wallet deltas via <c>reward_list</c>, and updates the
/// status block via <c>colosseum_status</c>.
/// </summary>
[MessagePackObject]
public sealed class FinishResponse
{
[JsonPropertyName("rewards")] [Key("rewards")]
public List<ColosseumReceivedReward> Rewards { get; set; } = new();
[JsonPropertyName("reward_list")] [Key("reward_list")]
public List<RewardEntryDto> RewardList { get; set; } = new();
[JsonPropertyName("colosseum_status")] [Key("colosseum_status")]
public ColosseumOwnStatus ColosseumStatus { get; set; } = new();
}

View File

@@ -107,6 +107,8 @@ public class Program
builder.Services.AddScoped<IViewerStoryProgressRepository, ViewerStoryProgressRepository>();
builder.Services.AddScoped<IArenaTwoPickRunRepository, ArenaTwoPickRunRepository>();
builder.Services.AddScoped<IArenaColosseumRunRepository, ArenaColosseumRunRepository>();
builder.Services.AddScoped<SVSim.EmulatedEntrypoint.Services.ArenaColosseum.IColosseumProgressionService,
SVSim.EmulatedEntrypoint.Services.ArenaColosseum.ColosseumProgressionService>();
builder.Services.AddScoped<IArenaTwoPickCardPoolService, ArenaTwoPickCardPoolService>();
builder.Services.AddScoped<IArenaTwoPickService, ArenaTwoPickService>();
builder.Services.AddScoped<IMatchContextBuilder, MatchContextBuilder>();
@@ -158,6 +160,11 @@ public class Program
// (see Shadowverse_Code_2026-05-23/ApiType.cs), so PvpOnly: park forever, no AI fallback.
new ModePolicy("rotation_free_battle", PolicyKind.PvpOnly),
new ModePolicy("unlimited_free_battle", PolicyKind.PvpOnly),
// Colosseum (Grand Prix). Pre-promotion + post-promotion (rank) URLs each map
// to their own pair-up mode — the URL IS the signal per do-matching.md, and the
// node session has no way to ask the client "which bracket are you in?".
new ModePolicy("colosseum_battle", PolicyKind.PvpOnly),
new ModePolicy("colosseum_rank_battle", PolicyKind.PvpOnly),
}));
builder.Services.AddSingleton<IMatchingPairUpService, InProcessPairUp>();
// Single resolver shared by every /do_matching family controller. Owns the

View File

@@ -0,0 +1,69 @@
using SVSim.Database.Models;
using SVSim.Database.Models.Config;
namespace SVSim.EmulatedEntrypoint.Services.ArenaColosseum;
public class ColosseumProgressionService : IColosseumProgressionService
{
/// <summary>Colosseum-specific node signal — see do-matching.md §matching_state 3008.</summary>
public const int PromoteToRankMatchingState = 3008;
public bool ShouldPromoteToRankMatching(ViewerArenaColosseumRun run, int matchingState) =>
matchingState == PromoteToRankMatchingState && !run.IsRankMatching;
public AdvancementDecision DecideAdvancement(ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds)
{
var currentRound = rounds.Rounds.FirstOrDefault(r => r.RoundId == run.RoundId);
var currentGroup = currentRound?.Groups.FirstOrDefault();
var maxRoundId = rounds.Rounds.Count == 0 ? run.RoundId : rounds.Rounds.Max(r => r.RoundId);
// No matching round config (e.g. content not seeded) — treat current state as terminal
// so the controller doesn't loop forever. Champion=false because we can't tell.
if (currentGroup is null)
{
return new AdvancementDecision(run.RoundId, IsBracketEnd: true, IsChampion: false);
}
// Cleared the breakthrough threshold this round.
if (run.WinCount >= currentGroup.BreakthroughNumber)
{
bool isFinal = run.RoundId >= maxRoundId;
return new AdvancementDecision(
NextRoundId: isFinal ? run.RoundId : run.RoundId + 1,
IsBracketEnd: isFinal,
IsChampion: isFinal);
}
// Exhausted the per-round battle cap without clearing — bracket ends at current round.
if (run.BattleCountThisRound >= currentGroup.MaxBattleCount)
{
return new AdvancementDecision(run.RoundId, IsBracketEnd: true, IsChampion: false);
}
// Mid-round, still playing.
return new AdvancementDecision(run.RoundId, IsBracketEnd: false, IsChampion: false);
}
public IReadOnlyList<ColosseumRoundsConfig.RewardEntry> BuildRetireRewards(
ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds)
{
var round = rounds.Rounds.FirstOrDefault(r => r.RoundId == run.RoundId);
return round?.RetireRewards ?? new();
}
public IReadOnlyList<ColosseumRoundsConfig.RewardEntry> BuildFinishRewards(
ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds)
{
var round = rounds.Rounds.FirstOrDefault(r => r.RoundId == run.RoundId);
var bundle = new List<ColosseumRoundsConfig.RewardEntry>();
if (round is not null)
{
bundle.AddRange(round.FinishRewards);
}
if (run.IsChampion)
{
bundle.AddRange(rounds.ChampionRewards);
}
return bundle;
}
}

View File

@@ -0,0 +1,39 @@
using SVSim.Database.Enums;
using SVSim.Database.Models;
using SVSim.Database.Models.Config;
namespace SVSim.EmulatedEntrypoint.Services.ArenaColosseum;
/// <summary>
/// Pure-logic decisions for the Colosseum bracket lifecycle. Reads a
/// <see cref="ViewerArenaColosseumRun"/> + <see cref="ColosseumRoundsConfig"/> snapshot and
/// returns advancement / promotion / reward decisions. Side-effectful (debits, grants,
/// run-row writes) live on the controllers — this service just computes.
/// </summary>
public interface IColosseumProgressionService
{
/// <summary>True when the node signal <c>matching_state == 3008</c> indicates the run
/// has been promoted to the ranked bracket and we haven't already flipped the flag.
/// Subsequent battle URLs route to <c>colosseum_rank_battle/*</c>.</summary>
bool ShouldPromoteToRankMatching(ViewerArenaColosseumRun run, int matchingState);
/// <summary>Triggered post-match-finish when wins/losses cross thresholds. Returns the
/// next round id (or current if no change), whether the bracket has ended, and the
/// champion flag for the final-round-cleared case.</summary>
AdvancementDecision DecideAdvancement(ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds);
/// <summary>Bundle to grant on <c>/retire</c>. Reads
/// <see cref="ColosseumRoundsConfig.RoundEntry.RetireRewards"/> for the run's
/// <see cref="ViewerArenaColosseumRun.RoundId"/>. Empty when no matching round.</summary>
IReadOnlyList<ColosseumRoundsConfig.RewardEntry> BuildRetireRewards(
ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds);
/// <summary>Bundle to grant on <c>/finish</c>. Combines the current round's
/// <see cref="ColosseumRoundsConfig.RoundEntry.FinishRewards"/> with
/// <see cref="ColosseumRoundsConfig.ChampionRewards"/> when the run is a champion.</summary>
IReadOnlyList<ColosseumRoundsConfig.RewardEntry> BuildFinishRewards(
ViewerArenaColosseumRun run, ColosseumRoundsConfig rounds);
}
/// <summary>Output of <see cref="IColosseumProgressionService.DecideAdvancement"/>.</summary>
public sealed record AdvancementDecision(int NextRoundId, bool IsBracketEnd, bool IsChampion);

View File

@@ -24,4 +24,13 @@ public interface IMatchContextBuilder
/// no deck at that slot.
/// </summary>
Task<MatchContext> BuildForRankBattleAsync(long viewerId, Format format, int deckNo);
/// <summary>
/// Build a context for an Arena Colosseum bracket match — reads the active
/// <c>ViewerArenaColosseumRun</c>'s registered deck slot (single-deck v1) via
/// <c>IDeckRepository.GetDeck</c> (NOT viewer-graph traversal per
/// <c>project_ef_nav_include_pitfall</c>). Throws when the run is missing or no deck
/// has been registered yet.
/// </summary>
Task<MatchContext> BuildForColosseumAsync(long viewerId);
}

View File

@@ -11,17 +11,20 @@ namespace SVSim.EmulatedEntrypoint.Services;
public class MatchContextBuilder : IMatchContextBuilder
{
private readonly IArenaTwoPickRunRepository _runs;
private readonly IArenaColosseumRunRepository _colosseumRuns;
private readonly IViewerRepository _viewers;
private readonly IDeckRepository _decks;
private readonly IGameConfigService _config;
public MatchContextBuilder(
IArenaTwoPickRunRepository runs,
IArenaColosseumRunRepository colosseumRuns,
IViewerRepository viewers,
IDeckRepository decks,
IGameConfigService config)
{
_runs = runs;
_colosseumRuns = colosseumRuns;
_viewers = viewers;
_decks = decks;
_config = config;
@@ -120,4 +123,58 @@ public class MatchContextBuilder : IMatchContextBuilder
IsOfficial: viewer.Info.IsOfficial ? 1 : 0,
BattleModeId: BattleModes.TakeTwo);
}
public async Task<MatchContext> BuildForColosseumAsync(long viewerId)
{
var run = await _colosseumRuns.GetByViewerIdAsync(viewerId)
?? throw new InvalidOperationException("arena_colosseum_no_active_run");
// v1 single-deck slot — Round-3 multi-deck format is deferred per plan.
var deckNos = JsonSerializer.Deserialize<List<int>>(run.RegisteredDeckNoListJson) ?? new();
if (deckNos.Count == 0)
{
throw new InvalidOperationException("arena_colosseum_no_deck_registered");
}
var deckNo = deckNos[0];
var viewer = await _viewers.LoadForMatchContextAsync(viewerId)
?? throw new InvalidOperationException($"viewer {viewerId} not found");
var deck = await _decks.GetDeck(viewerId, run.DeckFormat, deckNo)
?? throw new InvalidOperationException(
$"viewer {viewerId} has no deck #{deckNo} for format {run.DeckFormat}");
var defaults = _config.Get<DefaultLoadoutConfig>();
var emblemId = viewer.Info.SelectedEmblem.Id != 0
? viewer.Info.SelectedEmblem.Id.ToString()
: defaults.EmblemId.ToString();
var degreeId = viewer.Info.SelectedDegree.Id != 0
? viewer.Info.SelectedDegree.Id.ToString()
: defaults.DegreeId.ToString();
var charaId = run.LeaderSkinId != 0
? run.LeaderSkinId.ToString()
: deck.LeaderSkin.Id != 0
? deck.LeaderSkin.Id.ToString()
: deck.Class.Id.ToString();
var sleeveId = deck.Sleeve.Id != 0
? deck.Sleeve.Id.ToString()
: defaults.SleeveId.ToString();
var deckCardIds = deck.Cards
.SelectMany(c => Enumerable.Repeat(c.Card.Id, c.Count))
.ToList();
return new MatchContext(
SelfDeckCardIds: deckCardIds,
ClassId: (CardClass)deck.Class.Id,
CharaId: charaId,
CardMasterName: "card_master_node_10015",
CountryCode: viewer.Info.CountryCode ?? string.Empty,
UserName: viewer.DisplayName,
SleeveId: sleeveId,
EmblemId: emblemId,
DegreeId: degreeId,
FieldId: 43,
IsOfficial: viewer.Info.IsOfficial ? 1 : 0,
BattleModeId: BattleModes.TakeTwo);
}
}