Root cause for the lingering mulligan failure: the inline conditional
expression in MsgEnvelope.ToObject
JsonValueKind.Number => el.TryGetInt64(out var l) ? l : el.GetDouble(),
unified its branches to the common implicit-convertible type. long→double
is implicit, so both branches collapsed to double and the integer value
silently widened. Inside an array (idxList:[2]), each element came back
as boxed double; OfType<long> in ExtractIdxList then filtered every
entry out, so swapIndices arrived empty and BuildSwapResponse echoed
the unchanged hand — exactly the diff-against-Deal mismatch the client
flagged as "Card swap failed: AbandonCards[2]/DrawCards[]".
Extract a ParseNumber helper that returns object explicitly so each
branch boxes its own runtime type. Also harden ExtractIdxList to accept
any boxed numeric type (long/int/double/decimal/string) so a future
JSON-parser drift can't silently regress this path again.
Two regression tests:
- FromJson_NumericArray_PreservesLongTypeOnEachElement: confirms the
fix at the JSON-parse layer with a hardcoded "{\"idxList\":[2,3]}".
- Swap_WithIdxListContainingTwo_ProducesHandWithFreshIdxAtPosition1:
exercises the dispatch end-to-end with a Body holding a real boxed
long; asserts position 1 of the response hand is the fresh deck idx 4.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
114 lines
4.5 KiB
C#
114 lines
4.5 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace SVSim.BattleNode.Protocol;
|
|
|
|
/// <summary>
|
|
/// The shared envelope on every encrypted msg / synchronize frame. Body is opaque
|
|
/// (Dictionary<string, object?>) because shape varies per Uri — typed register-action
|
|
/// models come in a later slice.
|
|
/// </summary>
|
|
public sealed record MsgEnvelope(
|
|
NetworkBattleUri Uri,
|
|
long ViewerId,
|
|
string Uuid,
|
|
string? Bid,
|
|
int Try,
|
|
EmitCategory Cat,
|
|
long? PubSeq,
|
|
long? PlaySeq,
|
|
Dictionary<string, object?> Body)
|
|
{
|
|
private static readonly JsonSerializerOptions Options = CreateOptions();
|
|
|
|
private static readonly HashSet<string> ReservedEnvelopeKeys = new()
|
|
{
|
|
"uri", "viewerId", "uuid", "bid", "try", "cat", "pubSeq", "playSeq",
|
|
};
|
|
|
|
private static JsonSerializerOptions CreateOptions()
|
|
{
|
|
var opt = new JsonSerializerOptions
|
|
{
|
|
// Wire-key casing here is bare camelCase — NOT EmulatedEntrypoint's snake_case policy.
|
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
};
|
|
opt.Converters.Add(new JsonStringEnumConverter());
|
|
return opt;
|
|
}
|
|
|
|
public static string ToJson(MsgEnvelope env)
|
|
{
|
|
var doc = new Dictionary<string, object?>
|
|
{
|
|
["uri"] = env.Uri.ToString(),
|
|
["viewerId"] = env.ViewerId,
|
|
["uuid"] = env.Uuid,
|
|
["try"] = env.Try,
|
|
["cat"] = (int)env.Cat,
|
|
};
|
|
if (env.Bid is not null) doc["bid"] = env.Bid;
|
|
if (env.PubSeq.HasValue) doc["pubSeq"] = env.PubSeq.Value;
|
|
if (env.PlaySeq.HasValue) doc["playSeq"] = env.PlaySeq.Value;
|
|
foreach (var (k, v) in env.Body)
|
|
{
|
|
if (ReservedEnvelopeKeys.Contains(k))
|
|
throw new ArgumentException(
|
|
$"Body key '{k}' collides with a reserved envelope field. Move it to a typed field on MsgEnvelope.",
|
|
nameof(env));
|
|
doc[k] = v;
|
|
}
|
|
return JsonSerializer.Serialize(doc, Options);
|
|
}
|
|
|
|
public static MsgEnvelope FromJson(string json)
|
|
{
|
|
using var doc = JsonDocument.Parse(json);
|
|
var root = doc.RootElement;
|
|
|
|
var uri = Enum.Parse<NetworkBattleUri>(root.GetProperty("uri").GetString()!);
|
|
var viewerId = root.GetProperty("viewerId").GetInt64();
|
|
var uuid = root.GetProperty("uuid").GetString()!;
|
|
var bid = root.TryGetProperty("bid", out var bidEl) ? bidEl.GetString() : null;
|
|
var @try = root.TryGetProperty("try", out var tryEl) ? tryEl.GetInt32() : 0;
|
|
var cat = root.TryGetProperty("cat", out var catEl) ? (EmitCategory)catEl.GetInt32() : EmitCategory.Battle;
|
|
var pubSeq = root.TryGetProperty("pubSeq", out var psEl) ? psEl.GetInt64() : (long?)null;
|
|
var playSeq = root.TryGetProperty("playSeq", out var plsEl) ? plsEl.GetInt64() : (long?)null;
|
|
|
|
var body = new Dictionary<string, object?>();
|
|
foreach (var prop in root.EnumerateObject())
|
|
{
|
|
if (ReservedEnvelopeKeys.Contains(prop.Name)) continue;
|
|
body[prop.Name] = ToObject(prop.Value);
|
|
}
|
|
|
|
return new MsgEnvelope(uri, viewerId, uuid, bid, @try, cat, pubSeq, playSeq, body);
|
|
}
|
|
|
|
private static object? ToObject(JsonElement el) => el.ValueKind switch
|
|
{
|
|
JsonValueKind.String => el.GetString(),
|
|
// Extracted to a helper because writing the conditional inline as
|
|
// el.TryGetInt64(out var l) ? l : el.GetDouble()
|
|
// unifies the conditional's branches to the common implicit-convertible type. long→double
|
|
// is implicit; so the result type collapses to double and the long value silently widens.
|
|
// Downstream OfType<long> filters then drop the (now boxed-double) entries, which broke
|
|
// the mulligan idxList extraction. Separate method returns object explicitly so each
|
|
// branch boxes its own runtime type.
|
|
JsonValueKind.Number => ParseNumber(el),
|
|
JsonValueKind.True => true,
|
|
JsonValueKind.False => false,
|
|
JsonValueKind.Null => null,
|
|
JsonValueKind.Array => el.EnumerateArray().Select(ToObject).ToList(),
|
|
JsonValueKind.Object => el.EnumerateObject().ToDictionary(p => p.Name, p => ToObject(p.Value)),
|
|
_ => el.GetRawText(),
|
|
};
|
|
|
|
private static object ParseNumber(JsonElement el)
|
|
{
|
|
if (el.TryGetInt64(out var l)) return l;
|
|
return el.GetDouble();
|
|
}
|
|
}
|