b36c8d8716
GrpcDataConnection implements IDataHistoryService (explicitly; ReadHistoryAsync/ReleaseHistoryAsync avoid an overload clash with ReadAsync): the capabilities probe always asks for history, other calls send it only when the selected endpoint advertised it; per-call deadline min(remaining, HistoryTimeoutMilliseconds); FAILED_PRECONDITION/UNIMPLEMENTED => BadHistoryOperationUnsupported; chunks assembled within the request budget (BadTooManyOperations past it); page tokens wrapped with the issuing endpoint + serving incarnation so a resumed read never moves; release forwarded. The deployment lease gates history on the row's HistoryRead bit and carries HistoryTimeout. Decoded capabilities drop HistoryRead without the history field. X0 tests that used bit 32 as the unknown bit now use a still-reserved bit.
243 lines
15 KiB
C#
243 lines
15 KiB
C#
using System.Text;
|
|
using System.Text.Json.Nodes;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// X0 mixed-version tolerance (plan §4.3, test "R"). A newer central may author an operation bit this node does
|
|
/// not implement. Before X0 that rejected the WHOLE data-connection snapshot (every connection on the node went
|
|
/// down); after X0 the unknown bit is dropped from that row only (an unknown grant is no grant) and counted.
|
|
/// </summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "X0")]
|
|
public sealed class GrpcDataUnknownOperationToleranceTests
|
|
{
|
|
private static DataConnection Definition(string id, DataOperations operations) => new()
|
|
{
|
|
DataConnectionId = id, ClusterId = "owner", Revision = 1, Enabled = true,
|
|
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node,
|
|
ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"],
|
|
SecretReference = "secret:data/" + id, SecretScopeClusterId = "owner", AllowedOperations = operations,
|
|
MaxMessageBytes = 65536, MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2,
|
|
MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000
|
|
};
|
|
|
|
[Fact]
|
|
public async Task Unknown_bit_on_one_row_is_dropped_from_that_row_only_and_counted()
|
|
{
|
|
var activator = new Activator();
|
|
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
|
var history = Definition("history", DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
|
|
var plain = Definition("plain", DataOperations.Read | DataOperations.Subscribe);
|
|
var future = Definition("future", (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe);
|
|
|
|
// The pre-X0 runtime threw ArgumentException("Unknown operation.") here for the whole snapshot.
|
|
Should.NotThrow(() => runtime.Apply(new(1, "artifact-1", [history, plain, future])));
|
|
|
|
await EventuallyAsync(() => runtime.CurrentScopeReady);
|
|
(await Lease(runtime, "history")).ShouldBe(DataOperations.Read | DataOperations.Browse);
|
|
(await Lease(runtime, "plain")).ShouldBe(DataOperations.Read | DataOperations.Subscribe);
|
|
// A row left with no understood operation stays configured and grants nothing (fail closed).
|
|
(await Lease(runtime, "future")).ShouldBe(DataOperations.None);
|
|
|
|
runtime.DroppedUnknownOperations.ShouldBe(new Dictionary<string, DataOperations>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
["history"] = DataOperations.AlarmConfirm | DataOperations.AlarmShelve,
|
|
["future"] = (DataOperations)(1 << 30) | DataOperations.AlarmSubscribe,
|
|
});
|
|
runtime.UnknownOperationRowsDropped.ShouldBe(2);
|
|
// The production reader: the node diagnostics snapshot carries each row's dropped bits.
|
|
var diagnostics = runtime.CaptureDiagnostics().ToDictionary(x => x.ConnectionId);
|
|
diagnostics["history"].DroppedUnknownOperations.ShouldBe(DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
|
|
diagnostics["plain"].DroppedUnknownOperations.ShouldBe(DataOperations.None);
|
|
diagnostics["future"].DroppedUnknownOperations.ShouldBe((DataOperations)(1 << 30) | DataOperations.AlarmSubscribe);
|
|
diagnostics["plain"].MappingsWithDroppedOperations.ShouldBeNull("no mapping evidence was supplied");
|
|
// The input rows are not mutated: the drop is the node's reading, not a rewrite of the artifact.
|
|
history.AllowedOperations.ShouldBe(DataOperations.Read | DataOperations.Browse | DataOperations.AlarmConfirm | DataOperations.AlarmShelve);
|
|
activator.Allowlists.Last().Keys.Order(StringComparer.OrdinalIgnoreCase).ShouldBe(["future", "history", "plain"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Reapplying_the_same_revision_does_not_recount_and_a_clean_artifact_clears_the_diagnostic()
|
|
{
|
|
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4);
|
|
var snapshot = new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.AlarmConfirm)]);
|
|
runtime.Apply(snapshot);
|
|
runtime.Apply(snapshot);
|
|
runtime.UnknownOperationRowsDropped.ShouldBe(1);
|
|
runtime.DroppedUnknownOperations.ShouldContainKey("history");
|
|
|
|
runtime.Apply(new(2, "artifact-2", [Definition("history", DataOperations.Read)]));
|
|
runtime.DroppedUnknownOperations.ShouldBeEmpty();
|
|
runtime.UnknownOperationRowsDropped.ShouldBe(1);
|
|
|
|
// A -> B -> A is an accepted artifact CHANGE each time, so it recounts (documented semantics).
|
|
runtime.Apply(new(3, "artifact-1", [Definition("history", DataOperations.Read | DataOperations.AlarmConfirm)]));
|
|
runtime.UnknownOperationRowsDropped.ShouldBe(2);
|
|
}
|
|
|
|
[Fact]
|
|
public void Node_side_artifact_parse_accepts_rows_carrying_bits_a_newer_central_authored()
|
|
{
|
|
var root = Fixture();
|
|
root["DataConnections"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm);
|
|
root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm | DataOperations.AlarmSubscribe);
|
|
root["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.AlarmConfirm);
|
|
using var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
|
|
|
|
// Pre-X0 each of these threw InvalidDataException through the node-side DataConnectionValidator pass.
|
|
// Rows come back as authored; each consumer keeps only the bits it understands.
|
|
parsed.ParseDataConnections("node-a").ShouldHaveSingleItem().AllowedOperations.ShouldBe(
|
|
DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm);
|
|
parsed.ParseDataExports("node-b").ShouldHaveSingleItem().DataExportId.ShouldBe("export-a");
|
|
parsed.ParseRemoteNamespaceMappings("node-a").ShouldHaveSingleItem().RemoteNamespaceMappingId.ShouldBe("mapping-a");
|
|
}
|
|
|
|
[Fact]
|
|
public void Node_side_artifact_parse_still_rejects_what_it_rejected_before()
|
|
{
|
|
// Tolerance is only for unknown bits: a row with no operations at all, or a mapping granting an understood
|
|
// operation its connection lacks, is still invalid.
|
|
var none = Fixture();
|
|
none["DataConnections"]![0]!["AllowedOperations"] = 0;
|
|
using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(none.ToJsonString())))
|
|
Should.Throw<InvalidDataException>(() => parsed.ParseDataConnections("node-a"));
|
|
var wider = Fixture();
|
|
wider["RemoteNamespaceMappings"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Subscribe);
|
|
using (var parsed = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(wider.ToJsonString())))
|
|
Should.Throw<InvalidDataException>(() => parsed.ParseRemoteNamespaceMappings("node-a"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Origin_catalog_compiles_an_export_with_unknown_bits_and_grants_only_what_it_understands()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var snapshot = new DraftSnapshot
|
|
{
|
|
GenerationId = 1, ClusterId = "cluster",
|
|
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
|
|
RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }],
|
|
DataExports =
|
|
[
|
|
new() { DataExportId = "history", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster",
|
|
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.AlarmConfirm },
|
|
new() { DataExportId = "alarms-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
|
|
RootEntityId = "cluster", PrincipalId = "other", AllowedOperations = DataOperations.AlarmSubscribe | DataOperations.AlarmAcknowledge },
|
|
],
|
|
};
|
|
DataConnectionValidator.Validate(snapshot).ShouldContain(x => x.Code == "DataExportOperationsInvalid", "authoring still rejects reserved bits");
|
|
|
|
// Pre-X0 Compile threw InvalidDataException("Origin catalog configuration is invalid."): the whole origin went dark.
|
|
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read);
|
|
catalog.ExportOperations("other").ShouldBe(DataOperations.None);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_inert_all_unknown_export_does_not_lower_the_principals_limits_on_its_other_exports()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var snapshot = new DraftSnapshot
|
|
{
|
|
GenerationId = 1, ClusterId = "cluster",
|
|
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
|
|
RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }],
|
|
DataExports =
|
|
[
|
|
new() { DataExportId = "live", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "Cluster",
|
|
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read,
|
|
MaxBatchItems = 100, MaxPageItems = 100, MaxMonitoredItems = 100, MaxStreams = 10 },
|
|
new() { DataExportId = "future-only", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = "Cluster",
|
|
RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.AlarmConfirm | (DataOperations)(1 << 30),
|
|
MaxBatchItems = 1, MaxPageItems = 1, MaxMonitoredItems = 1, MaxStreams = 1 },
|
|
],
|
|
};
|
|
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var limits = new DataLimits(1000, 1000, 1_000_000, 1000, 100, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
|
var effective = catalog.LimitsFor("peer", limits);
|
|
effective.MaxBatchItems.ShouldBe(100);
|
|
effective.MaxPageItems.ShouldBe(100);
|
|
effective.MaxMonitoredItems.ShouldBe(100);
|
|
effective.MaxStreams.ShouldBe(10);
|
|
catalog.ExportOperations("peer").ShouldBe(DataOperations.Browse | DataOperations.Read);
|
|
}
|
|
|
|
private static async Task<DataOperations> Lease(DataConnectionDeploymentRuntime runtime, string id)
|
|
{
|
|
DataConnectionDeploymentLease? lease = null;
|
|
await EventuallyAsync(() => runtime.TryAcquire(id, out lease));
|
|
using (lease) return lease!.AllowedOperations;
|
|
}
|
|
|
|
private static async Task EventuallyAsync(Func<bool> condition)
|
|
{
|
|
for (var i = 0; i < 250; i++)
|
|
{
|
|
if (condition()) return;
|
|
await Task.Delay(20, TestContext.Current.CancellationToken);
|
|
}
|
|
throw new TimeoutException("Expected deployment state did not arrive.");
|
|
}
|
|
|
|
private sealed class Activator : IDataConnectionScopeActivator
|
|
{
|
|
public List<IReadOnlyDictionary<string, string>> Allowlists { get; } = [];
|
|
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken)
|
|
{
|
|
lock (Allowlists) Allowlists.Add(new Dictionary<string, string>(allowlist, StringComparer.OrdinalIgnoreCase));
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
private sealed class Security : IDataConnectionSecurityProvider
|
|
{
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new NoNetwork()));
|
|
}
|
|
|
|
private sealed class NoNetwork : HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
|
throw new InvalidOperationException("This tolerance test must not use the network.");
|
|
}
|
|
|
|
private static JsonObject Fixture() => JsonNode.Parse(
|
|
"""
|
|
{
|
|
"Clusters": [{"ClusterId":"local","Name":"Local","Enterprise":"ent","Site":"site","RedundancyMode":0,"CreatedBy":"test","Enabled":true}],
|
|
"Nodes": [
|
|
{"NodeId":"node-a","ClusterId":"local","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false},
|
|
{"NodeId":"node-b","ClusterId":"local","Host":"node-b","ApplicationUri":"urn:node-b","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}
|
|
],
|
|
"RawFolders": [{"RawFolderId":"local-root","ClusterId":"local","Name":"Local"}],
|
|
"DataConnections": [{
|
|
"DataConnectionId":"connection-a","ClusterId":"local","Revision":3,"Enabled":true,
|
|
"ConsumerNodeIds":["node-a"],"TargetMode":1,"Consistency":1,
|
|
"ExpectedClusterId":"local","ExpectedNodeId":"node-b","EligibleTargetNodeIds":[],
|
|
"Endpoints":["https://node-b:7443"],"SecretReference":"secret:data/upstream",
|
|
"SecretScopeClusterId":"local","AllowedOperations":5
|
|
}],
|
|
"DataExports": [{
|
|
"DataExportId":"export-a","ClusterId":"local","Revision":4,"Enabled":true,
|
|
"Realm":1,"RootKind":"RawFolder","RootEntityId":"local-root",
|
|
"PrincipalId":"peer","AllowedOperations":5
|
|
}],
|
|
"RemoteNamespaceMappings": [{
|
|
"RemoteNamespaceMappingId":"mapping-a","ClusterId":"local","DataConnectionId":"connection-a",
|
|
"Revision":5,"Enabled":true,"ConsumerNodeIds":["node-a"],"Realm":1,"RemoteRealm":1,
|
|
"LocalParentKind":"RawFolder","LocalParentId":"local-root","BranchName":"Remote",
|
|
"RemoteRootEntityId":"origin-root","RemoteNamespaceUri":"https://zb.com/otopcua/raw","RemoteIdentifierKind":"string",
|
|
"RemoteIdentifier":"origin-root","AllowedOperations":1,"WriteThrough":false
|
|
}]
|
|
}
|
|
""")!.AsObject();
|
|
}
|