e3f21cb86c
Consumer and origin history evidence for data connections (plan §6):
- DataConnectionHistoryDiagnostics: otopcua.dataconn.history.reads{variant,status_class,side} and
otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter (the H2 origin
counter sat on a private meter the host never exported); the plan's unknown-bits counter is the
existing X0 otopcua.dataconnection.unknown_operations_dropped, reused
- per-connection projected answers by status class and open consumer continuations (settled on
resume claim or release); origin sessions, open continuations and answers by status class
- negotiated features and advertised history variants/aggregates per connection
- AdminUI data-connections page renders them plus the dropped unknown-operation bits (#919)
- H4 unit-phase manifest key
219 lines
16 KiB
C#
219 lines
16 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
|
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
|
public sealed class GrpcDataLocalConnectionTests
|
|
{
|
|
[Fact]
|
|
public async Task Browse_lease_never_outlives_the_original_target_credential()
|
|
{
|
|
using var fixture = new LocalDataFixture(additionalRawNodes: 1);
|
|
var context = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(1) };
|
|
await using var connection = fixture.Services.Create(context, new(DataTargetMode.Node, "cluster", "node-a"));
|
|
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
|
var branch = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken);
|
|
branch.Serving.ShouldNotBeNull();
|
|
branch.Items.ShouldAllBe(x => x.Serving == branch.Serving);
|
|
branch.Status.ShouldBe(DataItemStatus.Good);
|
|
branch.Lease!.Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1));
|
|
branch.Continuation.ShouldNotBeNull();
|
|
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
|
|
var expired = await connection.BrowseAsync(new(fixture.Root, null, branch.Continuation, budget), TestContext.Current.CancellationToken);
|
|
expired.Status.ShouldBe(DataItemStatus.Denied);
|
|
expired.Items.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
await using var connection = fixture.Connection();
|
|
var result = await connection.GetMetadataAsync(new([fixture.Raw with { Subject = "bootstrap" },
|
|
fixture.Uns with { Subject = fixture.Raw.Subject }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
result[0].Status.ShouldBe(DataItemStatus.Good);
|
|
result[0].Value!.View.ShouldBe(fixture.Raw);
|
|
result[1].Status.ShouldBe(DataItemStatus.Denied);
|
|
result[1].Value.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Browse_continuation_is_bound_to_the_original_query_and_retains_bounded_scan_progress()
|
|
{
|
|
using var fixture = new LocalDataFixture(additionalRawNodes: 2);
|
|
await using var connection = fixture.Connection();
|
|
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
|
var page = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken);
|
|
page.Items.Count.ShouldBe(1);
|
|
page.Complete.ShouldBeFalse();
|
|
page.Continuation.ShouldNotBeNull();
|
|
var changed = await connection.BrowseAsync(new(fixture.Root, "changed", page.Continuation, budget), TestContext.Current.CancellationToken);
|
|
changed.Status.ShouldBe(DataItemStatus.InvalidContinuation);
|
|
var tampered = await connection.BrowseAsync(new(fixture.Root, null, page.Continuation + "!", budget), TestContext.Current.CancellationToken);
|
|
tampered.Status.ShouldBe(DataItemStatus.InvalidContinuation);
|
|
var next = await connection.BrowseAsync(new(fixture.Root, null, page.Continuation, budget), TestContext.Current.CancellationToken);
|
|
next.Status.ShouldBe(DataItemStatus.Good);
|
|
next.Items.ShouldHaveSingleItem().View.ShouldNotBe(page.Items[0].View);
|
|
var filtered = await connection.BrowseAsync(new(fixture.Root, "absent", null, budget), TestContext.Current.CancellationToken);
|
|
filtered.Items.ShouldBeEmpty();
|
|
filtered.Complete.ShouldBeFalse("filtering still scans only the admitted page window");
|
|
filtered.Continuation.ShouldNotBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Direct_local_api_browses_and_reads_without_a_namespace_mount()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
await using var connection = fixture.Connection();
|
|
var browse = await connection.BrowseAsync(new(fixture.Root, null, null, LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
browse.Status.ShouldBe(DataItemStatus.Good);
|
|
browse.Items.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw);
|
|
var metadata = await connection.GetMetadataAsync(new([fixture.Raw], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
metadata.ShouldHaveSingleItem().Value!.ValueKind.ShouldBe(DataValueKind.Int32);
|
|
fixture.Publish(42);
|
|
var results = await connection.ReadAsync(new([new("first", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
using var result = results.ShouldHaveSingleItem();
|
|
result.CorrelationId.ShouldBe("first");
|
|
result.Status.ShouldBe(DataItemStatus.Good);
|
|
result.Sample!.Value.GetScalar().ShouldBe(42);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Unwired_write_and_subscription_ports_are_not_advertised_or_reported_successful()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
await using var connection = fixture.Connection();
|
|
var capabilities = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken);
|
|
(capabilities.Operations & (DataOperations.Write | DataOperations.Subscribe)).ShouldBe(DataOperations.None);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 5);
|
|
var results = await connection.WriteAsync(new([new("write", "operation", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(1))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
results.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
await Should.ThrowAsync<InvalidOperationException>(() => connection.SubscribeAsync(TestContext.Current.CancellationToken));
|
|
}
|
|
|
|
[Fact]
|
|
public void Factory_rejects_wrong_target_and_forged_authenticated_context()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
Should.Throw<ArgumentException>(() => fixture.Services.Create(fixture.Context,
|
|
new(DataTargetMode.Node, "other-cluster", "node-a")));
|
|
Should.Throw<UnauthorizedAccessException>(() => fixture.Services.Create(fixture.Context with { PrincipalId = "forged" },
|
|
new(DataTargetMode.Node, "cluster", "node-a")));
|
|
}
|
|
}
|
|
|
|
internal sealed class LocalDataFixture : IDisposable
|
|
{
|
|
internal static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
|
internal readonly ManualTimeProvider Clock = new();
|
|
internal readonly ServingIdentity Serving = new("node-a", "serving-1", "Primary", 1, 1);
|
|
internal readonly DataPlaneAuthorityState Authority = new();
|
|
internal readonly CatalogActivation Activation = new();
|
|
internal readonly PartitionedSampleHub Hub;
|
|
internal readonly SourceTicket Ticket = new(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", "node-a", "serving-1"), new(1, 1));
|
|
internal readonly DataView Root = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant"), DataRealm.Raw, null, 0, "Plant");
|
|
internal readonly DataView Raw = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/Driver/Device/Speed"), DataRealm.Raw, null, 0, "Plant/Driver/Device/Speed");
|
|
internal readonly DataView Uns = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area/Line/Equipment/Speed"), DataRealm.Uns, null, 0, "Area/Line/Equipment/Speed");
|
|
internal readonly LocalDataServices Services;
|
|
/// <summary>H4: the origin's history diagnostics (counts by status class, live sessions and continuations).</summary>
|
|
internal readonly DataConnectionHistoryDiagnostics HistoryDiagnostics = new();
|
|
internal readonly LocalExportCatalog Catalog;
|
|
internal readonly DataAuthenticatedContext Context;
|
|
|
|
internal LocalDataFixture(int additionalRawNodes = 0,
|
|
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
|
|
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
|
|
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
|
|
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
|
|
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
|
|
IOriginHistoryPort? history = null, DataValueKind rawValueKind = DataValueKind.Int32, int maxBatchItems = 100)
|
|
{
|
|
if (clock is not null) Clock = clock;
|
|
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
|
|
Ticket = new(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", servingNode, servingIncarnation), new(1, 1));
|
|
Hub = HubTest.Create(clock: Clock, bytes: 1_000_000);
|
|
Hub.TryBind(Ticket).ShouldBeTrue();
|
|
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
|
Authority.Apply("cluster", "first", [key],
|
|
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer",
|
|
ScopeKind = nestedUnsCatalog ? NodeAclScopeKind.Cluster : NodeAclScopeKind.RawFolder,
|
|
ScopeId = nestedUnsCatalog ? null : "folder", PermissionFlags = writes is null ? NodePermissions.ReadOnly : NodePermissions.Operator }],
|
|
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
|
if (advanceAuthority)
|
|
{
|
|
Authority.Apply("cluster", "second", [key],
|
|
[new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder,
|
|
ScopeId = "folder", PermissionFlags = writes is null ? NodePermissions.ReadOnly : NodePermissions.Operator }],
|
|
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
|
Serving = Serving with { AuthorityEpoch = Authority.Current.GenerationId };
|
|
}
|
|
var epoch = Activation.Begin("first");
|
|
Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId);
|
|
Activation.Complete(epoch, true);
|
|
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
|
|
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
|
if (denyReadExport) operations &= ~DataOperations.Read;
|
|
if (history is not null) operations |= DataOperations.HistoryRead;
|
|
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
|
|
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", rawValueKind, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
|
|
var unsMetadata = rawMetadata with { View = Uns };
|
|
var folder = Root with { Address = Root.Address with { Identifier = "Plant/Driver" }, Subject = "Plant/Driver" };
|
|
var unsRoot = Uns with { Address = Uns.Address with { Identifier = "Area" }, Subject = "Area" };
|
|
var nodes = new List<LocalDataNode>
|
|
{new("RawFolder", "folder", rootMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant"] }, null, null),
|
|
new("RawTag", "tag", rawMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed"] }, nestedCatalog ? folder : Root, Ticket.Key),
|
|
new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, nestedUnsCatalog ? unsRoot : null, Ticket.Key)};
|
|
if (nestedUnsCatalog)
|
|
nodes.Add(new("UnsArea", "area", rootMetadata with { View = unsRoot, BrowseName = "Area" },
|
|
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area"] }, null, null));
|
|
if (nestedCatalog)
|
|
{
|
|
nodes.Add(new("RawFolder", "nested-folder", rootMetadata with { View = folder, BrowseName = "Driver" },
|
|
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver"] }, Root, null));
|
|
var array = Raw with { Address = Raw.Address with { Identifier = "Plant/Driver/Array" }, Subject = "Plant/Driver/Array" };
|
|
nodes.Add(new("RawTag", "array", rawMetadata with { View = array, BrowseName = "Array", ValueKind = DataValueKind.Array,
|
|
ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.UInt8 },
|
|
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Array"] }, folder, Ticket.Key));
|
|
}
|
|
for (var i = 0; i < additionalRawNodes; i++)
|
|
{
|
|
var view = Raw with { Address = Raw.Address with { Identifier = Raw.Address.Identifier + i }, Subject = Raw.Subject + i };
|
|
nodes.Add(new("RawTag", "extra-" + i, rawMetadata with { View = view, BrowseName = "Speed" + i },
|
|
new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "Driver", "Device", "Speed" + i] }, Root, Ticket.Key));
|
|
}
|
|
Catalog = new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
|
|
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw, RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations },
|
|
new() { DataExportId = "uns-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns, RootKind = nestedUnsCatalog ? "UnsArea" : "UnsTagReference", RootEntityId = nestedUnsCatalog ? "area" : "reference", PrincipalId = "peer", AllowedOperations = operations }]);
|
|
var limits = new DataLimits(100, maxBatchItems, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
|
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits);
|
|
Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority,
|
|
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions,
|
|
targetSubscriptions: targetSubscriptions, history: history) { HistoryDiagnostics = HistoryDiagnostics };
|
|
}
|
|
|
|
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));
|
|
internal void Publish(int value, bool beforeActivation = false)
|
|
{
|
|
using var owned = DataValue.FromScalar(DataValueKind.Int32, value);
|
|
Hub.TryReserveIngress(Ticket, owned.EstimatedRetainedBytes, out var reservation).ShouldBeTrue();
|
|
using (reservation!)
|
|
{
|
|
var sample = new DataSample(owned.Retain(), 0x00000400u, null, Clock.GetUtcNow(),
|
|
beforeActivation ? Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 } : Serving, 1);
|
|
if (!reservation!.TryCommit(sample, 1)) { sample.Dispose(); throw new InvalidOperationException(); }
|
|
}
|
|
Hub.ProcessPending();
|
|
}
|
|
public void Dispose() => Hub.Dispose();
|
|
}
|