diff --git a/SVSim.BattleNode/Bridge/MatchingBridge.cs b/SVSim.BattleNode/Bridge/MatchingBridge.cs index 7214382..337441d 100644 --- a/SVSim.BattleNode/Bridge/MatchingBridge.cs +++ b/SVSim.BattleNode/Bridge/MatchingBridge.cs @@ -10,6 +10,11 @@ namespace SVSim.BattleNode.Bridge; /// public sealed class MatchingBridge : IMatchingBridge { + /// Battle id is two zero-padded decimal halves concatenated (e.g. "975695" + "075012"). + /// The half-width and the draw bound must stay coupled: bound == 10^digits. + private const int BattleIdHalfDigits = 6; + private const int BattleIdHalfExclusiveMax = 1_000_000; // 10^BattleIdHalfDigits + private readonly IBattleSessionStore _store; private readonly BattleNodeOptions _options; @@ -23,12 +28,13 @@ public sealed class MatchingBridge : IMatchingBridge { ValidateContract(p1, p2, type); - // 12-digit decimal battle id mirrors the captures (e.g. "975695075012"). - // Two unbiased 6-digit draws concatenated — RandomNumberGenerator.GetInt32 uses - // rejection sampling so the result is uniform on [0, 10^6). - var hi = RandomNumberGenerator.GetInt32(0, 1_000_000); - var lo = RandomNumberGenerator.GetInt32(0, 1_000_000); - var battleId = $"{hi:D6}{lo:D6}"; + // Decimal battle id mirrors the captures (e.g. "975695075012"): two unbiased + // BattleIdHalfDigits-wide draws concatenated. RandomNumberGenerator.GetInt32 uses + // rejection sampling so each half is uniform on [0, BattleIdHalfExclusiveMax). + var hi = RandomNumberGenerator.GetInt32(0, BattleIdHalfExclusiveMax); + var lo = RandomNumberGenerator.GetInt32(0, BattleIdHalfExclusiveMax); + var halfFormat = "D" + BattleIdHalfDigits; + var battleId = hi.ToString(halfFormat) + lo.ToString(halfFormat); _store.RegisterPending(new PendingBattle(battleId, type, p1, p2)); return new PendingMatch(battleId, _options.NodeServerUrl); diff --git a/SVSim.BattleNode/Hosting/BattleNodeWebSocketHandler.cs b/SVSim.BattleNode/Hosting/BattleNodeWebSocketHandler.cs index dab1317..8d21ef9 100644 --- a/SVSim.BattleNode/Hosting/BattleNodeWebSocketHandler.cs +++ b/SVSim.BattleNode/Hosting/BattleNodeWebSocketHandler.cs @@ -33,6 +33,15 @@ namespace SVSim.BattleNode.Hosting; /// public sealed class BattleNodeWebSocketHandler { + /// Header/query key names carrying the upgrade credentials — the auth contract + /// with the client (and the loader that sets them). Single source of truth for both ends. + private const string BattleIdCredential = "BattleId"; + private const string ViewerIdCredential = "viewerId"; + + /// Grace period for the close handshake on a bail-out path. A fresh, short timeout — + /// ctx.RequestAborted may already be canceled by the path that decided to bail. + private static readonly TimeSpan PoliteCloseTimeout = TimeSpan.FromSeconds(5); + private readonly IBattleSessionStore _store; private readonly IWaitingRoom _waitingRoom; private readonly BattleNodeOptions _options; @@ -73,8 +82,8 @@ public sealed class BattleNodeWebSocketHandler // for the WebSocket-only transport (not on the URL query string). Real clients // therefore send BattleId/viewerId as headers; the integration test sends them as // query params for convenience. Check headers first, fall back to query. - var battleId = ReadCredential(ctx, "BattleId"); - var encryptedViewerId = ReadCredential(ctx, "viewerId"); + var battleId = ReadCredential(ctx, BattleIdCredential); + var encryptedViewerId = ReadCredential(ctx, ViewerIdCredential); if (string.IsNullOrEmpty(battleId) || string.IsNullOrEmpty(encryptedViewerId)) { _log.LogWarning("WS upgrade missing BattleId or viewerId (header or query)."); @@ -222,9 +231,7 @@ public sealed class BattleNodeWebSocketHandler /// private async Task TryPoliteCloseAsync(WebSocket ws, string reason, string battleId) { - // Use a fresh, short timeout — ctx.RequestAborted may already be canceled by the - // path that decided to bail out, which would skip the close immediately. - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + using var cts = new CancellationTokenSource(PoliteCloseTimeout); try { if (ws.State == WebSocketState.Open) diff --git a/SVSim.BattleNode/Lifecycle/BattleFrameDefaults.cs b/SVSim.BattleNode/Lifecycle/BattleFrameDefaults.cs index 88f8f05..17525be 100644 --- a/SVSim.BattleNode/Lifecycle/BattleFrameDefaults.cs +++ b/SVSim.BattleNode/Lifecycle/BattleFrameDefaults.cs @@ -26,4 +26,9 @@ internal static class BattleFrameDefaults /// the client's JudgeOperation doesn't read it. /// public const int OpponentJudgeSpin = 100; + + /// Spin value the PvP relay stamps on the Judge / OpponentTurnStart handover frames + /// in the deterministic-turn slice. 0 = no animation seed; per-turn spin is deferred + /// (see the real-spin design). The client self-generates its turn-open and doesn't read it. + public const int DeterministicTurnSpin = 0; } diff --git a/SVSim.BattleNode/Lifecycle/ServerBattleFrames.cs b/SVSim.BattleNode/Lifecycle/ServerBattleFrames.cs index e1e4718..9f1b106 100644 --- a/SVSim.BattleNode/Lifecycle/ServerBattleFrames.cs +++ b/SVSim.BattleNode/Lifecycle/ServerBattleFrames.cs @@ -33,7 +33,7 @@ public static class ServerBattleFrames EmblemId: selfCtx.EmblemId, DegreeId: selfCtx.DegreeId, FieldId: selfCtx.FieldId, - IsOfficial: selfCtx.IsOfficial, + IsOfficial: selfCtx.IsOfficial != 0, OppoId: oppoViewerId, Seed: seed), OppoInfo: new MatchedOppoInfo( @@ -43,7 +43,7 @@ public static class ServerBattleFrames EmblemId: oppoCtx.EmblemId, DegreeId: oppoCtx.DegreeId, FieldId: oppoCtx.FieldId, - IsOfficial: oppoCtx.IsOfficial, + IsOfficial: oppoCtx.IsOfficial != 0, OppoId: selfViewerId, Seed: seed, OppoDeckCount: oppoCtx.SelfDeckCardIds.Count), @@ -51,10 +51,10 @@ public static class ServerBattleFrames bid: battleId); public static MsgEnvelope BuildBattleStart( - MatchContext selfCtx, MatchContext oppoCtx, long selfViewerId, int turnState) => + MatchContext selfCtx, MatchContext oppoCtx, long selfViewerId, TurnState turnState) => EnvelopeForPush(NetworkBattleUri.BattleStart, new BattleStartBody( - TurnState: turnState, // 0 = this side goes first, 1 = second. Caller decides. + TurnState: turnState, // First = this side goes first, Second = second. Caller decides. BattleType: selfCtx.BattleType, SelfInfo: new BattleStartSelfInfo( Rank: BattleFrameDefaults.PlayerRank, diff --git a/SVSim.BattleNode/Protocol/Bodies/AlivePushBody.cs b/SVSim.BattleNode/Protocol/Bodies/AlivePushBody.cs index 5ebafbf..b32dba4 100644 --- a/SVSim.BattleNode/Protocol/Bodies/AlivePushBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/AlivePushBody.cs @@ -2,6 +2,10 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; +/// Gungnir keepalive push. scs = self connection status, ocs = opponent +/// connection status; both carry ("ONLINE") in v1. +/// Intentionally has no resultCode — the client treats an absent resultCode on alive +/// frames as "no error" (the lone body without one). public sealed record AlivePushBody( [property: JsonPropertyName("scs")] string Scs, [property: JsonPropertyName("ocs")] string Ocs) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/BattleFinishBody.cs b/SVSim.BattleNode/Protocol/Bodies/BattleFinishBody.cs index 42595ec..2129192 100644 --- a/SVSim.BattleNode/Protocol/Bodies/BattleFinishBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/BattleFinishBody.cs @@ -6,4 +6,4 @@ public sealed record BattleFinishBody( [property: JsonPropertyName("result")] [property: JsonConverter(typeof(JsonNumberEnumConverter))] BattleResult Result, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/BattleStartBody.cs b/SVSim.BattleNode/Protocol/Bodies/BattleStartBody.cs index 31a0239..b549118 100644 --- a/SVSim.BattleNode/Protocol/Bodies/BattleStartBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/BattleStartBody.cs @@ -3,11 +3,12 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; public sealed record BattleStartBody( - [property: JsonPropertyName("turnState")] int TurnState, + [property: JsonPropertyName("turnState")] + [property: JsonConverter(typeof(JsonNumberEnumConverter))] TurnState TurnState, [property: JsonPropertyName("battleType")] int BattleType, [property: JsonPropertyName("selfInfo")] BattleStartSelfInfo SelfInfo, [property: JsonPropertyName("oppoInfo")] BattleStartOppoInfo OppoInfo, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; public sealed record BattleStartSelfInfo( [property: JsonPropertyName("rank")] string Rank, @@ -18,6 +19,7 @@ public sealed record BattleStartSelfInfo( // Note: BattlePoint is int on the wire here (not string as on self) — matches the // captured prod frame at data_dumps/captures/battle-traffic_tk2_regular.ndjson. +// The string-self / int-oppo split is INTENTIONAL; do NOT unify the two for "consistency". public sealed record BattleStartOppoInfo( [property: JsonPropertyName("rank")] string Rank, [property: JsonPropertyName("isMasterRank")] string IsMasterRank, diff --git a/SVSim.BattleNode/Protocol/Bodies/DealBody.cs b/SVSim.BattleNode/Protocol/Bodies/DealBody.cs index 2c23aa2..83d7c8a 100644 --- a/SVSim.BattleNode/Protocol/Bodies/DealBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/DealBody.cs @@ -5,4 +5,4 @@ namespace SVSim.BattleNode.Protocol.Bodies; public sealed record DealBody( [property: JsonPropertyName("self")] IReadOnlyList Self, [property: JsonPropertyName("oppo")] IReadOnlyList Oppo, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/JudgeBody.cs b/SVSim.BattleNode/Protocol/Bodies/JudgeBody.cs index 851735d..c69e0e8 100644 --- a/SVSim.BattleNode/Protocol/Bodies/JudgeBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/JudgeBody.cs @@ -2,6 +2,9 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; +/// Server-pushed Judge frame (turn-handover gate; reflected to the sender in PvP). +/// Same wire shape as — kept distinct because they back +/// different frames/URIs. public sealed record JudgeBody( [property: JsonPropertyName("spin")] int Spin, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/MatchedBody.cs b/SVSim.BattleNode/Protocol/Bodies/MatchedBody.cs index a5e9e80..f4021da 100644 --- a/SVSim.BattleNode/Protocol/Bodies/MatchedBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/MatchedBody.cs @@ -6,8 +6,10 @@ public sealed record MatchedBody( [property: JsonPropertyName("selfInfo")] MatchedSelfInfo SelfInfo, [property: JsonPropertyName("oppoInfo")] MatchedOppoInfo OppoInfo, [property: JsonPropertyName("selfDeck")] IReadOnlyList SelfDeck, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; +// Note: `country_code` is deliberately snake_case among camelCase siblings — that's what prod +// sends on this frame (verified against the TK2 capture). Do NOT "normalize" it to countryCode. public sealed record MatchedSelfInfo( [property: JsonPropertyName("country_code")] string CountryCode, [property: JsonPropertyName("userName")] string UserName, @@ -15,7 +17,8 @@ public sealed record MatchedSelfInfo( [property: JsonPropertyName("emblemId")] string EmblemId, [property: JsonPropertyName("degreeId")] string DegreeId, [property: JsonPropertyName("fieldId")] int FieldId, - [property: JsonPropertyName("isOfficial")] int IsOfficial, + [property: JsonPropertyName("isOfficial")] + [property: JsonConverter(typeof(NumericBoolJsonConverter))] bool IsOfficial, [property: JsonPropertyName("oppoId")] long OppoId, [property: JsonPropertyName("seed")] long Seed); @@ -26,7 +29,8 @@ public sealed record MatchedOppoInfo( [property: JsonPropertyName("emblemId")] string EmblemId, [property: JsonPropertyName("degreeId")] string DegreeId, [property: JsonPropertyName("fieldId")] int FieldId, - [property: JsonPropertyName("isOfficial")] int IsOfficial, + [property: JsonPropertyName("isOfficial")] + [property: JsonConverter(typeof(NumericBoolJsonConverter))] bool IsOfficial, [property: JsonPropertyName("oppoId")] long OppoId, [property: JsonPropertyName("seed")] long Seed, [property: JsonPropertyName("oppoDeckCount")] int OppoDeckCount); diff --git a/SVSim.BattleNode/Protocol/Bodies/OpponentTurnStartBody.cs b/SVSim.BattleNode/Protocol/Bodies/OpponentTurnStartBody.cs index e397348..67403f4 100644 --- a/SVSim.BattleNode/Protocol/Bodies/OpponentTurnStartBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/OpponentTurnStartBody.cs @@ -2,6 +2,9 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; +/// Server-pushed opponent-turn-open frame (relayed to the non-active player). +/// Same wire shape as — kept distinct because they back different +/// frames/URIs. public sealed record OpponentTurnStartBody( [property: JsonPropertyName("spin")] int Spin, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/PlayActionsBroadcastBody.cs b/SVSim.BattleNode/Protocol/Bodies/PlayActionsBroadcastBody.cs index c639733..d1165ad 100644 --- a/SVSim.BattleNode/Protocol/Bodies/PlayActionsBroadcastBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/PlayActionsBroadcastBody.cs @@ -32,7 +32,8 @@ public sealed record KeyActionEntry( /// Only emitted for the open:1 pass-through case (open:0 strips the whole selectCard). public sealed record SelectCardEntry( [property: JsonPropertyName("cardId")] IReadOnlyList CardId, - [property: JsonPropertyName("open")] int Open); + [property: JsonPropertyName("open")] + [property: JsonConverter(typeof(JsonNumberEnumConverter))] ChoiceVisibility Open); /// One revealed card in a knownList. Vanilla slice fills cardId from the sender's /// deck map and leaves spellboost 0 / attachTarget "" (cost/clan/tribe deferred to the card-master @@ -48,7 +49,8 @@ public sealed record KnownCardEntry( /// verbatim — no perspective flip (bullet-3 audit F2). public sealed record OppoTargetEntry( [property: JsonPropertyName("targetIdx")] int TargetIdx, - [property: JsonPropertyName("isSelf")] int IsSelf); + [property: JsonPropertyName("isSelf")] + [property: JsonConverter(typeof(JsonNumberEnumConverter))] CardOwner IsSelf); /// One entry in a relayed uList (the unapproved-movement list) — a skill-driven /// card movement (fetch / search / summon-from-deck / discard-reveal) the node forwards VERBATIM @@ -60,12 +62,14 @@ public sealed record UnapprovedCardEntry( [property: JsonPropertyName("idxList")] IReadOnlyList IdxList, [property: JsonPropertyName("from")] int From, [property: JsonPropertyName("to")] int To, - [property: JsonPropertyName("isSelf")] int IsSelf, + [property: JsonPropertyName("isSelf")] + [property: JsonConverter(typeof(JsonNumberEnumConverter))] CardOwner IsSelf, [property: JsonPropertyName("skill")] string Skill, [property: JsonPropertyName("cardId")] long? CardId = null, [property: JsonPropertyName("clan")] int? Clan = null, [property: JsonPropertyName("cost")] int? Cost = null, [property: JsonPropertyName("skillKeyCardIdx")] IReadOnlyList? SkillKeyCardIdx = null, [property: JsonPropertyName("randomTargetIdx")] IReadOnlyList? RandomTargetIdx = null, - [property: JsonPropertyName("isInvoke")] int? IsInvoke = null, + [property: JsonPropertyName("isInvoke")] + [property: JsonConverter(typeof(NumericBoolJsonConverter))] bool? IsInvoke = null, [property: JsonPropertyName("attachTarget")] string? AttachTarget = null); diff --git a/SVSim.BattleNode/Protocol/Bodies/ReadyBody.cs b/SVSim.BattleNode/Protocol/Bodies/ReadyBody.cs index 21b5736..dcdacd6 100644 --- a/SVSim.BattleNode/Protocol/Bodies/ReadyBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/ReadyBody.cs @@ -7,4 +7,4 @@ public sealed record ReadyBody( [property: JsonPropertyName("oppo")] IReadOnlyList Oppo, [property: JsonPropertyName("idxChangeSeed")] int IdxChangeSeed, [property: JsonPropertyName("spin")] int Spin, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/ResultCodeOnlyBody.cs b/SVSim.BattleNode/Protocol/Bodies/ResultCodeOnlyBody.cs index 11057e2..6bfb4f6 100644 --- a/SVSim.BattleNode/Protocol/Bodies/ResultCodeOnlyBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/ResultCodeOnlyBody.cs @@ -3,4 +3,4 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; public sealed record ResultCodeOnlyBody( - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/SwapResponseBody.cs b/SVSim.BattleNode/Protocol/Bodies/SwapResponseBody.cs index 673aca7..40f2d96 100644 --- a/SVSim.BattleNode/Protocol/Bodies/SwapResponseBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/SwapResponseBody.cs @@ -4,4 +4,4 @@ namespace SVSim.BattleNode.Protocol.Bodies; public sealed record SwapResponseBody( [property: JsonPropertyName("self")] IReadOnlyList Self, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/Bodies/TurnEndBody.cs b/SVSim.BattleNode/Protocol/Bodies/TurnEndBody.cs index 60b75ac..17097e1 100644 --- a/SVSim.BattleNode/Protocol/Bodies/TurnEndBody.cs +++ b/SVSim.BattleNode/Protocol/Bodies/TurnEndBody.cs @@ -3,5 +3,6 @@ using System.Text.Json.Serialization; namespace SVSim.BattleNode.Protocol.Bodies; public sealed record TurnEndBody( - [property: JsonPropertyName("turnState")] int TurnState, - [property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody; + [property: JsonPropertyName("turnState")] + [property: JsonConverter(typeof(JsonNumberEnumConverter))] TurnState TurnState, + [property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody; diff --git a/SVSim.BattleNode/Protocol/CardOwner.cs b/SVSim.BattleNode/Protocol/CardOwner.cs new file mode 100644 index 0000000..7695e5a --- /dev/null +++ b/SVSim.BattleNode/Protocol/CardOwner.cs @@ -0,0 +1,17 @@ +namespace SVSim.BattleNode.Protocol; + +/// +/// Wire value of the actor-relative isSelf flag on relayed lists (targetList, +/// uList): whose side a referenced card belongs to, from the SENDER's perspective. The node +/// forwards it verbatim — no perspective flip (bullet-3 audit F2). The client reads it via +/// ConvertToInt(...) == 1 (NetworkBattleReceiver.cs), so it serializes as the +/// underlying int via . +/// +public enum CardOwner +{ + /// Card belongs to the opponent of the sender. + Opponent = 0, + + /// Card belongs to the sender. + Self = 1, +} diff --git a/SVSim.BattleNode/Protocol/ChoiceVisibility.cs b/SVSim.BattleNode/Protocol/ChoiceVisibility.cs new file mode 100644 index 0000000..3ca0356 --- /dev/null +++ b/SVSim.BattleNode/Protocol/ChoiceVisibility.cs @@ -0,0 +1,17 @@ +namespace SVSim.BattleNode.Protocol; + +/// +/// Wire value of open on a choice/Discover selectCard: whether the pick is revealed. +/// The client emits it as selectCardIsOpen ? 1 : 0 (SendKeyActionDataManager.cs); +/// the node uses it to decide whether to strip the pick for the opponent (Hidden = strip). +/// Serializes as the underlying int via +/// . +/// +public enum ChoiceVisibility +{ + /// Hidden draw-to-hand pick — the chosen card stays secret until played. + Hidden = 0, + + /// Visible board choice — the pick is revealed immediately. + Open = 1, +} diff --git a/SVSim.BattleNode/Protocol/NumericBoolJsonConverter.cs b/SVSim.BattleNode/Protocol/NumericBoolJsonConverter.cs new file mode 100644 index 0000000..60e992c --- /dev/null +++ b/SVSim.BattleNode/Protocol/NumericBoolJsonConverter.cs @@ -0,0 +1,29 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace SVSim.BattleNode.Protocol; + +/// +/// Serializes a as the wire's numeric 0/1. The client reads these flags via +/// Convert.ToInt32 / Convert.ToBoolean (e.g. isOfficial, isInvoke) — +/// never as a JSON true/false token — so a real bool property must still emit +/// a number. Read accepts a JSON number (0 = false, non-zero = true) and, defensively, a +/// true/false token or a numeric string. Applied per-field via +/// [JsonConverter(typeof(NumericBoolJsonConverter))]; works on bool? too (System.Text.Json +/// wraps a JsonConverter<bool> for the nullable case). +/// +public sealed class NumericBoolJsonConverter : JsonConverter +{ + public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => reader.TokenType switch + { + JsonTokenType.Number => reader.GetInt64() != 0, + JsonTokenType.True => true, + JsonTokenType.False => false, + JsonTokenType.String => long.TryParse(reader.GetString(), out var n) && n != 0, + _ => throw new JsonException($"Cannot convert token {reader.TokenType} to a numeric bool"), + }; + + public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options) + => writer.WriteNumberValue(value ? 1 : 0); +} diff --git a/SVSim.BattleNode/Protocol/TurnState.cs b/SVSim.BattleNode/Protocol/TurnState.cs new file mode 100644 index 0000000..0df8b62 --- /dev/null +++ b/SVSim.BattleNode/Protocol/TurnState.cs @@ -0,0 +1,16 @@ +namespace SVSim.BattleNode.Protocol; + +/// +/// Wire value of turnState on BattleStart / TurnEnd frames: which side acts first. +/// The client reads it via Convert.ToInt32 (RealTimeNetworkAgent.cs "turnState" +/// case) into NetworkUserInfoData.TurnState, so it serializes as the underlying int via +/// . +/// +public enum TurnState +{ + /// This side takes the first turn. + First = 0, + + /// This side takes the second turn. + Second = 1, +} diff --git a/SVSim.BattleNode/Reliability/Gungnir.cs b/SVSim.BattleNode/Reliability/Gungnir.cs index 3e28158..1d5146b 100644 --- a/SVSim.BattleNode/Reliability/Gungnir.cs +++ b/SVSim.BattleNode/Reliability/Gungnir.cs @@ -1,7 +1,9 @@ namespace SVSim.BattleNode.Reliability; /// -/// Body builders for the alive channel. The timer/loop that drives 5s emits lives on +/// Body builders for the alive channel ("Gungnir" is the client's codename for the +/// keepalive/connection-status channel — see ). +/// The timer/loop that drives emits lives on /// BattleSession; this class is just the pure body-shape factory. /// v1 always reports scs/ocs=ONLINE — real disconnect detection is deferred. The push /// body itself is constructed inline in BattleSession.HandleAliveEventAsync using diff --git a/SVSim.BattleNode/Reliability/OutboundSequencer.cs b/SVSim.BattleNode/Reliability/OutboundSequencer.cs index 79cdbb6..3b5f2a6 100644 --- a/SVSim.BattleNode/Reliability/OutboundSequencer.cs +++ b/SVSim.BattleNode/Reliability/OutboundSequencer.cs @@ -9,7 +9,11 @@ namespace SVSim.BattleNode.Reliability; /// public sealed class OutboundSequencer { - private long _next = 1; + /// First playSeq assigned. Starts at 1, not 0 — 0 is reserved for no-stock / + /// unsequenced pushes (which carry a null PlaySeq via ). + private const long FirstPlaySeq = 1; + + private long _next = FirstPlaySeq; private readonly Dictionary _archive = new(); public IReadOnlyDictionary Archive => _archive; diff --git a/SVSim.BattleNode/Sessions/Dispatch/BattleFrames.cs b/SVSim.BattleNode/Sessions/Dispatch/BattleFrames.cs index 7b4b2a3..1f4dc97 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/BattleFrames.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/BattleFrames.cs @@ -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, diff --git a/SVSim.BattleNode/Sessions/Dispatch/Handlers/JudgeHandler.cs b/SVSim.BattleNode/Sessions/Dispatch/Handlers/JudgeHandler.cs index cd6d637..2b03e9a 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/Handlers/JudgeHandler.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/Handlers/JudgeHandler.cs @@ -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) }; } diff --git a/SVSim.BattleNode/Sessions/Dispatch/Handlers/LoadedHandler.cs b/SVSim.BattleNode/Sessions/Dispatch/Handlers/LoadedHandler.cs index a1bdfad..e615fe9 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/Handlers/LoadedHandler.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/Handlers/LoadedHandler.cs @@ -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 { new(ctx.From, ServerBattleFrames.BuildBattleStart( diff --git a/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnEndHandler.cs b/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnEndHandler.cs index f54a2eb..8dbc55c 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnEndHandler.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnEndHandler.cs @@ -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(); // Pvp-not-both-ready → drop (Bot already returned above) diff --git a/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnStartHandler.cs b/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnStartHandler.cs index e7a143b..89d265a 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnStartHandler.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/Handlers/TurnStartHandler.cs @@ -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) }; } diff --git a/SVSim.BattleNode/Sessions/Dispatch/KnownListBuilder.cs b/SVSim.BattleNode/Sessions/Dispatch/KnownListBuilder.cs index 9ec92c0..bad9ea9 100644 --- a/SVSim.BattleNode/Sessions/Dispatch/KnownListBuilder.cs +++ b/SVSim.BattleNode/Sessions/Dispatch/KnownListBuilder.cs @@ -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 sc) { sc.TryGetValue("open", out var openRaw); - var open = (int)AsLong(openRaw); - if (open != 0 && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable ids) + var open = (ChoiceVisibility)(int)AsLong(openRaw); + if (open != ChoiceVisibility.Hidden && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable 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(), 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; diff --git a/SVSim.BattleNode/Sessions/Participants/NoOpBotParticipant.cs b/SVSim.BattleNode/Sessions/Participants/NoOpBotParticipant.cs index 65fc111..b82343a 100644 --- a/SVSim.BattleNode/Sessions/Participants/NoOpBotParticipant.cs +++ b/SVSim.BattleNode/Sessions/Participants/NoOpBotParticipant.cs @@ -14,22 +14,25 @@ namespace SVSim.BattleNode.Sessions.Participants; /// public sealed class NoOpBotParticipant : IBattleParticipant { + /// Stub card-master id stamped on the bot's (never-read) MatchContext. + private const string BotCardMasterName = "card_master_node_10015"; + public long ViewerId => ServerBattleFrames.FakeOpponentViewerId; public MatchContext Context { get; } = new( SelfDeckCardIds: Array.Empty(), - 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? 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); } diff --git a/SVSim.BattleNode/Sessions/Participants/RealParticipant.cs b/SVSim.BattleNode/Sessions/Participants/RealParticipant.cs index 1374031..fd2de61 100644 --- a/SVSim.BattleNode/Sessions/Participants/RealParticipant.cs +++ b/SVSim.BattleNode/Sessions/Participants/RealParticipant.cs @@ -31,6 +31,24 @@ internal interface IHasHandshakePhase /// public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase { + /// WS read-loop receive buffer, in bytes. Messages larger than this are + /// reassembled across multiple ReceiveAsync calls (see ). + private const int ReceiveBufferBytes = 8192; + + /// Engine.IO heartbeat parameters advertised in the open handshake — the + /// pingInterval/pingTimeout (ms) the BestHTTP client honors. Not related to + /// despite the 60s coincidence. + private const int EngineIoPingIntervalMs = 25000; + private const int EngineIoPingTimeoutMs = 60000; + + /// Length (hex chars) of the Engine.IO session id we mint in the open handshake. + private const int EngineIoSidLength = 16; + + /// Exclusive upper bound for one random hex nibble (0x0..0xF) fed to + /// . Distinct concept from + /// despite the shared value 16. + private const int KeyHexDigitExclusiveMax = 16; + private readonly WebSocket _ws; private readonly ILogger _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(); 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(), 25000, 60000).ToJson(); + var sid = Guid.NewGuid().ToString("N").Substring(0, EngineIoSidLength); + var handshake = new EngineIoHandshake( + sid, Array.Empty(), EngineIoPingIntervalMs, EngineIoPingTimeoutMs).ToJson(); await SendTextAsync($"0{handshake}", ct); } diff --git a/SVSim.BattleNode/Wire/NodeCrypto.cs b/SVSim.BattleNode/Wire/NodeCrypto.cs index dcbafc3..cf607be 100644 --- a/SVSim.BattleNode/Wire/NodeCrypto.cs +++ b/SVSim.BattleNode/Wire/NodeCrypto.cs @@ -10,6 +10,12 @@ namespace SVSim.BattleNode.Wire; /// public static class NodeCrypto { + /// Length of the ASCII key, in chars (AES-256 = 32 bytes = 32 ASCII chars). + private const int KeyLength = 32; + + /// IV length, in chars. The node derives the IV from the first half of the key. + private const int IvLength = KeyLength / 2; + /// /// Generate a fresh 32-char key for server-initiated encryption. /// Calls 32 times; the result is masked with @@ -27,20 +33,20 @@ public static class NodeCrypto /// public static string GenerateKey(Func randHexDigit) { - var sb = new StringBuilder(32); - for (var i = 0; i < 32; i++) + var sb = new StringBuilder(KeyLength); + for (var i = 0; i < KeyLength; i++) { sb.Append((randHexDigit() & 0xF).ToString("x")); } var ascii = Encoding.ASCII.GetBytes(sb.ToString()); - return Convert.ToBase64String(ascii).Substring(0, 32); + return Convert.ToBase64String(ascii).Substring(0, KeyLength); } /// Encrypt: returns key + base64(AES-256-CBC(plain)). public static string EncryptForNode(string plaintext, string key) { - if (key.Length != 32) - throw new ArgumentException($"Key must be exactly 32 chars, got {key.Length}", nameof(key)); + if (key.Length != KeyLength) + throw new ArgumentException($"Key must be exactly {KeyLength} chars, got {key.Length}", nameof(key)); using var aes = BuildAes(key); using var encryptor = aes.CreateEncryptor(); var plainBytes = Encoding.UTF8.GetBytes(plaintext); @@ -51,10 +57,10 @@ public static class NodeCrypto /// Decrypt: input[0..32] is key, input[32..] is base64(ciphertext). public static string DecryptForNode(string encrypted) { - if (encrypted.Length < 32) - throw new ArgumentException("Encrypted blob is shorter than the 32-char key prefix", nameof(encrypted)); - var key = encrypted.Substring(0, 32); - var cipherBytes = Convert.FromBase64String(encrypted.Substring(32)); + if (encrypted.Length < KeyLength) + throw new ArgumentException($"Encrypted blob is shorter than the {KeyLength}-char key prefix", nameof(encrypted)); + var key = encrypted.Substring(0, KeyLength); + var cipherBytes = Convert.FromBase64String(encrypted.Substring(KeyLength)); using var aes = BuildAes(key); using var decryptor = aes.CreateDecryptor(); var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length); @@ -62,9 +68,10 @@ public static class NodeCrypto } /// - /// Configure an AES-256-CBC instance with the node's IV derivation (first 16 chars - /// of the key, UTF-8). Callers own disposal. Assumes is the - /// 32-char ASCII key the encrypt / decrypt path has already validated. + /// Configure an AES-256-CBC instance with the node's IV derivation (first + /// chars of the key, UTF-8). Callers own disposal. Assumes + /// is the -char ASCII key the encrypt / + /// decrypt path has already validated. /// private static Aes BuildAes(string key) { @@ -73,7 +80,7 @@ public static class NodeCrypto aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = Encoding.UTF8.GetBytes(key); - aes.IV = Encoding.UTF8.GetBytes(key.Substring(0, 16)); + aes.IV = Encoding.UTF8.GetBytes(key.Substring(0, IvLength)); return aes; } } diff --git a/SVSim.UnitTests/BattleNode/Lifecycle/ServerBattleFramesTests.cs b/SVSim.UnitTests/BattleNode/Lifecycle/ServerBattleFramesTests.cs index a8fe15e..90865b0 100644 --- a/SVSim.UnitTests/BattleNode/Lifecycle/ServerBattleFramesTests.cs +++ b/SVSim.UnitTests/BattleNode/Lifecycle/ServerBattleFramesTests.cs @@ -65,15 +65,15 @@ public class ServerBattleFramesTests Assert.That(body.SelfInfo.EmblemId, Is.EqualTo("888")); Assert.That(body.SelfInfo.DegreeId, Is.EqualTo("777")); Assert.That(body.SelfInfo.FieldId, Is.EqualTo(42)); - Assert.That(body.SelfInfo.IsOfficial, Is.EqualTo(1)); + Assert.That(body.SelfInfo.IsOfficial, Is.True); } [Test] public void BuildBattleStart_HasTurnStateZero_AndUsesContextBattleType() { - var env = ServerBattleFrames.BuildBattleStart(FixtureCtx(), FakeOpponentCtx(), selfViewerId: 1, turnState: 0); + var env = ServerBattleFrames.BuildBattleStart(FixtureCtx(), FakeOpponentCtx(), selfViewerId: 1, turnState: TurnState.First); var body = (BattleStartBody)env.Body; - Assert.That(body.TurnState, Is.EqualTo(0)); + Assert.That(body.TurnState, Is.EqualTo(TurnState.First)); Assert.That(body.BattleType, Is.EqualTo(11)); } @@ -87,7 +87,7 @@ public class ServerBattleFramesTests BattleType = 42, }; - var env = ServerBattleFrames.BuildBattleStart(ctx, FakeOpponentCtx(), selfViewerId: 1, turnState: 0); + var env = ServerBattleFrames.BuildBattleStart(ctx, FakeOpponentCtx(), selfViewerId: 1, turnState: TurnState.First); var body = (BattleStartBody)env.Body; Assert.That(body.SelfInfo.ClassId, Is.EqualTo("7")); diff --git a/SVSim.UnitTests/BattleNode/Lifecycle/TypedBodyWireShapeTests.cs b/SVSim.UnitTests/BattleNode/Lifecycle/TypedBodyWireShapeTests.cs index 436ffe6..fe20320 100644 --- a/SVSim.UnitTests/BattleNode/Lifecycle/TypedBodyWireShapeTests.cs +++ b/SVSim.UnitTests/BattleNode/Lifecycle/TypedBodyWireShapeTests.cs @@ -87,7 +87,7 @@ public class TypedBodyWireShapeTests [Test] public void BuildBattleStart_SerializesAllWireKeysAndPreservesBattlePointAsymmetry() { - var env = ServerBattleFrames.BuildBattleStart(FixtureCtx(), FakeOpponentCtx(), selfViewerId: 906243102, turnState: 0); + var env = ServerBattleFrames.BuildBattleStart(FixtureCtx(), FakeOpponentCtx(), selfViewerId: 906243102, turnState: TurnState.First); var json = MsgEnvelope.ToJson(env); var node = JsonNode.Parse(json)!.AsObject(); diff --git a/SVSim.UnitTests/BattleNode/Protocol/Bodies/BattleStartBodyTests.cs b/SVSim.UnitTests/BattleNode/Protocol/Bodies/BattleStartBodyTests.cs index 21b7620..c49d597 100644 --- a/SVSim.UnitTests/BattleNode/Protocol/Bodies/BattleStartBodyTests.cs +++ b/SVSim.UnitTests/BattleNode/Protocol/Bodies/BattleStartBodyTests.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Nodes; using NUnit.Framework; +using SVSim.BattleNode.Protocol; using SVSim.BattleNode.Protocol.Bodies; namespace SVSim.UnitTests.BattleNode.Protocol.Bodies; @@ -12,7 +13,7 @@ public class BattleStartBodyTests public void Serializes_TopLevelFields_WithCorrectWireKeys() { var body = new BattleStartBody( - TurnState: 0, BattleType: 11, + TurnState: TurnState.First, BattleType: 11, SelfInfo: new BattleStartSelfInfo("10", "6270", "1", "1", "card_master_node_10015"), OppoInfo: new BattleStartOppoInfo("1", "0", 0, "0", "8", "8", "card_master_node_10015")); diff --git a/SVSim.UnitTests/BattleNode/Protocol/Bodies/MatchedBodyTests.cs b/SVSim.UnitTests/BattleNode/Protocol/Bodies/MatchedBodyTests.cs index 5dc6afc..39823b6 100644 --- a/SVSim.UnitTests/BattleNode/Protocol/Bodies/MatchedBodyTests.cs +++ b/SVSim.UnitTests/BattleNode/Protocol/Bodies/MatchedBodyTests.cs @@ -15,11 +15,11 @@ public class MatchedBodyTests SelfInfo: new MatchedSelfInfo( CountryCode: "KOR", UserName: "Player", SleeveId: "3000011", EmblemId: "701441011", DegreeId: "300003", FieldId: 43, - IsOfficial: 0, OppoId: 847666884L, Seed: 17_548_138L), + IsOfficial: false, OppoId: 847666884L, Seed: 17_548_138L), OppoInfo: new MatchedOppoInfo( CountryCode: "JPN", UserName: "Opponent", SleeveId: "704141010", EmblemId: "400001100", DegreeId: "120027", FieldId: 5, - IsOfficial: 0, OppoId: 906243102L, Seed: 17_548_138L, OppoDeckCount: 30), + IsOfficial: false, OppoId: 906243102L, Seed: 17_548_138L, OppoDeckCount: 30), SelfDeck: new[] { new DeckCardRef(Idx: 1, CardId: 100011010L) }); var node = (JsonObject)JsonSerializer.SerializeToNode(body)!; @@ -40,8 +40,8 @@ public class MatchedBodyTests public void OppoInfo_HasOppoDeckCount_OnTheWire() { var body = new MatchedBody( - SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L), - OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L, OppoDeckCount: 30), + SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L), + OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L, OppoDeckCount: 30), SelfDeck: System.Array.Empty()); var node = (JsonObject)JsonSerializer.SerializeToNode(body)!; @@ -54,8 +54,8 @@ public class MatchedBodyTests public void SelfInfo_DoesNotHaveOppoDeckCount_OnTheWire() { var body = new MatchedBody( - SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L), - OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30), + SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L), + OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30), SelfDeck: System.Array.Empty()); var node = (JsonObject)JsonSerializer.SerializeToNode(body)!; @@ -68,8 +68,8 @@ public class MatchedBodyTests public void ResultCode_DefaultsToOne_OnConstruction() { var body = new MatchedBody( - SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L), - OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30), + SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L), + OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30), SelfDeck: System.Array.Empty()); Assert.That(body.ResultCode, Is.EqualTo(1)); @@ -81,8 +81,8 @@ public class MatchedBodyTests public void SelfDeck_SerializesAsArray_WithIdxAndCardIdKeys() { var body = new MatchedBody( - SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L), - OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30), + SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L), + OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30), SelfDeck: new[] { new DeckCardRef(Idx: 1, CardId: 100011010L), diff --git a/SVSim.UnitTests/BattleNode/Protocol/NumericBoolJsonConverterTests.cs b/SVSim.UnitTests/BattleNode/Protocol/NumericBoolJsonConverterTests.cs new file mode 100644 index 0000000..a1b2819 --- /dev/null +++ b/SVSim.UnitTests/BattleNode/Protocol/NumericBoolJsonConverterTests.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using NUnit.Framework; +using SVSim.BattleNode.Protocol; + +namespace SVSim.UnitTests.BattleNode.Protocol; + +[TestFixture] +public class NumericBoolJsonConverterTests +{ + private sealed record Probe( + [property: JsonPropertyName("flag")] + [property: JsonConverter(typeof(NumericBoolJsonConverter))] + bool Flag, + [property: JsonPropertyName("opt")] + [property: JsonConverter(typeof(NumericBoolJsonConverter))] + bool? Opt = null); + + private static readonly JsonSerializerOptions Options = new() + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + [Test] + public void Writes_true_as_numeric_1_and_false_as_numeric_0() + { + var node = JsonSerializer.SerializeToElement(new Probe(Flag: true), Options); + Assert.That(node.GetProperty("flag").ValueKind, Is.EqualTo(JsonValueKind.Number)); + Assert.That(node.GetProperty("flag").GetInt32(), Is.EqualTo(1)); + + var falseNode = JsonSerializer.SerializeToElement(new Probe(Flag: false), Options); + Assert.That(falseNode.GetProperty("flag").GetInt32(), Is.EqualTo(0)); + } + + [Test] + public void Reads_numeric_0_and_1_back_to_bool() + { + Assert.That(JsonSerializer.Deserialize("{\"flag\":1}", Options)!.Flag, Is.True); + Assert.That(JsonSerializer.Deserialize("{\"flag\":0}", Options)!.Flag, Is.False); + } + + [Test] + public void Nullable_true_emits_1_and_null_is_omitted() + { + var present = JsonSerializer.SerializeToElement(new Probe(Flag: false, Opt: true), Options); + Assert.That(present.GetProperty("opt").GetInt32(), Is.EqualTo(1)); + + var absent = JsonSerializer.SerializeToElement(new Probe(Flag: false, Opt: null), Options); + Assert.That(absent.TryGetProperty("opt", out _), Is.False, "null bool? must be omitted, not emitted"); + } +} diff --git a/SVSim.UnitTests/BattleNode/Sessions/BattleSessionDispatchTests.cs b/SVSim.UnitTests/BattleNode/Sessions/BattleSessionDispatchTests.cs index 52d6721..b7b499d 100644 --- a/SVSim.UnitTests/BattleNode/Sessions/BattleSessionDispatchTests.cs +++ b/SVSim.UnitTests/BattleNode/Sessions/BattleSessionDispatchTests.cs @@ -21,7 +21,7 @@ public class BattleSessionDispatchTests var routes = s.ComputeFrames(a, NewEnvelope(NetworkBattleUri.Loaded)); var bs = (BattleStartBody)routes[0].Frame.Body; - Assert.That(bs.TurnState, Is.EqualTo(0), "A (first arriver) goes first."); + Assert.That(bs.TurnState, Is.EqualTo(TurnState.First), "A (first arriver) goes first."); } [Test] @@ -33,7 +33,7 @@ public class BattleSessionDispatchTests var routes = s.ComputeFrames(b, NewEnvelope(NetworkBattleUri.Loaded)); var bs = (BattleStartBody)routes[0].Frame.Body; - Assert.That(bs.TurnState, Is.EqualTo(1), "B (second arriver) goes second."); + Assert.That(bs.TurnState, Is.EqualTo(TurnState.Second), "B (second arriver) goes second."); } [Test] @@ -281,7 +281,7 @@ public class BattleSessionDispatchTests Assert.That(pb.OppoTargetList!.Count, Is.EqualTo(1)); Assert.That(pb.OppoTargetList[0].TargetIdx, Is.EqualTo(8)); - Assert.That(pb.OppoTargetList[0].IsSelf, Is.EqualTo(0)); + Assert.That(pb.OppoTargetList[0].IsSelf, Is.EqualTo(CardOwner.Opponent)); } [Test] @@ -316,7 +316,7 @@ public class BattleSessionDispatchTests Assert.That(pb.UList[0].IdxList, Is.EqualTo(new[] { 16, 22 })); Assert.That(pb.UList[0].From, Is.EqualTo(0)); Assert.That(pb.UList[0].To, Is.EqualTo(10)); - Assert.That(pb.UList[0].IsSelf, Is.EqualTo(1)); + Assert.That(pb.UList[0].IsSelf, Is.EqualTo(CardOwner.Self)); Assert.That(pb.UList[0].Skill, Is.EqualTo("37|36|0")); } @@ -807,7 +807,7 @@ public class BattleSessionDispatchTests Assert.That(routes[0].Target, Is.SameAs(b)); Assert.That(routes[0].Frame.Uri, Is.EqualTo(NetworkBattleUri.TurnEnd)); var body = (SVSim.BattleNode.Protocol.Bodies.TurnEndBody)routes[0].Frame.Body; - Assert.That(body.TurnState, Is.EqualTo(0)); + Assert.That(body.TurnState, Is.EqualTo(TurnState.First)); } [Test] diff --git a/SVSim.UnitTests/BattleNode/Sessions/KnownListBuilderTests.cs b/SVSim.UnitTests/BattleNode/Sessions/KnownListBuilderTests.cs index 3133844..4b601fb 100644 --- a/SVSim.UnitTests/BattleNode/Sessions/KnownListBuilderTests.cs +++ b/SVSim.UnitTests/BattleNode/Sessions/KnownListBuilderTests.cs @@ -1,4 +1,5 @@ using NUnit.Framework; +using SVSim.BattleNode.Protocol; using SVSim.BattleNode.Protocol.Bodies; using SVSim.BattleNode.Sessions.Dispatch; @@ -103,7 +104,7 @@ public class KnownListBuilderTests Assert.That(renamed, Is.Not.Null); Assert.That(renamed!.Count, Is.EqualTo(1)); Assert.That(renamed[0].TargetIdx, Is.EqualTo(8)); - Assert.That(renamed[0].IsSelf, Is.EqualTo(0)); + Assert.That(renamed[0].IsSelf, Is.EqualTo(CardOwner.Opponent)); } [Test] @@ -316,7 +317,7 @@ public class KnownListBuilderTests Assert.That(stripped![0].SelectCard, Is.Not.Null); Assert.That(stripped[0].SelectCard!.CardId, Is.EqualTo(new[] { 810041260L })); - Assert.That(stripped[0].SelectCard.Open, Is.EqualTo(1)); + Assert.That(stripped[0].SelectCard.Open, Is.EqualTo(ChoiceVisibility.Open)); } [Test] @@ -447,7 +448,7 @@ public class KnownListBuilderTests Assert.That(e.IdxList, Is.EqualTo(new[] { 16, 22 })); Assert.That(e.From, Is.EqualTo(0)); Assert.That(e.To, Is.EqualTo(10)); - Assert.That(e.IsSelf, Is.EqualTo(1)); + Assert.That(e.IsSelf, Is.EqualTo(CardOwner.Self)); Assert.That(e.Skill, Is.EqualTo("37|36|0")); Assert.That(e.CardId, Is.Null); Assert.That(e.Clan, Is.Null); @@ -479,7 +480,7 @@ public class KnownListBuilderTests Assert.That(e.Cost, Is.EqualTo(2)); Assert.That(e.SkillKeyCardIdx, Is.EqualTo(new[] { 7 })); Assert.That(e.RandomTargetIdx, Is.EqualTo(new[] { 2, 3 })); - Assert.That(e.IsInvoke, Is.EqualTo(1)); + Assert.That(e.IsInvoke, Is.True); Assert.That(e.AttachTarget, Is.EqualTo("12,13")); } @@ -496,7 +497,7 @@ public class KnownListBuilderTests Assert.That(relayed!.Count, Is.EqualTo(2)); Assert.That(relayed[0].Skill, Is.EqualTo("a")); Assert.That(relayed[1].Skill, Is.EqualTo("b")); - Assert.That(relayed[1].IsSelf, Is.EqualTo(0)); + Assert.That(relayed[1].IsSelf, Is.EqualTo(CardOwner.Opponent)); } [Test]