refactor(battle-node): de-magic wire flags and scattered constants

Quality pass from the 2026-06-04 BattleNode review (audit in the outer
repo). All changes are behavior-preserving — identical wire bytes,
verified by the full 1008-test suite staying green.

- Name scattered magic numbers: crypto key/IV lengths, outbound-sequencer
  base, WS receive buffer / EIO ping / SID length, polite-close timeout,
  upgrade-credential keys, battle-id digit math, deterministic-turn spin.
- resultCode = 1 -> (int)ReceiveNodeResultCode.Success across body records.
- Pong "3" -> EngineIoPacketType.Pong; remove dead NoOpBotParticipant.Touch
  (replace with #pragma warning disable CS0067).
- Wire-flag enums, serialized as numbers via JsonNumberEnumConverter:
  turnState -> TurnState{First,Second}, isSelf -> CardOwner{Opponent,Self},
  open -> ChoiceVisibility{Hidden,Open}.
- isOfficial / isInvoke -> bool / bool? via new NumericBoolJsonConverter
  (reads/writes 0/1; TDD'd). Scoped to the BattleNode wire boundary only;
  MatchContext and the HTTP/AI-start path stay int (AI-start uses -1 as a
  sentinel, so it is not boolean).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-06-04 20:46:09 -04:00
parent ed88683fa0
commit 24180d5b4b
38 changed files with 304 additions and 95 deletions

View File

@@ -28,7 +28,7 @@ internal static class BattleFrames
Cat: EmitCategory.Battle,
PubSeq: null,
PlaySeq: null,
Body: new TurnEndBody(TurnState: 0));
Body: new TurnEndBody(TurnState: TurnState.First));
internal static MsgEnvelope BuildJudgeBroadcast() => new(
NetworkBattleUri.Judge,

View File

@@ -1,3 +1,4 @@
using SVSim.BattleNode.Lifecycle;
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Protocol.Bodies;
@@ -16,7 +17,7 @@ internal sealed class JudgeHandler : IFrameHandler
// battleCode is dropped; spin=0 for the deterministic-turn slice.
if (ctx.Type == BattleType.Pvp && ctx.BothAfterReady())
{
var frame = ctx.Env with { Body = new JudgeBody(Spin: 0) };
var frame = ctx.Env with { Body = new JudgeBody(Spin: BattleFrameDefaults.DeterministicTurnSpin) };
return new[] { new DispatchRoute(ctx.From, frame, false) };
}

View File

@@ -17,8 +17,8 @@ internal sealed class LoadedHandler : IFrameHandler
// case 6: general — BattleStart (per-perspective) + Deal to the sender.
if (ctx.SenderPhase == BattleSessionPhase.AwaitingLoaded)
{
// A goes first deterministically (turnState 0); B goes second (turnState 1).
var turnState = ReferenceEquals(ctx.From, ctx.A) ? 0 : 1;
// A goes first deterministically; B goes second.
var turnState = ReferenceEquals(ctx.From, ctx.A) ? TurnState.First : TurnState.Second;
var r = new List<DispatchRoute>
{
new(ctx.From, ServerBattleFrames.BuildBattleStart(

View File

@@ -20,7 +20,7 @@ internal sealed class TurnEndHandler : IFrameHandler
// Opponent sees {turnState}; receiving TurnEnd drives ITS SendJudge (handover gate):
// the opponent (the turn taker-over) then sends a Judge, which JudgeHandler reflects
// back to it to start its turn. battleCode/actionSeq/cemetery are dropped.
var te = ctx.Env with { Body = new TurnEndBody(TurnState: 0) };
var te = ctx.Env with { Body = new TurnEndBody(TurnState: TurnState.First) };
return new[] { new DispatchRoute(ctx.Other, te, false) };
}
return Array.Empty<DispatchRoute>(); // Pvp-not-both-ready → drop (Bot already returned above)

View File

@@ -1,3 +1,4 @@
using SVSim.BattleNode.Lifecycle;
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Protocol.Bodies;
@@ -11,7 +12,7 @@ internal sealed class TurnStartHandler : IFrameHandler
// (spin=0 for the deterministic-turn slice) and self-generates its turn-open.
if (ctx.Type == BattleType.Pvp && ctx.BothAfterReady())
{
var frame = ctx.Env with { Body = new OpponentTurnStartBody(Spin: 0) };
var frame = ctx.Env with { Body = new OpponentTurnStartBody(Spin: BattleFrameDefaults.DeterministicTurnSpin) };
return new[] { new DispatchRoute(ctx.Other, frame, false) };
}

View File

@@ -1,3 +1,4 @@
using SVSim.BattleNode.Protocol;
using SVSim.BattleNode.Protocol.Bodies;
namespace SVSim.BattleNode.Sessions.Dispatch;
@@ -195,8 +196,8 @@ internal static class KnownListBuilder
if (d.TryGetValue("selectCard", out var scRaw) && scRaw is IDictionary<string, object?> sc)
{
sc.TryGetValue("open", out var openRaw);
var open = (int)AsLong(openRaw);
if (open != 0 && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable<object?> ids)
var open = (ChoiceVisibility)(int)AsLong(openRaw);
if (open != ChoiceVisibility.Hidden && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable<object?> ids)
selectCard = new SelectCardEntry(ids.Select(AsLong).ToList(), open);
}
result.Add(new KeyActionEntry(type, cardId, selectCard));
@@ -217,7 +218,7 @@ internal static class KnownListBuilder
d.TryGetValue("isSelf", out var isSelfRaw);
result.Add(new OppoTargetEntry(
TargetIdx: (int)AsLong(targetIdxRaw),
IsSelf: (int)AsLong(isSelfRaw)));
IsSelf: (CardOwner)(int)AsLong(isSelfRaw)));
}
return result.Count == 0 ? null : result;
}
@@ -247,14 +248,14 @@ internal static class KnownListBuilder
IdxList: AsIntList(idxRaw) ?? new List<int>(),
From: (int)AsLong(fromRaw),
To: (int)AsLong(toRaw),
IsSelf: (int)AsLong(isSelfRaw),
IsSelf: (CardOwner)(int)AsLong(isSelfRaw),
Skill: skillRaw as string ?? "",
CardId: d.TryGetValue("cardId", out var c) ? AsLong(c) : null,
Clan: d.TryGetValue("clan", out var cl) ? (int)AsLong(cl) : null,
Cost: d.TryGetValue("cost", out var co) ? (int)AsLong(co) : null,
SkillKeyCardIdx: AsIntList(d.TryGetValue("skillKeyCardIdx", out var sk) ? sk : null),
RandomTargetIdx: AsIntList(d.TryGetValue("randomTargetIdx", out var rt) ? rt : null),
IsInvoke: d.TryGetValue("isInvoke", out var iv) ? (int)AsLong(iv) : null,
IsInvoke: d.TryGetValue("isInvoke", out var iv) ? AsLong(iv) != 0 : null,
AttachTarget: d.TryGetValue("attachTarget", out var at) ? at as string : null));
}
return result.Count == 0 ? null : result;

