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.
This commit is contained in:
@@ -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<T>`**: 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.
|
||||
|
||||
@@ -14,7 +14,26 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types;
|
||||
/// </summary>
|
||||
public static class AttributeValueCodec
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = false };
|
||||
// AllowNamedFloatingPointLiterals: a List<double>/List<float> 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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The scalar DateTime wire format: ISO-8601 round-trip (<c>"O"</c>), always UTC, with
|
||||
/// full sub-second precision. Replaced the invariant general format
|
||||
/// (<c>"06/15/2026 13:45:30"</c> — no zone, whole seconds) that the
|
||||
/// <see cref="IFormattable"/> branch used to produce (CMN-4). Every reader parses with
|
||||
/// <see cref="DateTimeStyles.RoundtripKind"/> + invariant culture, which still accepts
|
||||
/// the old form, so values persisted or sent by an older node keep decoding.
|
||||
/// </summary>
|
||||
private const string DateTimeWireFormat = "O";
|
||||
|
||||
/// <summary>Encodes a value to its canonical string form.</summary>
|
||||
/// <param name="value">The value to encode; scalars use invariant-culture formatting, enumerables encode as a JSON array.</param>
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Decodes a canonical string. For <see cref="DataType.List"/> returns a typed
|
||||
/// <c>List<T></c>; for scalars returns the string unchanged. Throws
|
||||
|
||||
@@ -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<T>), 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<T> 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;
|
||||
|
||||
@@ -324,4 +324,89 @@ public class AttributeValueCodecTests
|
||||
public void CoerceEnumerable_ThrowsOnUnsupportedElementType() =>
|
||||
Assert.Throws<FormatException>(
|
||||
() => AttributeValueCodec.CoerceEnumerable(new object[] { new byte[] { 1 } }, DataType.Binary));
|
||||
|
||||
// ── CMN-3: non-finite floating-point list elements ──
|
||||
|
||||
/// <summary>A double list holding NaN/±Infinity encodes (no throw) and round-trips.</summary>
|
||||
[Fact]
|
||||
public void RoundTrip_DoubleList_NonFinite()
|
||||
{
|
||||
var json = AttributeValueCodec.Encode(
|
||||
new List<double> { double.NaN, double.PositiveInfinity, double.NegativeInfinity, 1.5 });
|
||||
var back = (IList<double>)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]);
|
||||
}
|
||||
|
||||
/// <summary>A float list holding NaN/±Infinity encodes (no throw) and round-trips.</summary>
|
||||
[Fact]
|
||||
public void RoundTrip_FloatList_NonFinite()
|
||||
{
|
||||
var json = AttributeValueCodec.Encode(
|
||||
new List<float> { float.NaN, float.PositiveInfinity, float.NegativeInfinity });
|
||||
var back = (IList<float>)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 ──
|
||||
|
||||
/// <summary>A UTC scalar DateTime encodes as ISO-8601 round-trip and keeps sub-second precision and Kind.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>An Unspecified-kind scalar DateTime is taken as UTC (all timestamps are UTC system-wide).</summary>
|
||||
[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)));
|
||||
|
||||
/// <summary>The scalar DateTime encoding is culture-independent.</summary>
|
||||
[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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A scalar DateTimeOffset encodes as ISO-8601 round-trip, preserving the offset.</summary>
|
||||
[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)));
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_DateTimeList_AcceptsOldAndNewScalarForms()
|
||||
{
|
||||
var back = (IList<DateTime>)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]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,4 +205,54 @@ public class DynamicJsonElementTests
|
||||
Assert.Throws<Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(
|
||||
() => { 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));
|
||||
|
||||
/// <summary>A JSON null converts to a null string (not "" and not a binder failure).</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>A JSON null converts to a null <c>int?</c>.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>A JSON null cannot convert to a non-nullable value type: the binder reports failure.</summary>
|
||||
[Fact]
|
||||
public void TryConvert_IntTarget_OnJsonNull_ReportsFailure()
|
||||
{
|
||||
var wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement);
|
||||
Assert.False(wrapper.TryConvert(ConvertTo(typeof(int)), out _));
|
||||
}
|
||||
|
||||
/// <summary>A JSON number converts through Nullable<T>'s underlying type.</summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>End to end through the dynamic binder: (string) and (int?) casts of a JSON-null wrapper yield null.</summary>
|
||||
[Fact]
|
||||
public void DynamicCast_OnJsonNullWrapper_YieldsNull()
|
||||
{
|
||||
dynamic wrapper = new DynamicJsonElement(JsonDocument.Parse("null").RootElement);
|
||||
Assert.Null((string?)wrapper);
|
||||
Assert.Null((int?)wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user