using Google.Protobuf; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections; [Trait("Feature", "GrpcData"), Trait("Phase", "P01"), Trait("Category", "Unit")] public sealed class GrpcDataCodecTests { [Fact] public void UInt64_and_empty_arrays_round_trip() { using var original = DataValue.FromArray( DataValueKind.UInt64, new object[] { ulong.MaxValue, 0UL }, new[] { 2 } ); using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(original)); decoded.ArrayElementKind.ShouldBe(DataValueKind.UInt64); decoded.GetArray().ShouldBe(new object[] { ulong.MaxValue, 0UL }); using var empty = DataValue.FromArray( DataValueKind.Int32, Array.Empty(), new[] { 0, 2 } ); using var roundTrip = TypedValueCodec.Decode(TypedValueCodec.Encode(empty)); roundTrip.Dimensions.ShouldBe(new[] { 0, 2 }); } [Fact] public void Null_and_empty_bytes_are_distinct() { using var value = DataValue.FromBytes(Array.Empty()); using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(value)); decoded.Kind.ShouldBe(DataValueKind.Bytes); decoded.GetBytes().Length.ShouldBe(0); using var nullValue = TypedValueCodec.Decode(TypedValueCodec.Encode(DataValue.Null())); nullValue.Kind.ShouldBe(DataValueKind.Null); } [Fact] public void Malformed_shape_and_oversized_payload_are_rejected() { var wire = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue { Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array, Array = new() { ElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int32, }, }; wire.Array.Dimensions.Add(1000000); Should.Throw(() => TypedValueCodec.Decode(wire, 10, 1000)); using var large = DataValue.FromBytes(new byte[100]); Should.Throw(() => TypedValueCodec.Decode(TypedValueCodec.Encode(large), 10, 10) ); } [Fact] public void Encoding_does_not_take_ownership_of_the_sample() { using var original = DataValue.FromBytes(new byte[] { 1, 2 }); var wire = TypedValueCodec.Encode(original); original.Dispose(); using var decoded = TypedValueCodec.Decode(wire); decoded.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2 }); } [Fact] public void Numeric_boundaries_and_special_floats_round_trip() { foreach ( var pair in new (DataValueKind Kind, object Value)[] { (DataValueKind.Int8, sbyte.MinValue), (DataValueKind.Int16, short.MaxValue), (DataValueKind.Int32, int.MinValue), (DataValueKind.Int64, long.MaxValue), (DataValueKind.UInt8, byte.MaxValue), (DataValueKind.UInt16, ushort.MaxValue), (DataValueKind.UInt32, uint.MaxValue), (DataValueKind.UInt64, ulong.MaxValue), (DataValueKind.Float, float.NaN), (DataValueKind.Double, double.PositiveInfinity), } ) { using var value = DataValue.FromScalar(pair.Kind, pair.Value); using var decoded = TypedValueCodec.Decode(TypedValueCodec.Encode(value)); decoded.GetScalar().ShouldBe(pair.Value); } } [Fact] public void Wrong_payload_and_array_element_type_are_rejected() { var wrong = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue { Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int8, Unsigned = 1, }; Should.Throw(() => TypedValueCodec.Decode(wrong)); var array = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.TypedValue { Kind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array, Array = new() { ElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Int32, }, }; array.Array.Dimensions.Add(1); array.Array.Elements.Add(wrong); Should.Throw(() => TypedValueCodec.Decode(array)); } [Fact] public void Array_metadata_preserves_element_kind_even_for_empty_arrays() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); foreach (var elementKind in new[] { DataValueKind.Int32, DataValueKind.String }) { var metadata = new DataMetadata( view, "x", "Variable", DataValueKind.Array, 1, new[] { 0 }, false, DataOperations.Read, 1, null, null, false, elementKind ); var decoded = DataProtoMapper.DecodeMetadata(DataProtoMapper.EncodeMetadata(metadata)); decoded.ArrayElementKind.ShouldBe(elementKind); } } [Fact] public void Array_metadata_rejects_missing_and_invalid_element_kind() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); var metadata = new DataMetadata( view, "x", "Variable", DataValueKind.Array, 1, new[] { 0 }, false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32 ); var wire = DataProtoMapper.EncodeMetadata(metadata); wire.ClearArrayElementKind(); Should.Throw(() => DataProtoMapper.DecodeMetadata(wire)); wire.ArrayElementKind = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind.Array; Should.Throw(() => DataProtoMapper.DecodeMetadata(wire)); var scalar = metadata with { ValueKind = DataValueKind.Int32 }; Should.Throw(() => DataProtoMapper.EncodeMetadata(scalar)); } [Fact] public void Write_batch_uses_independent_item_and_array_limits() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); using var value = DataValue.FromArray( DataValueKind.Int32, Enumerable.Range(0, 100).Cast().ToArray(), new[] { 100 } ); var item = new WriteItem( "correlation", "operation", view, value, 1, "incarnation", TimeSpan.FromSeconds(1) ); var wire = DataProtoMapper.EncodeWriteRequest( new WriteBatch(new[] { item }, new DataBudget(TimeSpan.FromSeconds(1), 1, 100000)) ); var decoded = DataProtoMapper.DecodeWriteRequest(wire, 1, 100000, 1000); try { decoded.Items.Single().Value.GetArray().Count.ShouldBe(100); } finally { foreach (var entry in decoded.Items) entry.Value.Dispose(); } Should.Throw(() => DataProtoMapper.DecodeWriteRequest(wire, 1, 100, 1000) ); } [Fact] public void Write_hash_ignores_retry_fields_but_binds_semantic_preconditions() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); using var value = DataValue.FromScalar(DataValueKind.Int32, 5); using var other = DataValue.FromScalar(DataValueKind.Int32, 6); var item = new WriteItem("one", "op", view, value, 1, "inc", TimeSpan.FromSeconds(1)); var hash = DataProtoMapper.WritePayloadHash(item); DataProtoMapper .WritePayloadHash( item with { CorrelationId = "two", RemainingBudget = TimeSpan.FromMilliseconds(5), } ) .ShouldBe(hash); DataProtoMapper.WritePayloadHash(item with { Value = other }).ShouldNotBe(hash); DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 1 }).ShouldNotBe(hash); DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 2 }).ShouldNotBe( DataProtoMapper.WritePayloadHash(item with { ExpectedServingGeneration = 1 })); DataProtoMapper .WritePayloadHash(item with { ExpectedCatalogRevision = 2 }) .ShouldNotBe(hash); DataProtoMapper .WritePayloadHash( item with { View = view with { Address = view.Address with { Identifier = "y" } }, } ) .ShouldNotBe(hash); } [Fact] public void Write_generation_preserves_presence_and_rejects_nonpositive_values() { var view = new DataView(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject"); using var value = DataValue.FromScalar(DataValueKind.Int32, 5); var item = new WriteItem("one", "op", view, value, 1, "inc", TimeSpan.FromSeconds(1)); var budget = new DataBudget(TimeSpan.FromSeconds(1), 1, 10000); var absent = DataProtoMapper.EncodeWriteRequest(new([item], budget)); absent.Items[0].HasExpectedServingGeneration.ShouldBeFalse(); var wire = DataProtoMapper.EncodeWriteRequest(new([item with { ExpectedServingGeneration = 9 }], budget)); wire.Items[0].HasExpectedServingGeneration.ShouldBeTrue(); var decoded = DataProtoMapper.DecodeWriteRequest(wire, 1, 10000); decoded.Items[0].ExpectedServingGeneration.ShouldBe(9); decoded.Items[0].Value.Dispose(); wire.Items[0].ExpectedServingGeneration = 0; Should.Throw(() => DataProtoMapper.DecodeWriteRequest(wire, 1, 10000)); } [Fact] public void Timestamp_ticks_round_trip_and_subtick_precision_is_rejected() { var instant = DateTimeOffset.UnixEpoch.AddTicks(1234567); using var value = DataValue.FromScalar(DataValueKind.Timestamp, instant); var wire = TypedValueCodec.Encode(value); using var decoded = TypedValueCodec.Decode(wire); decoded.GetScalar().ShouldBe(instant); wire.Timestamp.Nanos += 1; Should.Throw(() => TypedValueCodec.Decode(wire)); } [Fact] public void Compatible_capabilities_ignore_unknown_kinds_and_fallback_compact_version() { var limits = new DataLimits( 10, 10, 10000, 10, 2, 10000, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1) ); var capabilities = new DataCapabilities( 1, 0, new ServingIdentity("node", "inc", "primary", 1, 2), DataReadiness.Ready, DataOperations.Read, new HashSet { DataValueKind.Int32 }, limits, true, 1, "cluster" ); var wire = DataProtoMapper.EncodeCapabilities(capabilities); wire.ValueKinds.Add((ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.ValueKind)999); wire.Operations |= 0x80000000; wire.CompactCodecVersion = 99; var decoded = DataProtoMapper.DecodeCapabilities(wire); decoded.ClusterId.ShouldBe("cluster"); decoded.ValueKinds.ShouldContain(DataValueKind.Int32); decoded.ValueKinds.Count.ShouldBe(1); decoded.Operations.ShouldBe(DataOperations.Read); DataProtoMapper.NegotiateCompact(decoded).ShouldBeFalse(); wire.ProtocolMajor = 2; Should.Throw(() => DataProtoMapper.DecodeCapabilities(wire)); } [Fact] public void Receiver_limits_reject_collection_counts_and_aggregate_write_expansion() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); var budget = new DataBudget(TimeSpan.FromSeconds(1), 100, 100000); var read = DataProtoMapper.EncodeReadRequest( new ReadRequest( new[] { new ReadItem("1", view, null), new ReadItem("2", view, null) }, budget ) ); var metadata = DataProtoMapper.EncodeMetadataRequest( new MetadataRequest(new[] { view, view }, budget) ); Should.Throw(() => DataProtoMapper.DecodeReadRequest(read, new DataDecodeLimits(1, 100000, 100)) ); Should.Throw(() => DataProtoMapper.DecodeMetadataRequest(metadata, new DataDecodeLimits(1, 100000, 100)) ); using var first = DataValue.FromBytes(new byte[400]); using var second = DataValue.FromBytes(new byte[400]); var write = DataProtoMapper.EncodeWriteRequest( new WriteBatch( new[] { new WriteItem("1", "o1", view, first, 1, "inc", TimeSpan.FromSeconds(1)), new WriteItem("2", "o2", view, second, 1, "inc", TimeSpan.FromSeconds(1)), }, budget ) ); write.CalculateSize().ShouldBeLessThan(2000); Should.Throw(() => DataProtoMapper.DecodeWriteRequest(write, 2, 2000, 100) ); } [Fact] public void Malformed_settings_identity_and_versions_are_rejected() { var settings = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Settings { SamplingTicks = 1, PublishingTicks = 1, Trigger = (int)DataChangeTrigger.StatusValue, Deadband = double.NaN, }; Should.Throw(() => DataProtoMapper.DecodeSettings(settings)); var serving = new ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1.Serving { NodeId = "", Incarnation = "i", Role = "primary", CatalogEpoch = 1, AuthorityEpoch = 1, }; Should.Throw(() => DataProtoMapper.DecodeServing(serving)); } [Fact] public void Write_requires_operation_identity_incarnation_and_positive_preconditions() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); using var value = DataValue.Null(); var item = new WriteItem("c", "operation", view, value, 1, "inc", TimeSpan.FromSeconds(1)); var request = DataProtoMapper.EncodeWriteRequest( new WriteBatch(new[] { item }, new DataBudget(TimeSpan.FromSeconds(1), 1, 10000)) ); var wire = request.Items[0]; wire.OperationId = ""; Should.Throw(() => DataProtoMapper.DecodeWriteRequest(request, 1, 10000) ); wire.OperationId = "operation"; wire.ExpectedServingIncarnation = ""; Should.Throw(() => DataProtoMapper.DecodeWriteRequest(request, 1, 10000) ); wire.ExpectedServingIncarnation = "inc"; wire.ExpectedCatalogRevision = 0; Should.Throw(() => DataProtoMapper.DecodeWriteRequest(request, 1, 10000) ); wire.ExpectedCatalogRevision = 1; wire.RemainingBudgetTicks = 0; Should.Throw(() => DataProtoMapper.DecodeWriteRequest(request, 1, 10000) ); } [Fact] public void Browse_and_nested_metadata_obey_receiver_limits() { var view = new DataView( new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "subject" ); var budget = new DataBudget(TimeSpan.FromSeconds(1), 10, 100000); var request = DataProtoMapper.EncodeBrowseRequest( new BrowseRequest(view, new string('a', 200), null, budget) ); Should.Throw(() => DataProtoMapper.DecodeBrowseRequest(request, new DataDecodeLimits(1, 100, 100)) ); var metadata = new DataMetadata( view, "x", "Variable", DataValueKind.Array, 16, Enumerable.Repeat(0, 16).ToArray(), false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32 ); var branch = new DataBrowseBranch( view, DataItemStatus.Good, new[] { metadata }, true, null, null ); var response = DataProtoMapper.EncodeBrowseResponse(branch); DataProtoMapper .DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100)) .Items.Count.ShouldBe(1); Should.Throw(() => DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 100, 100)) ); response.Items[0].Dimensions.Add(0); Should.Throw(() => DataProtoMapper.DecodeBrowseResponse(response, new DataDecodeLimits(1, 10000, 100)) ); } }