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:
@@ -10,6 +10,11 @@ namespace SVSim.BattleNode.Bridge;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class MatchingBridge : IMatchingBridge
|
public sealed class MatchingBridge : IMatchingBridge
|
||||||
{
|
{
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
private const int BattleIdHalfDigits = 6;
|
||||||
|
private const int BattleIdHalfExclusiveMax = 1_000_000; // 10^BattleIdHalfDigits
|
||||||
|
|
||||||
private readonly IBattleSessionStore _store;
|
private readonly IBattleSessionStore _store;
|
||||||
private readonly BattleNodeOptions _options;
|
private readonly BattleNodeOptions _options;
|
||||||
|
|
||||||
@@ -23,12 +28,13 @@ public sealed class MatchingBridge : IMatchingBridge
|
|||||||
{
|
{
|
||||||
ValidateContract(p1, p2, type);
|
ValidateContract(p1, p2, type);
|
||||||
|
|
||||||
// 12-digit decimal battle id mirrors the captures (e.g. "975695075012").
|
// Decimal battle id mirrors the captures (e.g. "975695075012"): two unbiased
|
||||||
// Two unbiased 6-digit draws concatenated — RandomNumberGenerator.GetInt32 uses
|
// BattleIdHalfDigits-wide draws concatenated. RandomNumberGenerator.GetInt32 uses
|
||||||
// rejection sampling so the result is uniform on [0, 10^6).
|
// rejection sampling so each half is uniform on [0, BattleIdHalfExclusiveMax).
|
||||||
var hi = RandomNumberGenerator.GetInt32(0, 1_000_000);
|
var hi = RandomNumberGenerator.GetInt32(0, BattleIdHalfExclusiveMax);
|
||||||
var lo = RandomNumberGenerator.GetInt32(0, 1_000_000);
|
var lo = RandomNumberGenerator.GetInt32(0, BattleIdHalfExclusiveMax);
|
||||||
var battleId = $"{hi:D6}{lo:D6}";
|
var halfFormat = "D" + BattleIdHalfDigits;
|
||||||
|
var battleId = hi.ToString(halfFormat) + lo.ToString(halfFormat);
|
||||||
|
|
||||||
_store.RegisterPending(new PendingBattle(battleId, type, p1, p2));
|
_store.RegisterPending(new PendingBattle(battleId, type, p1, p2));
|
||||||
return new PendingMatch(battleId, _options.NodeServerUrl);
|
return new PendingMatch(battleId, _options.NodeServerUrl);
|
||||||
|
|||||||
@@ -33,6 +33,15 @@ namespace SVSim.BattleNode.Hosting;
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public sealed class BattleNodeWebSocketHandler
|
public sealed class BattleNodeWebSocketHandler
|
||||||
{
|
{
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
private const string BattleIdCredential = "BattleId";
|
||||||
|
private const string ViewerIdCredential = "viewerId";
|
||||||
|
|
||||||
|
/// <summary>Grace period for the close handshake on a bail-out path. A fresh, short timeout —
|
||||||
|
/// <c>ctx.RequestAborted</c> may already be canceled by the path that decided to bail.</summary>
|
||||||
|
private static readonly TimeSpan PoliteCloseTimeout = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
private readonly IBattleSessionStore _store;
|
private readonly IBattleSessionStore _store;
|
||||||
private readonly IWaitingRoom _waitingRoom;
|
private readonly IWaitingRoom _waitingRoom;
|
||||||
private readonly BattleNodeOptions _options;
|
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
|
// 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
|
// therefore send BattleId/viewerId as headers; the integration test sends them as
|
||||||
// query params for convenience. Check headers first, fall back to query.
|
// query params for convenience. Check headers first, fall back to query.
|
||||||
var battleId = ReadCredential(ctx, "BattleId");
|
var battleId = ReadCredential(ctx, BattleIdCredential);
|
||||||
var encryptedViewerId = ReadCredential(ctx, "viewerId");
|
var encryptedViewerId = ReadCredential(ctx, ViewerIdCredential);
|
||||||
if (string.IsNullOrEmpty(battleId) || string.IsNullOrEmpty(encryptedViewerId))
|
if (string.IsNullOrEmpty(battleId) || string.IsNullOrEmpty(encryptedViewerId))
|
||||||
{
|
{
|
||||||
_log.LogWarning("WS upgrade missing BattleId or viewerId (header or query).");
|
_log.LogWarning("WS upgrade missing BattleId or viewerId (header or query).");
|
||||||
@@ -222,9 +231,7 @@ public sealed class BattleNodeWebSocketHandler
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task TryPoliteCloseAsync(WebSocket ws, string reason, string battleId)
|
private async Task TryPoliteCloseAsync(WebSocket ws, string reason, string battleId)
|
||||||
{
|
{
|
||||||
// Use a fresh, short timeout — ctx.RequestAborted may already be canceled by the
|
using var cts = new CancellationTokenSource(PoliteCloseTimeout);
|
||||||
// path that decided to bail out, which would skip the close immediately.
|
|
||||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ws.State == WebSocketState.Open)
|
if (ws.State == WebSocketState.Open)
|
||||||
|
|||||||
@@ -26,4 +26,9 @@ internal static class BattleFrameDefaults
|
|||||||
/// the client's <c>JudgeOperation</c> doesn't read it.
|
/// the client's <c>JudgeOperation</c> doesn't read it.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public const int OpponentJudgeSpin = 100;
|
public const int OpponentJudgeSpin = 100;
|
||||||
|
|
||||||
|
/// <summary>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.</summary>
|
||||||
|
public const int DeterministicTurnSpin = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ public static class ServerBattleFrames
|
|||||||
EmblemId: selfCtx.EmblemId,
|
EmblemId: selfCtx.EmblemId,
|
||||||
DegreeId: selfCtx.DegreeId,
|
DegreeId: selfCtx.DegreeId,
|
||||||
FieldId: selfCtx.FieldId,
|
FieldId: selfCtx.FieldId,
|
||||||
IsOfficial: selfCtx.IsOfficial,
|
IsOfficial: selfCtx.IsOfficial != 0,
|
||||||
OppoId: oppoViewerId,
|
OppoId: oppoViewerId,
|
||||||
Seed: seed),
|
Seed: seed),
|
||||||
OppoInfo: new MatchedOppoInfo(
|
OppoInfo: new MatchedOppoInfo(
|
||||||
@@ -43,7 +43,7 @@ public static class ServerBattleFrames
|
|||||||
EmblemId: oppoCtx.EmblemId,
|
EmblemId: oppoCtx.EmblemId,
|
||||||
DegreeId: oppoCtx.DegreeId,
|
DegreeId: oppoCtx.DegreeId,
|
||||||
FieldId: oppoCtx.FieldId,
|
FieldId: oppoCtx.FieldId,
|
||||||
IsOfficial: oppoCtx.IsOfficial,
|
IsOfficial: oppoCtx.IsOfficial != 0,
|
||||||
OppoId: selfViewerId,
|
OppoId: selfViewerId,
|
||||||
Seed: seed,
|
Seed: seed,
|
||||||
OppoDeckCount: oppoCtx.SelfDeckCardIds.Count),
|
OppoDeckCount: oppoCtx.SelfDeckCardIds.Count),
|
||||||
@@ -51,10 +51,10 @@ public static class ServerBattleFrames
|
|||||||
bid: battleId);
|
bid: battleId);
|
||||||
|
|
||||||
public static MsgEnvelope BuildBattleStart(
|
public static MsgEnvelope BuildBattleStart(
|
||||||
MatchContext selfCtx, MatchContext oppoCtx, long selfViewerId, int turnState) =>
|
MatchContext selfCtx, MatchContext oppoCtx, long selfViewerId, TurnState turnState) =>
|
||||||
EnvelopeForPush(NetworkBattleUri.BattleStart,
|
EnvelopeForPush(NetworkBattleUri.BattleStart,
|
||||||
new BattleStartBody(
|
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,
|
BattleType: selfCtx.BattleType,
|
||||||
SelfInfo: new BattleStartSelfInfo(
|
SelfInfo: new BattleStartSelfInfo(
|
||||||
Rank: BattleFrameDefaults.PlayerRank,
|
Rank: BattleFrameDefaults.PlayerRank,
|
||||||
|
|||||||
@@ -2,6 +2,10 @@ using System.Text.Json.Serialization;
|
|||||||
|
|
||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
|
/// <summary>Gungnir keepalive push. <c>scs</c> = self connection status, <c>ocs</c> = opponent
|
||||||
|
/// connection status; both carry <see cref="WireConstants.OnlineStatus"/> ("ONLINE") in v1.
|
||||||
|
/// Intentionally has no <c>resultCode</c> — the client treats an absent resultCode on alive
|
||||||
|
/// frames as "no error" (the lone body without one).</summary>
|
||||||
public sealed record AlivePushBody(
|
public sealed record AlivePushBody(
|
||||||
[property: JsonPropertyName("scs")] string Scs,
|
[property: JsonPropertyName("scs")] string Scs,
|
||||||
[property: JsonPropertyName("ocs")] string Ocs) : IMsgBody;
|
[property: JsonPropertyName("ocs")] string Ocs) : IMsgBody;
|
||||||
|
|||||||
@@ -6,4 +6,4 @@ public sealed record BattleFinishBody(
|
|||||||
[property: JsonPropertyName("result")]
|
[property: JsonPropertyName("result")]
|
||||||
[property: JsonConverter(typeof(JsonNumberEnumConverter<BattleResult>))]
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<BattleResult>))]
|
||||||
BattleResult Result,
|
BattleResult Result,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ using System.Text.Json.Serialization;
|
|||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
public sealed record BattleStartBody(
|
public sealed record BattleStartBody(
|
||||||
[property: JsonPropertyName("turnState")] int TurnState,
|
[property: JsonPropertyName("turnState")]
|
||||||
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<TurnState>))] TurnState TurnState,
|
||||||
[property: JsonPropertyName("battleType")] int BattleType,
|
[property: JsonPropertyName("battleType")] int BattleType,
|
||||||
[property: JsonPropertyName("selfInfo")] BattleStartSelfInfo SelfInfo,
|
[property: JsonPropertyName("selfInfo")] BattleStartSelfInfo SelfInfo,
|
||||||
[property: JsonPropertyName("oppoInfo")] BattleStartOppoInfo OppoInfo,
|
[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(
|
public sealed record BattleStartSelfInfo(
|
||||||
[property: JsonPropertyName("rank")] string Rank,
|
[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
|
// 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.
|
// 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(
|
public sealed record BattleStartOppoInfo(
|
||||||
[property: JsonPropertyName("rank")] string Rank,
|
[property: JsonPropertyName("rank")] string Rank,
|
||||||
[property: JsonPropertyName("isMasterRank")] string IsMasterRank,
|
[property: JsonPropertyName("isMasterRank")] string IsMasterRank,
|
||||||
|
|||||||
@@ -5,4 +5,4 @@ namespace SVSim.BattleNode.Protocol.Bodies;
|
|||||||
public sealed record DealBody(
|
public sealed record DealBody(
|
||||||
[property: JsonPropertyName("self")] IReadOnlyList<PosIdx> Self,
|
[property: JsonPropertyName("self")] IReadOnlyList<PosIdx> Self,
|
||||||
[property: JsonPropertyName("oppo")] IReadOnlyList<PosIdx> Oppo,
|
[property: JsonPropertyName("oppo")] IReadOnlyList<PosIdx> Oppo,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ using System.Text.Json.Serialization;
|
|||||||
|
|
||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
|
/// <summary>Server-pushed Judge frame (turn-handover gate; reflected to the sender in PvP).
|
||||||
|
/// Same wire shape as <see cref="OpponentTurnStartBody"/> — kept distinct because they back
|
||||||
|
/// different frames/URIs.</summary>
|
||||||
public sealed record JudgeBody(
|
public sealed record JudgeBody(
|
||||||
[property: JsonPropertyName("spin")] int Spin,
|
[property: JsonPropertyName("spin")] int Spin,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ public sealed record MatchedBody(
|
|||||||
[property: JsonPropertyName("selfInfo")] MatchedSelfInfo SelfInfo,
|
[property: JsonPropertyName("selfInfo")] MatchedSelfInfo SelfInfo,
|
||||||
[property: JsonPropertyName("oppoInfo")] MatchedOppoInfo OppoInfo,
|
[property: JsonPropertyName("oppoInfo")] MatchedOppoInfo OppoInfo,
|
||||||
[property: JsonPropertyName("selfDeck")] IReadOnlyList<DeckCardRef> SelfDeck,
|
[property: JsonPropertyName("selfDeck")] IReadOnlyList<DeckCardRef> 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(
|
public sealed record MatchedSelfInfo(
|
||||||
[property: JsonPropertyName("country_code")] string CountryCode,
|
[property: JsonPropertyName("country_code")] string CountryCode,
|
||||||
[property: JsonPropertyName("userName")] string UserName,
|
[property: JsonPropertyName("userName")] string UserName,
|
||||||
@@ -15,7 +17,8 @@ public sealed record MatchedSelfInfo(
|
|||||||
[property: JsonPropertyName("emblemId")] string EmblemId,
|
[property: JsonPropertyName("emblemId")] string EmblemId,
|
||||||
[property: JsonPropertyName("degreeId")] string DegreeId,
|
[property: JsonPropertyName("degreeId")] string DegreeId,
|
||||||
[property: JsonPropertyName("fieldId")] int FieldId,
|
[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("oppoId")] long OppoId,
|
||||||
[property: JsonPropertyName("seed")] long Seed);
|
[property: JsonPropertyName("seed")] long Seed);
|
||||||
|
|
||||||
@@ -26,7 +29,8 @@ public sealed record MatchedOppoInfo(
|
|||||||
[property: JsonPropertyName("emblemId")] string EmblemId,
|
[property: JsonPropertyName("emblemId")] string EmblemId,
|
||||||
[property: JsonPropertyName("degreeId")] string DegreeId,
|
[property: JsonPropertyName("degreeId")] string DegreeId,
|
||||||
[property: JsonPropertyName("fieldId")] int FieldId,
|
[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("oppoId")] long OppoId,
|
||||||
[property: JsonPropertyName("seed")] long Seed,
|
[property: JsonPropertyName("seed")] long Seed,
|
||||||
[property: JsonPropertyName("oppoDeckCount")] int OppoDeckCount);
|
[property: JsonPropertyName("oppoDeckCount")] int OppoDeckCount);
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ using System.Text.Json.Serialization;
|
|||||||
|
|
||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
|
/// <summary>Server-pushed opponent-turn-open frame (relayed to the non-active player).
|
||||||
|
/// Same wire shape as <see cref="JudgeBody"/> — kept distinct because they back different
|
||||||
|
/// frames/URIs.</summary>
|
||||||
public sealed record OpponentTurnStartBody(
|
public sealed record OpponentTurnStartBody(
|
||||||
[property: JsonPropertyName("spin")] int Spin,
|
[property: JsonPropertyName("spin")] int Spin,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ public sealed record KeyActionEntry(
|
|||||||
/// Only emitted for the open:1 pass-through case (open:0 strips the whole <c>selectCard</c>).</summary>
|
/// Only emitted for the open:1 pass-through case (open:0 strips the whole <c>selectCard</c>).</summary>
|
||||||
public sealed record SelectCardEntry(
|
public sealed record SelectCardEntry(
|
||||||
[property: JsonPropertyName("cardId")] IReadOnlyList<long> CardId,
|
[property: JsonPropertyName("cardId")] IReadOnlyList<long> CardId,
|
||||||
[property: JsonPropertyName("open")] int Open);
|
[property: JsonPropertyName("open")]
|
||||||
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<ChoiceVisibility>))] ChoiceVisibility Open);
|
||||||
|
|
||||||
/// <summary>One revealed card in a <c>knownList</c>. Vanilla slice fills cardId from the sender's
|
/// <summary>One revealed card in a <c>knownList</c>. Vanilla slice fills cardId from the sender's
|
||||||
/// deck map and leaves spellboost 0 / attachTarget "" (cost/clan/tribe deferred to the card-master
|
/// 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).</summary>
|
/// verbatim — no perspective flip (bullet-3 audit F2).</summary>
|
||||||
public sealed record OppoTargetEntry(
|
public sealed record OppoTargetEntry(
|
||||||
[property: JsonPropertyName("targetIdx")] int TargetIdx,
|
[property: JsonPropertyName("targetIdx")] int TargetIdx,
|
||||||
[property: JsonPropertyName("isSelf")] int IsSelf);
|
[property: JsonPropertyName("isSelf")]
|
||||||
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<CardOwner>))] CardOwner IsSelf);
|
||||||
|
|
||||||
/// <summary>One entry in a relayed <c>uList</c> (the unapproved-movement list) — a skill-driven
|
/// <summary>One entry in a relayed <c>uList</c> (the unapproved-movement list) — a skill-driven
|
||||||
/// card movement (fetch / search / summon-from-deck / discard-reveal) the node forwards VERBATIM
|
/// 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<int> IdxList,
|
[property: JsonPropertyName("idxList")] IReadOnlyList<int> IdxList,
|
||||||
[property: JsonPropertyName("from")] int From,
|
[property: JsonPropertyName("from")] int From,
|
||||||
[property: JsonPropertyName("to")] int To,
|
[property: JsonPropertyName("to")] int To,
|
||||||
[property: JsonPropertyName("isSelf")] int IsSelf,
|
[property: JsonPropertyName("isSelf")]
|
||||||
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<CardOwner>))] CardOwner IsSelf,
|
||||||
[property: JsonPropertyName("skill")] string Skill,
|
[property: JsonPropertyName("skill")] string Skill,
|
||||||
[property: JsonPropertyName("cardId")] long? CardId = null,
|
[property: JsonPropertyName("cardId")] long? CardId = null,
|
||||||
[property: JsonPropertyName("clan")] int? Clan = null,
|
[property: JsonPropertyName("clan")] int? Clan = null,
|
||||||
[property: JsonPropertyName("cost")] int? Cost = null,
|
[property: JsonPropertyName("cost")] int? Cost = null,
|
||||||
[property: JsonPropertyName("skillKeyCardIdx")] IReadOnlyList<int>? SkillKeyCardIdx = null,
|
[property: JsonPropertyName("skillKeyCardIdx")] IReadOnlyList<int>? SkillKeyCardIdx = null,
|
||||||
[property: JsonPropertyName("randomTargetIdx")] IReadOnlyList<int>? RandomTargetIdx = null,
|
[property: JsonPropertyName("randomTargetIdx")] IReadOnlyList<int>? RandomTargetIdx = null,
|
||||||
[property: JsonPropertyName("isInvoke")] int? IsInvoke = null,
|
[property: JsonPropertyName("isInvoke")]
|
||||||
|
[property: JsonConverter(typeof(NumericBoolJsonConverter))] bool? IsInvoke = null,
|
||||||
[property: JsonPropertyName("attachTarget")] string? AttachTarget = null);
|
[property: JsonPropertyName("attachTarget")] string? AttachTarget = null);
|
||||||
|
|||||||
@@ -7,4 +7,4 @@ public sealed record ReadyBody(
|
|||||||
[property: JsonPropertyName("oppo")] IReadOnlyList<PosIdx> Oppo,
|
[property: JsonPropertyName("oppo")] IReadOnlyList<PosIdx> Oppo,
|
||||||
[property: JsonPropertyName("idxChangeSeed")] int IdxChangeSeed,
|
[property: JsonPropertyName("idxChangeSeed")] int IdxChangeSeed,
|
||||||
[property: JsonPropertyName("spin")] int Spin,
|
[property: JsonPropertyName("spin")] int Spin,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -3,4 +3,4 @@ using System.Text.Json.Serialization;
|
|||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
public sealed record ResultCodeOnlyBody(
|
public sealed record ResultCodeOnlyBody(
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -4,4 +4,4 @@ namespace SVSim.BattleNode.Protocol.Bodies;
|
|||||||
|
|
||||||
public sealed record SwapResponseBody(
|
public sealed record SwapResponseBody(
|
||||||
[property: JsonPropertyName("self")] IReadOnlyList<PosIdx> Self,
|
[property: JsonPropertyName("self")] IReadOnlyList<PosIdx> Self,
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
@@ -3,5 +3,6 @@ using System.Text.Json.Serialization;
|
|||||||
namespace SVSim.BattleNode.Protocol.Bodies;
|
namespace SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
public sealed record TurnEndBody(
|
public sealed record TurnEndBody(
|
||||||
[property: JsonPropertyName("turnState")] int TurnState,
|
[property: JsonPropertyName("turnState")]
|
||||||
[property: JsonPropertyName("resultCode")] int ResultCode = 1) : IMsgBody;
|
[property: JsonConverter(typeof(JsonNumberEnumConverter<TurnState>))] TurnState TurnState,
|
||||||
|
[property: JsonPropertyName("resultCode")] int ResultCode = (int)ReceiveNodeResultCode.Success) : IMsgBody;
|
||||||
|
|||||||
17
SVSim.BattleNode/Protocol/CardOwner.cs
Normal file
17
SVSim.BattleNode/Protocol/CardOwner.cs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
namespace SVSim.BattleNode.Protocol;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wire value of the actor-relative <c>isSelf</c> flag on relayed lists (<c>targetList</c>,
|
||||||
|
/// <c>uList</c>): 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
|
||||||
|
/// <c>ConvertToInt(...) == 1</c> (<c>NetworkBattleReceiver.cs</c>), so it serializes as the
|
||||||
|
/// underlying int via <see cref="System.Text.Json.Serialization.JsonNumberEnumConverter{T}"/>.
|
||||||
|
/// </summary>
|
||||||
|
public enum CardOwner
|
||||||
|
{
|
||||||
|
/// <summary>Card belongs to the opponent of the sender.</summary>
|
||||||
|
Opponent = 0,
|
||||||
|
|
||||||
|
/// <summary>Card belongs to the sender.</summary>
|
||||||
|
Self = 1,
|
||||||
|
}
|
||||||
17
SVSim.BattleNode/Protocol/ChoiceVisibility.cs
Normal file
17
SVSim.BattleNode/Protocol/ChoiceVisibility.cs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
namespace SVSim.BattleNode.Protocol;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wire value of <c>open</c> on a choice/Discover <c>selectCard</c>: whether the pick is revealed.
|
||||||
|
/// The client emits it as <c>selectCardIsOpen ? 1 : 0</c> (<c>SendKeyActionDataManager.cs</c>);
|
||||||
|
/// the node uses it to decide whether to strip the pick for the opponent (<c>Hidden</c> = strip).
|
||||||
|
/// Serializes as the underlying int via
|
||||||
|
/// <see cref="System.Text.Json.Serialization.JsonNumberEnumConverter{T}"/>.
|
||||||
|
/// </summary>
|
||||||
|
public enum ChoiceVisibility
|
||||||
|
{
|
||||||
|
/// <summary>Hidden draw-to-hand pick — the chosen card stays secret until played.</summary>
|
||||||
|
Hidden = 0,
|
||||||
|
|
||||||
|
/// <summary>Visible board choice — the pick is revealed immediately.</summary>
|
||||||
|
Open = 1,
|
||||||
|
}
|
||||||
29
SVSim.BattleNode/Protocol/NumericBoolJsonConverter.cs
Normal file
29
SVSim.BattleNode/Protocol/NumericBoolJsonConverter.cs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace SVSim.BattleNode.Protocol;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes a <see cref="bool"/> as the wire's numeric 0/1. The client reads these flags via
|
||||||
|
/// <c>Convert.ToInt32</c> / <c>Convert.ToBoolean</c> (e.g. <c>isOfficial</c>, <c>isInvoke</c>) —
|
||||||
|
/// never as a JSON <c>true</c>/<c>false</c> token — so a real <c>bool</c> property must still emit
|
||||||
|
/// a number. Read accepts a JSON number (0 = false, non-zero = true) and, defensively, a
|
||||||
|
/// <c>true</c>/<c>false</c> token or a numeric string. Applied per-field via
|
||||||
|
/// <c>[JsonConverter(typeof(NumericBoolJsonConverter))]</c>; works on <c>bool?</c> too (System.Text.Json
|
||||||
|
/// wraps a <c>JsonConverter<bool></c> for the nullable case).
|
||||||
|
/// </summary>
|
||||||
|
public sealed class NumericBoolJsonConverter : JsonConverter<bool>
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
16
SVSim.BattleNode/Protocol/TurnState.cs
Normal file
16
SVSim.BattleNode/Protocol/TurnState.cs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
namespace SVSim.BattleNode.Protocol;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wire value of <c>turnState</c> on BattleStart / TurnEnd frames: which side acts first.
|
||||||
|
/// The client reads it via <c>Convert.ToInt32</c> (<c>RealTimeNetworkAgent.cs</c> "turnState"
|
||||||
|
/// case) into <c>NetworkUserInfoData.TurnState</c>, so it serializes as the underlying int via
|
||||||
|
/// <see cref="System.Text.Json.Serialization.JsonNumberEnumConverter{T}"/>.
|
||||||
|
/// </summary>
|
||||||
|
public enum TurnState
|
||||||
|
{
|
||||||
|
/// <summary>This side takes the first turn.</summary>
|
||||||
|
First = 0,
|
||||||
|
|
||||||
|
/// <summary>This side takes the second turn.</summary>
|
||||||
|
Second = 1,
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
namespace SVSim.BattleNode.Reliability;
|
namespace SVSim.BattleNode.Reliability;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 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 <see cref="Protocol.Bodies.AlivePushBody"/>).
|
||||||
|
/// The timer/loop that drives <see cref="EmitInterval"/> emits lives on
|
||||||
/// BattleSession; this class is just the pure body-shape factory.
|
/// BattleSession; this class is just the pure body-shape factory.
|
||||||
/// v1 always reports scs/ocs=ONLINE — real disconnect detection is deferred. The push
|
/// v1 always reports scs/ocs=ONLINE — real disconnect detection is deferred. The push
|
||||||
/// body itself is constructed inline in BattleSession.HandleAliveEventAsync using
|
/// body itself is constructed inline in BattleSession.HandleAliveEventAsync using
|
||||||
|
|||||||
@@ -9,7 +9,11 @@ namespace SVSim.BattleNode.Reliability;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class OutboundSequencer
|
public sealed class OutboundSequencer
|
||||||
{
|
{
|
||||||
private long _next = 1;
|
/// <summary>First playSeq assigned. Starts at 1, not 0 — 0 is reserved for no-stock /
|
||||||
|
/// unsequenced pushes (which carry a null PlaySeq via <see cref="WrapNoStock"/>).</summary>
|
||||||
|
private const long FirstPlaySeq = 1;
|
||||||
|
|
||||||
|
private long _next = FirstPlaySeq;
|
||||||
private readonly Dictionary<long, MsgEnvelope> _archive = new();
|
private readonly Dictionary<long, MsgEnvelope> _archive = new();
|
||||||
|
|
||||||
public IReadOnlyDictionary<long, MsgEnvelope> Archive => _archive;
|
public IReadOnlyDictionary<long, MsgEnvelope> Archive => _archive;
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ internal static class BattleFrames
|
|||||||
Cat: EmitCategory.Battle,
|
Cat: EmitCategory.Battle,
|
||||||
PubSeq: null,
|
PubSeq: null,
|
||||||
PlaySeq: null,
|
PlaySeq: null,
|
||||||
Body: new TurnEndBody(TurnState: 0));
|
Body: new TurnEndBody(TurnState: TurnState.First));
|
||||||
|
|
||||||
internal static MsgEnvelope BuildJudgeBroadcast() => new(
|
internal static MsgEnvelope BuildJudgeBroadcast() => new(
|
||||||
NetworkBattleUri.Judge,
|
NetworkBattleUri.Judge,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using SVSim.BattleNode.Lifecycle;
|
||||||
using SVSim.BattleNode.Protocol;
|
using SVSim.BattleNode.Protocol;
|
||||||
using SVSim.BattleNode.Protocol.Bodies;
|
using SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ internal sealed class JudgeHandler : IFrameHandler
|
|||||||
// battleCode is dropped; spin=0 for the deterministic-turn slice.
|
// battleCode is dropped; spin=0 for the deterministic-turn slice.
|
||||||
if (ctx.Type == BattleType.Pvp && ctx.BothAfterReady())
|
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) };
|
return new[] { new DispatchRoute(ctx.From, frame, false) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ internal sealed class LoadedHandler : IFrameHandler
|
|||||||
// case 6: general — BattleStart (per-perspective) + Deal to the sender.
|
// case 6: general — BattleStart (per-perspective) + Deal to the sender.
|
||||||
if (ctx.SenderPhase == BattleSessionPhase.AwaitingLoaded)
|
if (ctx.SenderPhase == BattleSessionPhase.AwaitingLoaded)
|
||||||
{
|
{
|
||||||
// A goes first deterministically (turnState 0); B goes second (turnState 1).
|
// A goes first deterministically; B goes second.
|
||||||
var turnState = ReferenceEquals(ctx.From, ctx.A) ? 0 : 1;
|
var turnState = ReferenceEquals(ctx.From, ctx.A) ? TurnState.First : TurnState.Second;
|
||||||
var r = new List<DispatchRoute>
|
var r = new List<DispatchRoute>
|
||||||
{
|
{
|
||||||
new(ctx.From, ServerBattleFrames.BuildBattleStart(
|
new(ctx.From, ServerBattleFrames.BuildBattleStart(
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ internal sealed class TurnEndHandler : IFrameHandler
|
|||||||
// Opponent sees {turnState}; receiving TurnEnd drives ITS SendJudge (handover gate):
|
// Opponent sees {turnState}; receiving TurnEnd drives ITS SendJudge (handover gate):
|
||||||
// the opponent (the turn taker-over) then sends a Judge, which JudgeHandler reflects
|
// 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.
|
// 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 new[] { new DispatchRoute(ctx.Other, te, false) };
|
||||||
}
|
}
|
||||||
return Array.Empty<DispatchRoute>(); // Pvp-not-both-ready → drop (Bot already returned above)
|
return Array.Empty<DispatchRoute>(); // Pvp-not-both-ready → drop (Bot already returned above)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using SVSim.BattleNode.Lifecycle;
|
||||||
using SVSim.BattleNode.Protocol;
|
using SVSim.BattleNode.Protocol;
|
||||||
using SVSim.BattleNode.Protocol.Bodies;
|
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.
|
// (spin=0 for the deterministic-turn slice) and self-generates its turn-open.
|
||||||
if (ctx.Type == BattleType.Pvp && ctx.BothAfterReady())
|
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) };
|
return new[] { new DispatchRoute(ctx.Other, frame, false) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using SVSim.BattleNode.Protocol;
|
||||||
using SVSim.BattleNode.Protocol.Bodies;
|
using SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
namespace SVSim.BattleNode.Sessions.Dispatch;
|
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)
|
if (d.TryGetValue("selectCard", out var scRaw) && scRaw is IDictionary<string, object?> sc)
|
||||||
{
|
{
|
||||||
sc.TryGetValue("open", out var openRaw);
|
sc.TryGetValue("open", out var openRaw);
|
||||||
var open = (int)AsLong(openRaw);
|
var open = (ChoiceVisibility)(int)AsLong(openRaw);
|
||||||
if (open != 0 && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable<object?> ids)
|
if (open != ChoiceVisibility.Hidden && sc.TryGetValue("cardId", out var idsRaw) && idsRaw is IEnumerable<object?> ids)
|
||||||
selectCard = new SelectCardEntry(ids.Select(AsLong).ToList(), open);
|
selectCard = new SelectCardEntry(ids.Select(AsLong).ToList(), open);
|
||||||
}
|
}
|
||||||
result.Add(new KeyActionEntry(type, cardId, selectCard));
|
result.Add(new KeyActionEntry(type, cardId, selectCard));
|
||||||
@@ -217,7 +218,7 @@ internal static class KnownListBuilder
|
|||||||
d.TryGetValue("isSelf", out var isSelfRaw);
|
d.TryGetValue("isSelf", out var isSelfRaw);
|
||||||
result.Add(new OppoTargetEntry(
|
result.Add(new OppoTargetEntry(
|
||||||
TargetIdx: (int)AsLong(targetIdxRaw),
|
TargetIdx: (int)AsLong(targetIdxRaw),
|
||||||
IsSelf: (int)AsLong(isSelfRaw)));
|
IsSelf: (CardOwner)(int)AsLong(isSelfRaw)));
|
||||||
}
|
}
|
||||||
return result.Count == 0 ? null : result;
|
return result.Count == 0 ? null : result;
|
||||||
}
|
}
|
||||||
@@ -247,14 +248,14 @@ internal static class KnownListBuilder
|
|||||||
IdxList: AsIntList(idxRaw) ?? new List<int>(),
|
IdxList: AsIntList(idxRaw) ?? new List<int>(),
|
||||||
From: (int)AsLong(fromRaw),
|
From: (int)AsLong(fromRaw),
|
||||||
To: (int)AsLong(toRaw),
|
To: (int)AsLong(toRaw),
|
||||||
IsSelf: (int)AsLong(isSelfRaw),
|
IsSelf: (CardOwner)(int)AsLong(isSelfRaw),
|
||||||
Skill: skillRaw as string ?? "",
|
Skill: skillRaw as string ?? "",
|
||||||
CardId: d.TryGetValue("cardId", out var c) ? AsLong(c) : null,
|
CardId: d.TryGetValue("cardId", out var c) ? AsLong(c) : null,
|
||||||
Clan: d.TryGetValue("clan", out var cl) ? (int)AsLong(cl) : null,
|
Clan: d.TryGetValue("clan", out var cl) ? (int)AsLong(cl) : null,
|
||||||
Cost: d.TryGetValue("cost", out var co) ? (int)AsLong(co) : null,
|
Cost: d.TryGetValue("cost", out var co) ? (int)AsLong(co) : null,
|
||||||
SkillKeyCardIdx: AsIntList(d.TryGetValue("skillKeyCardIdx", out var sk) ? sk : null),
|
SkillKeyCardIdx: AsIntList(d.TryGetValue("skillKeyCardIdx", out var sk) ? sk : null),
|
||||||
RandomTargetIdx: AsIntList(d.TryGetValue("randomTargetIdx", out var rt) ? rt : 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));
|
AttachTarget: d.TryGetValue("attachTarget", out var at) ? at as string : null));
|
||||||
}
|
}
|
||||||
return result.Count == 0 ? null : result;
|
return result.Count == 0 ? null : result;
|
||||||
|
|||||||
@@ -14,22 +14,25 @@ namespace SVSim.BattleNode.Sessions.Participants;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class NoOpBotParticipant : IBattleParticipant
|
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 long ViewerId => ServerBattleFrames.FakeOpponentViewerId;
|
||||||
public MatchContext Context { get; } = new(
|
public MatchContext Context { get; } = new(
|
||||||
SelfDeckCardIds: Array.Empty<long>(),
|
SelfDeckCardIds: Array.Empty<long>(),
|
||||||
ClassId: "0", CharaId: "0", CardMasterName: "card_master_node_10015",
|
ClassId: "0", CharaId: "0", CardMasterName: BotCardMasterName,
|
||||||
CountryCode: "", UserName: "Bot", SleeveId: "0",
|
CountryCode: "", UserName: "Bot", SleeveId: "0",
|
||||||
EmblemId: "0", DegreeId: "0", FieldId: 0, IsOfficial: 0,
|
EmblemId: "0", DegreeId: "0", FieldId: 0, IsOfficial: 0,
|
||||||
BattleType: 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;
|
public event Func<MsgEnvelope, CancellationToken, Task>? FrameEmitted;
|
||||||
|
#pragma warning restore CS0067
|
||||||
|
|
||||||
public Task PushAsync(MsgEnvelope envelope, bool noStock, CancellationToken ct) => Task.CompletedTask;
|
public Task PushAsync(MsgEnvelope envelope, bool noStock, CancellationToken ct) => Task.CompletedTask;
|
||||||
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
|
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
|
||||||
public Task TerminateAsync(BattleFinishReason reason) => Task.CompletedTask;
|
public Task TerminateAsync(BattleFinishReason reason) => Task.CompletedTask;
|
||||||
public ValueTask DisposeAsync() => ValueTask.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);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,24 @@ internal interface IHasHandshakePhase
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
|
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 WebSocket _ws;
|
||||||
private readonly ILogger<RealParticipant> _log;
|
private readonly ILogger<RealParticipant> _log;
|
||||||
private readonly bool _diagnosticLogging;
|
private readonly bool _diagnosticLogging;
|
||||||
@@ -100,7 +118,7 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
|
|||||||
_sessionCt = cancellation;
|
_sessionCt = cancellation;
|
||||||
await SendEioOpenAsync(cancellation);
|
await SendEioOpenAsync(cancellation);
|
||||||
|
|
||||||
var buffer = new byte[8192];
|
var buffer = new byte[ReceiveBufferBytes];
|
||||||
var pendingAttachments = new List<byte[]>();
|
var pendingAttachments = new List<byte[]>();
|
||||||
SocketIoFrame? pendingFrame = null;
|
SocketIoFrame? pendingFrame = null;
|
||||||
string exitReason = "loop-condition-false";
|
string exitReason = "loop-condition-false";
|
||||||
@@ -126,7 +144,7 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
|
|||||||
}
|
}
|
||||||
if (eio.Type == EngineIoPacketType.Ping)
|
if (eio.Type == EngineIoPacketType.Ping)
|
||||||
{
|
{
|
||||||
await SendTextAsync("3", cancellation);
|
await SendTextAsync(((int)EngineIoPacketType.Pong).ToString(), cancellation);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (eio.Type != EngineIoPacketType.Message) 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)
|
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 bytes = MsgPayloadCodec.Encode(env, key);
|
||||||
var sio = SocketIoFrame.BinaryEventWithAttachments(eventName, new[] { bytes });
|
var sio = SocketIoFrame.BinaryEventWithAttachments(eventName, new[] { bytes });
|
||||||
var (text, bins) = sio.Encode();
|
var (text, bins) = sio.Encode();
|
||||||
@@ -428,8 +446,9 @@ public sealed class RealParticipant : IBattleParticipant, IHasHandshakePhase
|
|||||||
|
|
||||||
private async Task SendEioOpenAsync(CancellationToken ct)
|
private async Task SendEioOpenAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
var sid = Guid.NewGuid().ToString("N").Substring(0, 16);
|
var sid = Guid.NewGuid().ToString("N").Substring(0, EngineIoSidLength);
|
||||||
var handshake = new EngineIoHandshake(sid, Array.Empty<string>(), 25000, 60000).ToJson();
|
var handshake = new EngineIoHandshake(
|
||||||
|
sid, Array.Empty<string>(), EngineIoPingIntervalMs, EngineIoPingTimeoutMs).ToJson();
|
||||||
await SendTextAsync($"0{handshake}", ct);
|
await SendTextAsync($"0{handshake}", ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,12 @@ namespace SVSim.BattleNode.Wire;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class NodeCrypto
|
public static class NodeCrypto
|
||||||
{
|
{
|
||||||
|
/// <summary>Length of the ASCII key, in chars (AES-256 = 32 bytes = 32 ASCII chars).</summary>
|
||||||
|
private const int KeyLength = 32;
|
||||||
|
|
||||||
|
/// <summary>IV length, in chars. The node derives the IV from the first half of the key.</summary>
|
||||||
|
private const int IvLength = KeyLength / 2;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Generate a fresh 32-char key for server-initiated encryption.
|
/// Generate a fresh 32-char key for server-initiated encryption.
|
||||||
/// Calls <paramref name="randHexDigit"/> 32 times; the result is masked with
|
/// Calls <paramref name="randHexDigit"/> 32 times; the result is masked with
|
||||||
@@ -27,20 +33,20 @@ public static class NodeCrypto
|
|||||||
/// </remarks>
|
/// </remarks>
|
||||||
public static string GenerateKey(Func<int> randHexDigit)
|
public static string GenerateKey(Func<int> randHexDigit)
|
||||||
{
|
{
|
||||||
var sb = new StringBuilder(32);
|
var sb = new StringBuilder(KeyLength);
|
||||||
for (var i = 0; i < 32; i++)
|
for (var i = 0; i < KeyLength; i++)
|
||||||
{
|
{
|
||||||
sb.Append((randHexDigit() & 0xF).ToString("x"));
|
sb.Append((randHexDigit() & 0xF).ToString("x"));
|
||||||
}
|
}
|
||||||
var ascii = Encoding.ASCII.GetBytes(sb.ToString());
|
var ascii = Encoding.ASCII.GetBytes(sb.ToString());
|
||||||
return Convert.ToBase64String(ascii).Substring(0, 32);
|
return Convert.ToBase64String(ascii).Substring(0, KeyLength);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Encrypt: returns key + base64(AES-256-CBC(plain)).</summary>
|
/// <summary>Encrypt: returns key + base64(AES-256-CBC(plain)).</summary>
|
||||||
public static string EncryptForNode(string plaintext, string key)
|
public static string EncryptForNode(string plaintext, string key)
|
||||||
{
|
{
|
||||||
if (key.Length != 32)
|
if (key.Length != KeyLength)
|
||||||
throw new ArgumentException($"Key must be exactly 32 chars, got {key.Length}", nameof(key));
|
throw new ArgumentException($"Key must be exactly {KeyLength} chars, got {key.Length}", nameof(key));
|
||||||
using var aes = BuildAes(key);
|
using var aes = BuildAes(key);
|
||||||
using var encryptor = aes.CreateEncryptor();
|
using var encryptor = aes.CreateEncryptor();
|
||||||
var plainBytes = Encoding.UTF8.GetBytes(plaintext);
|
var plainBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||||
@@ -51,10 +57,10 @@ public static class NodeCrypto
|
|||||||
/// <summary>Decrypt: input[0..32] is key, input[32..] is base64(ciphertext).</summary>
|
/// <summary>Decrypt: input[0..32] is key, input[32..] is base64(ciphertext).</summary>
|
||||||
public static string DecryptForNode(string encrypted)
|
public static string DecryptForNode(string encrypted)
|
||||||
{
|
{
|
||||||
if (encrypted.Length < 32)
|
if (encrypted.Length < KeyLength)
|
||||||
throw new ArgumentException("Encrypted blob is shorter than the 32-char key prefix", nameof(encrypted));
|
throw new ArgumentException($"Encrypted blob is shorter than the {KeyLength}-char key prefix", nameof(encrypted));
|
||||||
var key = encrypted.Substring(0, 32);
|
var key = encrypted.Substring(0, KeyLength);
|
||||||
var cipherBytes = Convert.FromBase64String(encrypted.Substring(32));
|
var cipherBytes = Convert.FromBase64String(encrypted.Substring(KeyLength));
|
||||||
using var aes = BuildAes(key);
|
using var aes = BuildAes(key);
|
||||||
using var decryptor = aes.CreateDecryptor();
|
using var decryptor = aes.CreateDecryptor();
|
||||||
var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
|
var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
|
||||||
@@ -62,9 +68,10 @@ public static class NodeCrypto
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Configure an AES-256-CBC instance with the node's IV derivation (first 16 chars
|
/// Configure an AES-256-CBC instance with the node's IV derivation (first
|
||||||
/// of the key, UTF-8). Callers own disposal. Assumes <paramref name="key"/> is the
|
/// <see cref="IvLength"/> chars of the key, UTF-8). Callers own disposal. Assumes
|
||||||
/// 32-char ASCII key the encrypt / decrypt path has already validated.
|
/// <paramref name="key"/> is the <see cref="KeyLength"/>-char ASCII key the encrypt /
|
||||||
|
/// decrypt path has already validated.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static Aes BuildAes(string key)
|
private static Aes BuildAes(string key)
|
||||||
{
|
{
|
||||||
@@ -73,7 +80,7 @@ public static class NodeCrypto
|
|||||||
aes.Mode = CipherMode.CBC;
|
aes.Mode = CipherMode.CBC;
|
||||||
aes.Padding = PaddingMode.PKCS7;
|
aes.Padding = PaddingMode.PKCS7;
|
||||||
aes.Key = Encoding.UTF8.GetBytes(key);
|
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;
|
return aes;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,15 +65,15 @@ public class ServerBattleFramesTests
|
|||||||
Assert.That(body.SelfInfo.EmblemId, Is.EqualTo("888"));
|
Assert.That(body.SelfInfo.EmblemId, Is.EqualTo("888"));
|
||||||
Assert.That(body.SelfInfo.DegreeId, Is.EqualTo("777"));
|
Assert.That(body.SelfInfo.DegreeId, Is.EqualTo("777"));
|
||||||
Assert.That(body.SelfInfo.FieldId, Is.EqualTo(42));
|
Assert.That(body.SelfInfo.FieldId, Is.EqualTo(42));
|
||||||
Assert.That(body.SelfInfo.IsOfficial, Is.EqualTo(1));
|
Assert.That(body.SelfInfo.IsOfficial, Is.True);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Test]
|
[Test]
|
||||||
public void BuildBattleStart_HasTurnStateZero_AndUsesContextBattleType()
|
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;
|
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));
|
Assert.That(body.BattleType, Is.EqualTo(11));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +87,7 @@ public class ServerBattleFramesTests
|
|||||||
BattleType = 42,
|
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;
|
var body = (BattleStartBody)env.Body;
|
||||||
|
|
||||||
Assert.That(body.SelfInfo.ClassId, Is.EqualTo("7"));
|
Assert.That(body.SelfInfo.ClassId, Is.EqualTo("7"));
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ public class TypedBodyWireShapeTests
|
|||||||
[Test]
|
[Test]
|
||||||
public void BuildBattleStart_SerializesAllWireKeysAndPreservesBattlePointAsymmetry()
|
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 json = MsgEnvelope.ToJson(env);
|
||||||
var node = JsonNode.Parse(json)!.AsObject();
|
var node = JsonNode.Parse(json)!.AsObject();
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Nodes;
|
using System.Text.Json.Nodes;
|
||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
|
using SVSim.BattleNode.Protocol;
|
||||||
using SVSim.BattleNode.Protocol.Bodies;
|
using SVSim.BattleNode.Protocol.Bodies;
|
||||||
|
|
||||||
namespace SVSim.UnitTests.BattleNode.Protocol.Bodies;
|
namespace SVSim.UnitTests.BattleNode.Protocol.Bodies;
|
||||||
@@ -12,7 +13,7 @@ public class BattleStartBodyTests
|
|||||||
public void Serializes_TopLevelFields_WithCorrectWireKeys()
|
public void Serializes_TopLevelFields_WithCorrectWireKeys()
|
||||||
{
|
{
|
||||||
var body = new BattleStartBody(
|
var body = new BattleStartBody(
|
||||||
TurnState: 0, BattleType: 11,
|
TurnState: TurnState.First, BattleType: 11,
|
||||||
SelfInfo: new BattleStartSelfInfo("10", "6270", "1", "1", "card_master_node_10015"),
|
SelfInfo: new BattleStartSelfInfo("10", "6270", "1", "1", "card_master_node_10015"),
|
||||||
OppoInfo: new BattleStartOppoInfo("1", "0", 0, "0", "8", "8", "card_master_node_10015"));
|
OppoInfo: new BattleStartOppoInfo("1", "0", 0, "0", "8", "8", "card_master_node_10015"));
|
||||||
|
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ public class MatchedBodyTests
|
|||||||
SelfInfo: new MatchedSelfInfo(
|
SelfInfo: new MatchedSelfInfo(
|
||||||
CountryCode: "KOR", UserName: "Player", SleeveId: "3000011",
|
CountryCode: "KOR", UserName: "Player", SleeveId: "3000011",
|
||||||
EmblemId: "701441011", DegreeId: "300003", FieldId: 43,
|
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(
|
OppoInfo: new MatchedOppoInfo(
|
||||||
CountryCode: "JPN", UserName: "Opponent", SleeveId: "704141010",
|
CountryCode: "JPN", UserName: "Opponent", SleeveId: "704141010",
|
||||||
EmblemId: "400001100", DegreeId: "120027", FieldId: 5,
|
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) });
|
SelfDeck: new[] { new DeckCardRef(Idx: 1, CardId: 100011010L) });
|
||||||
|
|
||||||
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
||||||
@@ -40,8 +40,8 @@ public class MatchedBodyTests
|
|||||||
public void OppoInfo_HasOppoDeckCount_OnTheWire()
|
public void OppoInfo_HasOppoDeckCount_OnTheWire()
|
||||||
{
|
{
|
||||||
var body = new MatchedBody(
|
var body = new MatchedBody(
|
||||||
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L),
|
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L),
|
||||||
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L, OppoDeckCount: 30),
|
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L, OppoDeckCount: 30),
|
||||||
SelfDeck: System.Array.Empty<DeckCardRef>());
|
SelfDeck: System.Array.Empty<DeckCardRef>());
|
||||||
|
|
||||||
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
||||||
@@ -54,8 +54,8 @@ public class MatchedBodyTests
|
|||||||
public void SelfInfo_DoesNotHaveOppoDeckCount_OnTheWire()
|
public void SelfInfo_DoesNotHaveOppoDeckCount_OnTheWire()
|
||||||
{
|
{
|
||||||
var body = new MatchedBody(
|
var body = new MatchedBody(
|
||||||
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L),
|
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L),
|
||||||
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30),
|
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30),
|
||||||
SelfDeck: System.Array.Empty<DeckCardRef>());
|
SelfDeck: System.Array.Empty<DeckCardRef>());
|
||||||
|
|
||||||
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
var node = (JsonObject)JsonSerializer.SerializeToNode(body)!;
|
||||||
@@ -68,8 +68,8 @@ public class MatchedBodyTests
|
|||||||
public void ResultCode_DefaultsToOne_OnConstruction()
|
public void ResultCode_DefaultsToOne_OnConstruction()
|
||||||
{
|
{
|
||||||
var body = new MatchedBody(
|
var body = new MatchedBody(
|
||||||
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L),
|
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L),
|
||||||
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30),
|
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30),
|
||||||
SelfDeck: System.Array.Empty<DeckCardRef>());
|
SelfDeck: System.Array.Empty<DeckCardRef>());
|
||||||
|
|
||||||
Assert.That(body.ResultCode, Is.EqualTo(1));
|
Assert.That(body.ResultCode, Is.EqualTo(1));
|
||||||
@@ -81,8 +81,8 @@ public class MatchedBodyTests
|
|||||||
public void SelfDeck_SerializesAsArray_WithIdxAndCardIdKeys()
|
public void SelfDeck_SerializesAsArray_WithIdxAndCardIdKeys()
|
||||||
{
|
{
|
||||||
var body = new MatchedBody(
|
var body = new MatchedBody(
|
||||||
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,0,1L,1L),
|
SelfInfo: new MatchedSelfInfo("KOR","P","s","e","d",0,false,1L,1L),
|
||||||
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,0,1L,1L,30),
|
OppoInfo: new MatchedOppoInfo("JPN","O","s","e","d",0,false,1L,1L,30),
|
||||||
SelfDeck: new[]
|
SelfDeck: new[]
|
||||||
{
|
{
|
||||||
new DeckCardRef(Idx: 1, CardId: 100011010L),
|
new DeckCardRef(Idx: 1, CardId: 100011010L),
|
||||||
|
|||||||
@@ -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<Probe>("{\"flag\":1}", Options)!.Flag, Is.True);
|
||||||
|
Assert.That(JsonSerializer.Deserialize<Probe>("{\"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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ public class BattleSessionDispatchTests
|
|||||||
var routes = s.ComputeFrames(a, NewEnvelope(NetworkBattleUri.Loaded));
|
var routes = s.ComputeFrames(a, NewEnvelope(NetworkBattleUri.Loaded));
|
||||||
|
|
||||||
var bs = (BattleStartBody)routes[0].Frame.Body;
|
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]
|
[Test]
|
||||||
@@ -33,7 +33,7 @@ public class BattleSessionDispatchTests
|
|||||||
var routes = s.ComputeFrames(b, NewEnvelope(NetworkBattleUri.Loaded));
|
var routes = s.ComputeFrames(b, NewEnvelope(NetworkBattleUri.Loaded));
|
||||||
|
|
||||||
var bs = (BattleStartBody)routes[0].Frame.Body;
|
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]
|
[Test]
|
||||||
@@ -281,7 +281,7 @@ public class BattleSessionDispatchTests
|
|||||||
|
|
||||||
Assert.That(pb.OppoTargetList!.Count, Is.EqualTo(1));
|
Assert.That(pb.OppoTargetList!.Count, Is.EqualTo(1));
|
||||||
Assert.That(pb.OppoTargetList[0].TargetIdx, Is.EqualTo(8));
|
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]
|
[Test]
|
||||||
@@ -316,7 +316,7 @@ public class BattleSessionDispatchTests
|
|||||||
Assert.That(pb.UList[0].IdxList, Is.EqualTo(new[] { 16, 22 }));
|
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].From, Is.EqualTo(0));
|
||||||
Assert.That(pb.UList[0].To, Is.EqualTo(10));
|
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"));
|
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].Target, Is.SameAs(b));
|
||||||
Assert.That(routes[0].Frame.Uri, Is.EqualTo(NetworkBattleUri.TurnEnd));
|
Assert.That(routes[0].Frame.Uri, Is.EqualTo(NetworkBattleUri.TurnEnd));
|
||||||
var body = (SVSim.BattleNode.Protocol.Bodies.TurnEndBody)routes[0].Frame.Body;
|
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]
|
[Test]
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using NUnit.Framework;
|
using NUnit.Framework;
|
||||||
|
using SVSim.BattleNode.Protocol;
|
||||||
using SVSim.BattleNode.Protocol.Bodies;
|
using SVSim.BattleNode.Protocol.Bodies;
|
||||||
using SVSim.BattleNode.Sessions.Dispatch;
|
using SVSim.BattleNode.Sessions.Dispatch;
|
||||||
|
|
||||||
@@ -103,7 +104,7 @@ public class KnownListBuilderTests
|
|||||||
Assert.That(renamed, Is.Not.Null);
|
Assert.That(renamed, Is.Not.Null);
|
||||||
Assert.That(renamed!.Count, Is.EqualTo(1));
|
Assert.That(renamed!.Count, Is.EqualTo(1));
|
||||||
Assert.That(renamed[0].TargetIdx, Is.EqualTo(8));
|
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]
|
[Test]
|
||||||
@@ -316,7 +317,7 @@ public class KnownListBuilderTests
|
|||||||
|
|
||||||
Assert.That(stripped![0].SelectCard, Is.Not.Null);
|
Assert.That(stripped![0].SelectCard, Is.Not.Null);
|
||||||
Assert.That(stripped[0].SelectCard!.CardId, Is.EqualTo(new[] { 810041260L }));
|
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]
|
[Test]
|
||||||
@@ -447,7 +448,7 @@ public class KnownListBuilderTests
|
|||||||
Assert.That(e.IdxList, Is.EqualTo(new[] { 16, 22 }));
|
Assert.That(e.IdxList, Is.EqualTo(new[] { 16, 22 }));
|
||||||
Assert.That(e.From, Is.EqualTo(0));
|
Assert.That(e.From, Is.EqualTo(0));
|
||||||
Assert.That(e.To, Is.EqualTo(10));
|
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.Skill, Is.EqualTo("37|36|0"));
|
||||||
Assert.That(e.CardId, Is.Null);
|
Assert.That(e.CardId, Is.Null);
|
||||||
Assert.That(e.Clan, 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.Cost, Is.EqualTo(2));
|
||||||
Assert.That(e.SkillKeyCardIdx, Is.EqualTo(new[] { 7 }));
|
Assert.That(e.SkillKeyCardIdx, Is.EqualTo(new[] { 7 }));
|
||||||
Assert.That(e.RandomTargetIdx, Is.EqualTo(new[] { 2, 3 }));
|
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"));
|
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!.Count, Is.EqualTo(2));
|
||||||
Assert.That(relayed[0].Skill, Is.EqualTo("a"));
|
Assert.That(relayed[0].Skill, Is.EqualTo("a"));
|
||||||
Assert.That(relayed[1].Skill, Is.EqualTo("b"));
|
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]
|
[Test]
|
||||||
|
|||||||
Reference in New Issue
Block a user