View File

@@ -14,22 +14,25 @@ namespace SVSim.BattleNode.Sessions.Participants;
/// </summary>
public sealed class NoOpBotParticipant : IBattleParticipant
{
/// <summary>Stub card-master id stamped on the bot's (never-read) MatchContext.</summary>
private const string BotCardMasterName = "card_master_node_10015";
public long ViewerId => ServerBattleFrames.FakeOpponentViewerId;
public MatchContext Context { get; } = new(
SelfDeckCardIds: Array.Empty<long>(),
ClassId: "0", CharaId: "0", CardMasterName: "card_master_node_10015",
ClassId: "0", CharaId: "0", CardMasterName: BotCardMasterName,
CountryCode: "", UserName: "Bot", SleeveId: "0",
EmblemId: "0", DegreeId: "0", FieldId: 0, IsOfficial: 0,
BattleType: 0);
// Required by IBattleParticipant, but a silent bot never raises it — suppress the
// "event is never used" warning rather than keeping a dead null-emitting method.
#pragma warning disable CS0067
public event Func<MsgEnvelope, CancellationToken, Task>? FrameEmitted;
#pragma warning restore CS0067
public Task PushAsync(MsgEnvelope envelope, bool noStock, CancellationToken ct) => Task.CompletedTask;
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
public Task TerminateAsync(BattleFinishReason reason) => Task.CompletedTask;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
// Suppress unused-event warning — FrameEmitted is declared by the interface contract;
// intentionally never invoked.
private void Touch() => FrameEmitted?.Invoke(null!, default);
}

