From 51a7f9e8d2347b3acee827655aa37a4a87c6a7aa Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 9 Mar 2026 20:17:01 -0400 Subject: [PATCH] Fix: extend $type-anywhere deserialization to Condition, TriggerEvent, and Filter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor EffectPolymorphicConverter into a generic PolymorphicAbilityConverter base class, add concrete converters for all four abstract ability model types: Effect, Condition, TriggerEvent, and Filter — all share the same abstract + [JsonPolymorphic] pattern and the same ordering constraint from the admin builder. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../src/SOR.Game/Abilities/AbilitySystem.cs | 9 +- .../Abilities/EffectPolymorphicConverter.cs | 85 ++++++++++--------- 2 files changed, 50 insertions(+), 44 deletions(-) diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs index 860c51b..516439d 100644 --- a/Server/src/SOR.Game/Abilities/AbilitySystem.cs +++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs @@ -23,10 +23,13 @@ public static class AbilitySystem Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter(), - // Handles polymorphic Effect deserialization when $type is not the first - // property — the default [JsonPolymorphic] behavior requires $type first - // for abstract base types. + // Handle polymorphic deserialization when $type is not the first property. + // The default [JsonPolymorphic] behavior requires $type first for abstract + // base types; admin-tool JSON does not guarantee that ordering. new EffectPolymorphicConverter(), + new ConditionPolymorphicConverter(), + new TriggerPolymorphicConverter(), + new FilterPolymorphicConverter(), }, }; diff --git a/Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs b/Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs index 64617cf..317612d 100644 --- a/Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs +++ b/Server/src/SOR.Game/Abilities/EffectPolymorphicConverter.cs @@ -6,89 +6,85 @@ using System.Text.Json.Serialization; using SOR.Game.Abilities.Models; /// -/// Custom JSON converter for the polymorphic hierarchy. +/// Generic base converter that fixes polymorphic deserialization when the +/// $type discriminator is not the first property in a JSON object. /// -/// Problem: requires the $type discriminator to be -/// the first property in the JSON object when the base class is abstract. -/// Card-definition JSON authored in the admin tool does not guarantee that ordering -/// (e.g. {"N":1,"$type":"DrawCards","Player":"Owner"}). +/// System.Text.Json requires $type to appear first for abstract base +/// classes. Card-definition JSON authored in the admin tool does not guarantee +/// that ordering. This converter buffers the entire JSON object, finds +/// $type at any position, looks up the concrete type from the +/// map on , +/// then deserializes via the default converter. /// -/// Fix: this converter intercepts only typeof(Effect) (not derived types — -/// see ), reads the entire JSON object into a -/// , finds $type regardless of position, then -/// deserializes into the correct concrete type. Concrete derived types are handled -/// by the standard serializer so there is no infinite recursion. +/// CanConvert returns true only for the exact base type +/// — not for concrete derived types — so there is no +/// infinite recursion when the default converter processes derived-type properties. /// -internal sealed class EffectPolymorphicConverter : JsonConverter +internal abstract class PolymorphicAbilityConverter : JsonConverter where T : class { - private static readonly Dictionary _typeMap; - private static readonly Dictionary _reverseMap; + // Static fields are per closed type T — each T gets its own map. + private static readonly Dictionary s_typeMap; + private static readonly Dictionary s_reverseMap; - static EffectPolymorphicConverter() + static PolymorphicAbilityConverter() { - _typeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); - _reverseMap = new Dictionary(); + s_typeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); + s_reverseMap = new Dictionary(); - foreach (var attr in typeof(Effect) - .GetCustomAttributes()) + foreach (var attr in typeof(T).GetCustomAttributes()) { if (attr.TypeDiscriminator is string disc) { - _typeMap[disc] = attr.DerivedType; - _reverseMap[attr.DerivedType] = disc; + s_typeMap[disc] = attr.DerivedType; + s_reverseMap[attr.DerivedType] = disc; } } } /// - /// Only intercept the abstract base itself. - /// Concrete derived types (e.g. DrawCardsEffect) fall through to the - /// default serializer — this prevents infinite recursion. + /// Only intercept the abstract base itself. + /// Concrete derived types fall through to the default serializer. /// - public override bool CanConvert(Type typeToConvert) - => typeToConvert == typeof(Effect); + public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(T); - public override Effect? Read( - ref Utf8JsonReader reader, - Type typeToConvert, + public override T? Read( + ref Utf8JsonReader reader, + Type typeToConvert, JsonSerializerOptions options) { - // Buffer the entire object so we can find $type anywhere. using var doc = JsonDocument.ParseValue(ref reader); var root = doc.RootElement; if (!root.TryGetProperty("$type", out var discriminatorProp)) - throw new JsonException("Effect object is missing the '$type' discriminator."); + throw new JsonException($"{typeof(T).Name} object is missing the '$type' discriminator."); var discriminator = discriminatorProp.GetString() - ?? throw new JsonException("Effect '$type' discriminator is null."); + ?? throw new JsonException($"{typeof(T).Name} '$type' discriminator is null."); - if (!_typeMap.TryGetValue(discriminator, out var concreteType)) - throw new JsonException($"Unknown Effect '$type': '{discriminator}'."); + if (!s_typeMap.TryGetValue(discriminator, out var concreteType)) + throw new JsonException($"Unknown {typeof(T).Name} '$type': '{discriminator}'."); - // Deserialize as the concrete type. CanConvert returns false for concrete - // types, so this call uses the default converter — no recursion. - return (Effect?)root.Deserialize(concreteType, options); + // CanConvert returns false for concrete derived types, so no infinite recursion. + return (T?)root.Deserialize(concreteType, options); } public override void Write( Utf8JsonWriter writer, - Effect value, + T value, JsonSerializerOptions options) { var concreteType = value.GetType(); - if (!_reverseMap.TryGetValue(concreteType, out var discriminator)) + if (!s_reverseMap.TryGetValue(concreteType, out var discriminator)) throw new JsonException($"No '$type' discriminator registered for {concreteType.Name}."); - // Serialize the concrete object first to get its properties as a JsonDocument. - // CanConvert returns false for concrete types, so no recursion. + // Serialize the concrete object (CanConvert=false for it → no recursion). using var mem = new System.IO.MemoryStream(); using (var inner = new Utf8JsonWriter(mem)) JsonSerializer.Serialize(inner, value, concreteType, options); using var doc = JsonDocument.Parse(mem.ToArray()); - // Write the final object: $type first, then all concrete properties. + // Write with $type first so round-trip JSON is always well-formed. writer.WriteStartObject(); writer.WriteString("$type", discriminator); foreach (var prop in doc.RootElement.EnumerateObject()) @@ -96,3 +92,10 @@ internal sealed class EffectPolymorphicConverter : JsonConverter writer.WriteEndObject(); } } + +// ── Concrete converters ─────────────────────────────────────────────────────── + +internal sealed class EffectPolymorphicConverter : PolymorphicAbilityConverter { } +internal sealed class ConditionPolymorphicConverter : PolymorphicAbilityConverter { } +internal sealed class TriggerPolymorphicConverter : PolymorphicAbilityConverter{ } +internal sealed class FilterPolymorphicConverter : PolymorphicAbilityConverter { }