From 405ca6367ed7619657d1f68dc089b0b6d43faa01 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:39:36 -0500 Subject: [PATCH] fix(commons): codec handles non-finite list floats, ISO-8601 UTC scalar DateTime, JSON null converts to null (CMN-3, CMN-4, CMN-10, WP3 task 3.11) Wire stays compatible: the scalar DateTime is a string either way and every reader parses with RoundtripKind/invariant, which still accepts the old invariant general form. --- docs/requirements/Component-Commons.md | 2 +- .../Types/AttributeValueCodec.cs | 34 +++++++- .../Types/DynamicJsonElement.cs | 15 +++- .../Types/AttributeValueCodecTests.cs | 85 +++++++++++++++++++ .../Types/DynamicJsonElementTests.cs | 50 +++++++++++ 5 files changed, 183 insertions(+), 3 deletions(-) diff --git a/docs/requirements/Component-Commons.md b/docs/requirements/Component-Commons.md index c3a57589..3fa64b39 100644 --- a/docs/requirements/Component-Commons.md +++ b/docs/requirements/Component-Commons.md @@ -26,7 +26,7 @@ Referenced by all component libraries and the Host. Commons must define shared primitive and utility types used across multiple components, including but not limited to: -- **`DataType` enum**: Enumerates the data types supported by the system: Boolean, Int32, Float, Double, String, DateTime, Binary, and **List** (a homogeneous multi-value attribute). A `List` attribute carries a companion `ElementDataType` (one of the scalar types — String, Int32, Float, Double, Boolean, DateTime; not Binary, not nested List) on `TemplateAttribute` / `InstanceAttributeOverride` and the flattened `ResolvedAttribute`. List values are stored and transmitted as a canonical **native-typed** JSON array via the `AttributeValueCodec` helper — numbers and booleans unquoted, strings quoted, `DateTime` as ISO-8601 (e.g. `[10,20]`, `[true,false]`, `["2026-06-16T00:00:00Z"]`); scalars keep their historical invariant-culture string form. `AttributeValueCodec.Decode` is backward compatible: it reads both the native form and the earlier array-of-strings form (`["10","20"]`). Already-persisted old-form values are normalized to native on the fly — an idempotent central startup normalizer (`ListValueNormalizer`, run after migrations) rewrites MS SQL rows, the `InstanceActor` re-persists site SQLite overrides on load, and bundle import re-encodes List values. The `ElementDataType` is fixed by the defining level and cannot be changed on a derived template or instance override. +- **`DataType` enum**: Enumerates the data types supported by the system: Boolean, Int32, Float, Double, String, DateTime, Binary, and **List** (a homogeneous multi-value attribute). A `List` attribute carries a companion `ElementDataType` (one of the scalar types — String, Int32, Float, Double, Boolean, DateTime; not Binary, not nested List) on `TemplateAttribute` / `InstanceAttributeOverride` and the flattened `ResolvedAttribute`. List values are stored and transmitted as a canonical **native-typed** JSON array via the `AttributeValueCodec` helper — numbers and booleans unquoted, strings quoted, `DateTime` as ISO-8601 (e.g. `[10,20]`, `[true,false]`, `["2026-06-16T00:00:00Z"]`); scalars keep their historical invariant-culture string form, except `DateTime`/`DateTimeOffset`, which encode as ISO-8601 round-trip (`"O"`; a `DateTime` is normalised to UTC, an Unspecified kind is taken as UTC) so the scalar keeps its zone and sub-second precision — the older invariant general form (`06/15/2026 13:45:30`) still parses everywhere a value is read. Non-finite `Float`/`Double` list elements encode as the JSON strings `"NaN"`/`"Infinity"`/`"-Infinity"` and decode back. `AttributeValueCodec.Decode` is backward compatible: it reads both the native form and the earlier array-of-strings form (`["10","20"]`). Already-persisted old-form values are normalized to native on the fly — an idempotent central startup normalizer (`ListValueNormalizer`, run after migrations) rewrites MS SQL rows, the `InstanceActor` re-persists site SQLite overrides on load, and bundle import re-encodes List values. The `ElementDataType` is fixed by the defining level and cannot be changed on a derived template or instance override. - **`RetryPolicy`**: A record or immutable class describing retry behavior (max retries, fixed delay between retries). - **`Result`**: A discriminated result type that represents either a success value or an error, enabling consistent error handling across component boundaries without exceptions. - **`InstanceState` enum**: Enabled, Disabled. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs index 8649b9c1..ca81da3b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/AttributeValueCodec.cs @@ -14,7 +14,26 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types; /// public static class AttributeValueCodec { - private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = false }; + // AllowNamedFloatingPointLiterals: a List/List holding NaN or ±Infinity + // (a bad-scaled analog, a divide-by-zero) encodes as the JSON strings "NaN" / + // "Infinity" / "-Infinity" instead of throwing ArgumentException from the serializer + // (CMN-3). Decode reads them back through the invariant-culture double/float parse, + // which accepts the same literals. + private static readonly JsonSerializerOptions JsonOpts = new() + { + WriteIndented = false, + NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowNamedFloatingPointLiterals, + }; + + /// + /// The scalar DateTime wire format: ISO-8601 round-trip ("O"), always UTC, with + /// full sub-second precision. Replaced the invariant general format + /// ("06/15/2026 13:45:30" — no zone, whole seconds) that the + /// branch used to produce (CMN-4). Every reader parses with + /// + invariant culture, which still accepts + /// the old form, so values persisted or sent by an older node keep decoding. + /// + private const string DateTimeWireFormat = "O"; /// Encodes a value to its canonical string form. /// The value to encode; scalars use invariant-culture formatting, enumerables encode as a JSON array. @@ -25,6 +44,12 @@ public static class AttributeValueCodec { case null: return null; case string s: return s; // already canonical + // DateTime/DateTimeOffset before the generic IFormattable branch: ISO-8601 + // round-trip so the scalar keeps its zone and sub-second precision (CMN-4). + // All timestamps are UTC system-wide, so an Unspecified kind is taken as UTC + // and a Local one is converted. + case DateTime dt: return ToUtc(dt).ToString(DateTimeWireFormat, CultureInfo.InvariantCulture); + case DateTimeOffset dto: return dto.ToString(DateTimeWireFormat, CultureInfo.InvariantCulture); case IFormattable f: return f.ToString(null, CultureInfo.InvariantCulture); case IEnumerable e: // Native-typed JSON: serialize the runtime collection so System.Text.Json emits @@ -35,6 +60,13 @@ public static class AttributeValueCodec } } + private static DateTime ToUtc(DateTime dt) => dt.Kind switch + { + DateTimeKind.Utc => dt, + DateTimeKind.Local => dt.ToUniversalTime(), + _ => DateTime.SpecifyKind(dt, DateTimeKind.Utc), + }; + /// /// Decodes a canonical string. For returns a typed /// List<T>; for scalars returns the string unchanged. Throws diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs index 797dcbb9..e196b03f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/DynamicJsonElement.cs @@ -96,7 +96,20 @@ public class DynamicJsonElement : DynamicObject return true; } - result = ConvertTo(binder.Type); + // A JSON null converts to null for any target that can hold null (reference + // types and Nullable), e.g. (string)resp or (int?)resp on a JSON-null body. + // A non-nullable value type (e.g. int) genuinely cannot represent it: report + // failure so the binder surfaces a binding error (CMN-10). + var underlying = Nullable.GetUnderlyingType(binder.Type); + if (_element.ValueKind == JsonValueKind.Null) + { + result = null; + return !binder.Type.IsValueType || underlying != null; + } + + // Nullable targets convert through their underlying type: (int?)resp on a + // JSON number yields the boxed int, which the binder lifts to int?. + result = ConvertTo(underlying ?? binder.Type); // A non-object target with a null result means ConvertTo could not handle the // element/type pair — report failure so the binder surfaces a binding error. return result != null; diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs index 4c8e736b..d714bf22 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/AttributeValueCodecTests.cs @@ -324,4 +324,89 @@ public class AttributeValueCodecTests public void CoerceEnumerable_ThrowsOnUnsupportedElementType() => Assert.Throws( () => AttributeValueCodec.CoerceEnumerable(new object[] { new byte[] { 1 } }, DataType.Binary)); + + // ── CMN-3: non-finite floating-point list elements ── + + /// A double list holding NaN/±Infinity encodes (no throw) and round-trips. + [Fact] + public void RoundTrip_DoubleList_NonFinite() + { + var json = AttributeValueCodec.Encode( + new List { double.NaN, double.PositiveInfinity, double.NegativeInfinity, 1.5 }); + var back = (IList)AttributeValueCodec.Decode(json, DataType.List, DataType.Double)!; + Assert.True(double.IsNaN(back[0])); + Assert.Equal(double.PositiveInfinity, back[1]); + Assert.Equal(double.NegativeInfinity, back[2]); + Assert.Equal(1.5, back[3]); + } + + /// A float list holding NaN/±Infinity encodes (no throw) and round-trips. + [Fact] + public void RoundTrip_FloatList_NonFinite() + { + var json = AttributeValueCodec.Encode( + new List { float.NaN, float.PositiveInfinity, float.NegativeInfinity }); + var back = (IList)AttributeValueCodec.Decode(json, DataType.List, DataType.Float)!; + Assert.True(float.IsNaN(back[0])); + Assert.Equal(float.PositiveInfinity, back[1]); + Assert.Equal(float.NegativeInfinity, back[2]); + } + + // ── CMN-4: scalar DateTime wire form ── + + /// A UTC scalar DateTime encodes as ISO-8601 round-trip and keeps sub-second precision and Kind. + [Fact] + public void Encode_ScalarUtcDateTime_RoundTripsWithSubSecondPrecision() + { + var dt = new DateTime(2026, 6, 15, 13, 45, 30, 123, DateTimeKind.Utc).AddTicks(4567); + var encoded = AttributeValueCodec.Encode(dt)!; + Assert.Equal("2026-06-15T13:45:30.1234567Z", encoded); + + var back = DateTime.Parse(encoded, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); + Assert.Equal(dt, back); + Assert.Equal(DateTimeKind.Utc, back.Kind); + } + + /// An Unspecified-kind scalar DateTime is taken as UTC (all timestamps are UTC system-wide). + [Fact] + public void Encode_ScalarUnspecifiedDateTime_IsStampedUtc() => + Assert.Equal("2026-06-15T13:45:30.0000000Z", + AttributeValueCodec.Encode(new DateTime(2026, 6, 15, 13, 45, 30, DateTimeKind.Unspecified))); + + /// The scalar DateTime encoding is culture-independent. + [Fact] + public void Encode_ScalarDateTime_IsInvariant() + { + var original = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = new CultureInfo("de-DE"); + Assert.Equal("2026-06-15T13:45:30.5000000Z", + AttributeValueCodec.Encode(new DateTime(2026, 6, 15, 13, 45, 30, 500, DateTimeKind.Utc))); + } + finally + { + CultureInfo.CurrentCulture = original; + } + } + + /// A scalar DateTimeOffset encodes as ISO-8601 round-trip, preserving the offset. + [Fact] + public void Encode_ScalarDateTimeOffset_IsIso8601() => + Assert.Equal("2026-06-15T13:45:30.2500000+00:00", + AttributeValueCodec.Encode(new DateTimeOffset(2026, 6, 15, 13, 45, 30, 250, TimeSpan.Zero))); + + /// + /// Compatibility read: a List element in the pre-CMN-4 scalar form (invariant general + /// format) still decodes next to an element in the new ISO form. + /// + [Fact] + public void Decode_DateTimeList_AcceptsOldAndNewScalarForms() + { + var back = (IList)AttributeValueCodec.Decode( + "[\"06/15/2026 13:45:30\",\"2026-06-15T13:45:30.1230000Z\"]", + DataType.List, DataType.DateTime)!; + Assert.Equal(new DateTime(2026, 6, 15, 13, 45, 30), back[0]); + Assert.Equal(new DateTime(2026, 6, 15, 13, 45, 30, 123, DateTimeKind.Utc), back[1]); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs index c2f2f696..5f67f839 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Commons.Tests/Types/DynamicJsonElementTests.cs @@ -205,4 +205,54 @@ public class DynamicJsonElementTests Assert.Throws( () => { var _ = obj.items[idx]; }); } + + // ── CMN-10: JSON null converts to null for nullable targets ── + + private static ConvertBinder ConvertTo(Type t) => + (ConvertBinder)Microsoft.CSharp.RuntimeBinder.Binder.Convert( + Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags.ConvertExplicit, t, typeof(DynamicJsonElementTests)); + + /// A JSON null converts to a null string (not "" and not a binder failure). + [Fact] + public void TryConvert_StringTarget_OnJsonNull_ReturnsNull() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(string)), out var result)); + Assert.Null(result); + } + + /// A JSON null converts to a null int?. + [Fact] + public void TryConvert_NullableIntTarget_OnJsonNull_ReturnsNull() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(int?)), out var result)); + Assert.Null(result); + } + + /// A JSON null cannot convert to a non-nullable value type: the binder reports failure. + [Fact] + public void TryConvert_IntTarget_OnJsonNull_ReportsFailure() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.False(wrapper.TryConvert(ConvertTo(typeof(int)), out _)); + } + + /// A JSON number converts through Nullable<T>'s underlying type. + [Fact] + public void TryConvert_NullableIntTarget_OnNumber_ReturnsValue() + { + var wrapper = new DynamicJsonElement(JsonDocument.Parse("42").RootElement); + Assert.True(wrapper.TryConvert(ConvertTo(typeof(int?)), out var result)); + Assert.Equal(42, result); + } + + /// End to end through the dynamic binder: (string) and (int?) casts of a JSON-null wrapper yield null. + [Fact] + public void DynamicCast_OnJsonNullWrapper_YieldsNull() + { + dynamic wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement); + Assert.Null((string?)wrapper); + Assert.Null((int?)wrapper); + } }