View File

@@ -31,6 +31,24 @@ internal interface IHasHandshakePhase
/// </summary>
public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
{
/// <summary>WS read-loop receive buffer, in bytes. Messages larger than this are
/// reassembled across multiple ReceiveAsync calls (see <see cref="ReadCompleteMessageAsync"/>).</summary>
private const int ReceiveBufferBytes = 8192;
/// <summary>Engine.IO heartbeat parameters advertised in the open handshake — the
/// pingInterval/pingTimeout (ms) the BestHTTP client honors. Not related to
/// <see cref="Bridge.BattleNodeOptions.WaitingRoomTimeout"/> despite the 60s coincidence.</summary>
private const int EngineIoPingIntervalMs = 25000;
private const int EngineIoPingTimeoutMs = 60000;
/// <summary>Length (hex chars) of the Engine.IO session id we mint in the open handshake.</summary>
private const int EngineIoSidLength = 16;
/// <summary>Exclusive upper bound for one random hex nibble (0x0..0xF) fed to
/// <see cref="NodeCrypto.GenerateKey"/>. Distinct concept from <see cref="EngineIoSidLength"/>
/// despite the shared value 16.</summary>
private const int KeyHexDigitExclusiveMax = 16;
private readonly WebSocket _ws;
private readonly ILogger<RealParticipant> _log;
private readonly bool _diagnosticLogging;
@@ -100,7 +118,7 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
_sessionCt = cancellation;
await SendEioOpenAsync(cancellation);
var buffer = new byte[8192];
var buffer = new byte[ReceiveBufferBytes];
var pendingAttachments = new List<byte[]>();
SocketIoFrame? pendingFrame = null;
string exitReason = "loop-condition-false";
@@ -126,7 +144,7 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
}
if (eio.Type == EngineIoPacketType.Ping)
{
await SendTextAsync("3", cancellation);
await SendTextAsync(((int)EngineIoPacketType.Pong).ToString(), cancellation);
continue;
}
if (eio.Type != EngineIoPacketType.Message) continue;
@@ -388,7 +406,7 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
private async Task EncodeAndSendAsync(MsgEnvelope env, string eventName, CancellationToken ct)
{
var key = NodeCrypto.GenerateKey(() => RandomNumberGenerator.GetInt32(0, 16));
var key = NodeCrypto.GenerateKey(() => RandomNumberGenerator.GetInt32(0, KeyHexDigitExclusiveMax));
var bytes = MsgPayloadCodec.Encode(env, key);
var sio = SocketIoFrame.BinaryEventWithAttachments(eventName, new[] { bytes });
var (text, bins) = sio.Encode();
@@ -428,8 +446,9 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
private async Task SendEioOpenAsync(CancellationToken ct)
{
var sid = Guid.NewGuid().ToString("N").Substring(0, 16);
var handshake = new EngineIoHandshake(sid, Array.Empty<string>(), 25000, 60000).ToJson();
var sid = Guid.NewGuid().ToString("N").Substring(0, EngineIoSidLength);
var handshake = new EngineIoHandshake(
sid, Array.Empty<string>(), EngineIoPingIntervalMs, EngineIoPingTimeoutMs).ToJson();
await SendTextAsync($"0{handshake}", ct);
}