diff --git a/docs/DataConnections.md b/docs/DataConnections.md index ce8704d57..098ae8ec2 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -247,6 +247,16 @@ Neither change alters the wire shape: one drops an optional field, the other dro consumer (`Guid`, `Bytes`), instead of failing the page. The item never reaches the projection cache or the address space. A malformed item of a supported kind (rank, dimensions and element kind disagree) still fails the page closed. An empty `Complete = false` page, which the origin's name filter can produce, is paged through by SDK `BrowseNext`. + - **Version skew: an unknown enum number fails one item, not the response (#956).** A value-kind or array-element-kind + number this build does not define (a data type a newer origin added) decodes to an *unknown-kind marker* + (`DataMetadata.HasUnknownKind`) instead of throwing in `DataProtoMapper.DecodeMetadata`, which used to fail the whole + browse page or metadata batch before the resolver could skip anything. The resolver skips the marker whatever its node + kind (a `Folder` included), a remote root carrying it is refused, and it can never be validated, re-encoded or granted. + A per-item metadata **status** this build does not define reads as that item's `Unavailable` (no value, no lease); the + rest of the batch is unaffected. Still malformed and still failing the response: `Unspecified` (0) for any of these, an + array whose rank and dimensions disagree, an element kind on a known scalar, an unknown **realm** (an item's realm must + equal the requested parent's), and an unknown browse-**branch** status (the page fails `Unavailable` either way). Node + kinds are strings and operation bits are masked to the understood set, so neither needed a change. - The node stays in the catalog, so a deployed export rooted at it still compiles, but it grants nothing: the values are unsupported, and the condition sits under the tag's folder, not under the tag. **Authoring and the deploy gate refuse such an export (#942, `DataExportRootAlarmBearing`)**, and likewise one rooted at a `UnsTagReference` to an diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index 8d1e7b39a..f75a02274 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -274,8 +274,11 @@ public static class DataProtoMapper if (x.Dimensions.Count > TypedValueCodec.MaxDimensions) throw new ArgumentException("Too many dimensions."); Preflight(x, 1, null); + // #956: a value-kind number this build does not define (a newer origin's data type) is NOT a decode failure — it + // decodes to an unknown-kind marker (DataMetadata.HasUnknownKind) that ValidateDecoded accepts and Validate refuses, + // so the resolver skips that one item (#941) instead of the whole browse page / metadata batch failing here. + // Unspecified (0) is still malformed and throws (ValidateDecoded). var kind = (DataValueKind)x.ValueKind; - DataContractValidation.Required(kind); var metadata = new DataMetadata( DecodeView(x.View), x.BrowseName, @@ -296,7 +299,7 @@ public static class DataProtoMapper null, x.History is { } history ? new DataHistoryInfo(history.Historizing) : null ); - metadata.Validate(); + metadata.ValidateDecoded(); return metadata; } @@ -1249,6 +1252,12 @@ public static class DataProtoMapper { Preflight(item, 1, limits); var status = (DataItemStatus)item.Status; + if (item.Status != 0 && !System.Enum.IsDefined(status)) + // #956 version skew: a per-item status a newer origin added is that item's failure, not the batch's. It grants + // nothing (no value, no lease) and reads as transient (Unavailable), so the consumer retries rather than caching + // a permanent refusal. Unspecified (0) is still malformed and fails the response below. + return new(item.CorrelationId, DataItemStatus.Unavailable, null, + $"Origin item status {item.Status} is not understood by this build.", null); DataContractValidation.Required(status); MetadataLease? lease = item.Lease is { } itemLease ? new(itemLease.CatalogEpoch, itemLease.AuthorityEpoch, TimeSpan.FromTicks(itemLease.DurationTicks)) : null; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs index 1320f3e64..8e25d19b0 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/DataContracts.cs @@ -356,6 +356,37 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null, DataHistoryInfo? History = null) { + /// + /// #956 version skew: the value kind (or the array element kind) is a number this build does not define — a data type + /// a newer origin added. Such an item is an unsupported marker: it decodes (so one item never fails a whole + /// browse page or metadata batch), it fails (so it can never be re-encoded, materialised or + /// granted), and the consumer's resolver skips it like any other unmaterialisable kind (#941). + /// + public bool HasUnknownKind => !Enum.IsDefined(ValueKind) || ArrayElementKind is { } element && !Enum.IsDefined(element); + + /// + /// Validation of an item decoded from a peer (#956): for every item of a kind this build defines; + /// for a marker, everything that does not depend on the unknown kind's meaning — the view, + /// a nonzero kind, a positive catalog revision, non-negative dimensions and, for a known Array whose element kind + /// is the unknown one, the array shape. Unspecified (0) is a malformed item, never version skew, and still throws. + /// + public void ValidateDecoded() + { + if (!HasUnknownKind) { Validate(); return; } + ArgumentNullException.ThrowIfNull(View); + View.Validate(); + ArgumentNullException.ThrowIfNull(Dimensions); + if (ValueKind == DataValueKind.Unspecified || ArrayElementKind == DataValueKind.Unspecified) + throw new ArgumentOutOfRangeException(nameof(ValueKind), ValueKind, "A defined nonzero value is required."); + if (CatalogRevision <= 0 || Dimensions.Any(d => d < 0)) throw new ArgumentOutOfRangeException(nameof(CatalogRevision)); + if (Enum.IsDefined(ValueKind)) + { + // The value kind is known, so the unknown one is the element kind: only an array may carry one, with its shape. + if (ValueKind != DataValueKind.Array) throw new ArgumentException("Only arrays may specify an element kind.", nameof(ArrayElementKind)); + if (ValueRank <= 0 || Dimensions.Count != ValueRank) throw new ArgumentException("Array rank and dimensions must agree.", nameof(ValueRank)); + } + } + public void Validate() { ArgumentNullException.ThrowIfNull(View); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs index 84a716bda..9767c3965 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedCatalogCache.cs @@ -139,9 +139,11 @@ public sealed class ProjectedCatalogCache /// that is not materialisable (an UnsupportedVariable from a pre-#917 origin, a node kind a newer origin adds, a /// value type the consumer cannot represent) is SKIPPED by the resolver; it used to fail the whole page, making the /// folder BadNoCommunication. A malformed item of a supported kind (rank / dimensions / element kind that do - /// not agree) still fails the page closed — that is a protocol violation, not an unknown kind. + /// not agree) still fails the page closed — that is a protocol violation, not an unknown kind. #956: an item whose value + /// or element kind is a number this build does not define (, decoded as a + /// marker rather than failing the response) is never materialisable, whatever its node kind. /// - internal static bool IsMaterialisable(DataMetadata metadata) => metadata.NodeKind switch + internal static bool IsMaterialisable(DataMetadata metadata) => !metadata.HasUnknownKind && metadata.NodeKind switch { "Folder" => true, "Variable" or "Tag" => HasBuiltInType(metadata.ValueKind == DataValueKind.Array ? metadata.ArrayElementKind : metadata.ValueKind), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs index 6e5858437..dd76fad95 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/RemoteNamespaceResolver.cs @@ -207,7 +207,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp { var originView = new DataView(request.Parent.Address, request.Parent.Realm, null, 0, binding.Mapping.RemoteRootEntityId); var metadata = await connection.Connection.GetMetadataAsync(new([originView], request.Budget with { Timeout = remaining }), route.Token).ConfigureAwait(false); - if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null) + if (metadata.Count != 1 || metadata[0].Status != DataItemStatus.Good || metadata[0].Value is not { } root || root.HasUnknownKind || root.View.Address != originView.Address || root.View.MappingId is not null || root.Serving is null) return PreparedPage.Failed(ProjectionPageStatus.Unavailable); originParent = root; } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataVersionSkewCodecTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataVersionSkewCodecTests.cs new file mode 100644 index 000000000..7f11c0c1f --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/DataConnections/GrpcDataVersionSkewCodecTests.cs @@ -0,0 +1,136 @@ +using Google.Protobuf; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; + +namespace ZB.MOM.WW.OtOpcUa.Commons.Tests.DataConnections; + +/// +/// #956: an enum number a newer origin added must fail only the item that carries it, never the whole browse page or +/// metadata batch at decode — the consumer's resolver (#941) skips the item. Malformed values (Unspecified = 0, a shape +/// that does not agree) still fail closed. +/// +[Trait("Feature", "GrpcData"), Trait("Category", "Unit")] +public sealed class GrpcDataVersionSkewCodecTests +{ + private const int NewerKind = 99; // a ValueKind number this build does not define + + private static readonly DataView View = new(new DataAddress("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x"); + + private static DataMetadata Scalar(string name = "x") => + new(View with { Address = View.Address with { Identifier = name }, Subject = name }, name, "Variable", DataValueKind.Int32, -1, + [], false, DataOperations.Read, 1, null, null, false); + + private static DataMetadata Array1() => + new(View, "a", "Variable", DataValueKind.Array, 1, [0], false, DataOperations.Read, 1, null, null, false, DataValueKind.Int32); + + /// Wire bytes from a newer origin: the field carries a number this build's proto enum does not define. + private static W.Metadata Reparse(W.Metadata wire) => W.Metadata.Parser.ParseFrom(wire.ToByteArray()); + + [Theory] + [InlineData("Variable")] + [InlineData("Folder")] + [InlineData("Method")] + public void An_unknown_value_kind_decodes_to_an_unknown_kind_marker_not_a_failure(string nodeKind) + { + var wire = DataProtoMapper.EncodeMetadata(Scalar() with { NodeKind = nodeKind }); + wire.ValueKind = (W.ValueKind)NewerKind; + var decoded = DataProtoMapper.DecodeMetadata(Reparse(wire)); + + ((int)decoded.ValueKind).ShouldBe(NewerKind); + decoded.HasUnknownKind.ShouldBeTrue(); + decoded.BrowseName.ShouldBe("x"); + // The marker is never valid as a contract value: it cannot be validated, re-encoded or granted. + Should.Throw(() => decoded.Validate()); + Should.Throw(() => DataProtoMapper.EncodeMetadata(decoded)); + } + + [Fact] + public void An_unknown_array_element_kind_decodes_to_the_marker_with_its_shape_still_checked() + { + var wire = DataProtoMapper.EncodeMetadata(Array1()); + wire.ArrayElementKind = (W.ValueKind)NewerKind; + var decoded = DataProtoMapper.DecodeMetadata(Reparse(wire)); + decoded.HasUnknownKind.ShouldBeTrue(); + ((int)decoded.ArrayElementKind!.Value).ShouldBe(NewerKind); + + // A known Array whose shape does not agree is still malformed, whatever its element kind. + var badShape = wire.Clone(); + badShape.Dimensions.Add(0); + Should.Throw(() => DataProtoMapper.DecodeMetadata(badShape)); + // A known scalar may not carry an element kind at all — an unknown one included. + var scalar = DataProtoMapper.EncodeMetadata(Scalar()); + scalar.ArrayElementKind = (W.ValueKind)NewerKind; + Should.Throw(() => DataProtoMapper.DecodeMetadata(scalar)); + } + + [Fact] + public void Unspecified_is_still_malformed_never_version_skew() + { + var wire = DataProtoMapper.EncodeMetadata(Scalar()); + wire.ValueKind = W.ValueKind.Unspecified; + Should.Throw(() => DataProtoMapper.DecodeMetadata(wire)); + + var unknownWithUnspecifiedElement = DataProtoMapper.EncodeMetadata(Scalar()); + unknownWithUnspecifiedElement.ValueKind = (W.ValueKind)NewerKind; + unknownWithUnspecifiedElement.ArrayElementKind = W.ValueKind.Unspecified; + Should.Throw(() => DataProtoMapper.DecodeMetadata(unknownWithUnspecifiedElement)); + + var unknownWithBadRevision = DataProtoMapper.EncodeMetadata(Scalar()); + unknownWithBadRevision.ValueKind = (W.ValueKind)NewerKind; + unknownWithBadRevision.CatalogRevision = 0; + Should.Throw(() => DataProtoMapper.DecodeMetadata(unknownWithBadRevision)); + } + + [Fact] + public void One_unknown_kind_item_does_not_fail_the_browse_page() + { + var response = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, + [Scalar("a"), Scalar("b"), Scalar("c")], true, null, null)); + response.Items[1].ValueKind = (W.ValueKind)NewerKind; + var branch = DataProtoMapper.DecodeBrowseResponse(W.BrowseResponse.Parser.ParseFrom(response.ToByteArray()), + new DataDecodeLimits(10, 100000, 100)); + + branch.Items.Select(x => x.BrowseName).ShouldBe(["a", "b", "c"]); + branch.Items.Select(x => x.HasUnknownKind).ShouldBe([false, true, false]); + } + + [Fact] + public void One_unknown_kind_item_does_not_fail_the_metadata_batch() + { + var response = DataProtoMapper.EncodeMetadataResponse([ + new DataItemResult("0", DataItemStatus.Good, Scalar("a"), null), + new DataItemResult("1", DataItemStatus.Good, Scalar("b"), null)]); + response.Items[0].Value.ValueKind = (W.ValueKind)NewerKind; + var items = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(response.ToByteArray()), + new DataDecodeLimits(10, 100000, 100)); + + items[0].Value!.HasUnknownKind.ShouldBeTrue(); + items[1].Value!.HasUnknownKind.ShouldBeFalse(); + items[1].Value!.ValueKind.ShouldBe(DataValueKind.Int32); + } + + [Fact] + public void An_unknown_per_item_metadata_status_fails_that_item_transiently_not_the_batch() + { + var response = DataProtoMapper.EncodeMetadataResponse([ + new DataItemResult("0", DataItemStatus.Good, Scalar("a"), null, + new MetadataLease(1, 1, TimeSpan.FromSeconds(1))), + new DataItemResult("1", DataItemStatus.Good, Scalar("b"), null)]); + response.Items[0].Status = 99; // a status a newer origin added; it even carries a value and a lease + var items = DataProtoMapper.DecodeMetadataResponse(W.MetadataResponse.Parser.ParseFrom(response.ToByteArray()), + new DataDecodeLimits(10, 100000, 100)); + + items[0].CorrelationId.ShouldBe("0"); + items[0].Status.ShouldBe(DataItemStatus.Unavailable); + items[0].Value.ShouldBeNull("an unknown status grants nothing"); + items[0].Lease.ShouldBeNull("an unknown status grants nothing"); + items[1].Status.ShouldBe(DataItemStatus.Good); + + // Unspecified (0) is malformed and still fails the response. + response.Items[0].Status = 0; + Should.Throw(() => DataProtoMapper.DecodeMetadataResponse(response, new DataDecodeLimits(10, 100000, 100))); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs index 93c6efcca..7c69d70c0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataBrowseToleranceWireTests.cs @@ -22,6 +22,8 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests [InlineData("Method", DataValueKind.Null)] // a node kind a newer origin might add [InlineData("Variable", DataValueKind.Guid)] // a value kind the consumer has no OPC UA type for [InlineData("Variable", DataValueKind.Bytes)] + [InlineData("Variable", (DataValueKind)99)] // #956: a value-kind number a newer origin added (decoded as a marker) + [InlineData("Folder", (DataValueKind)99)] // #956: even a Folder — a supported node kind — is skipped, not Validate()d public async Task A_child_of_an_unmaterialisable_kind_is_skipped_not_the_whole_folder_941(string nodeKind, DataValueKind valueKind) { using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1);