feat: add immutable partitioned data publication hub
This commit is contained in:
+135
@@ -0,0 +1,135 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataCachedReadTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Prepared_response_is_fenced_before_send_after_ingress_invalidation_or_authority_change()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
var lease = results[0].ResourceLease.ShouldBeAssignableTo<IDataPublicationLease>();
|
||||
lease!.IsValid.ShouldBeTrue();
|
||||
fixture.Hub.Invalidate(fixture.Ticket, "overflow before serialization");
|
||||
lease!.IsValid.ShouldBeFalse();
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeTrue();
|
||||
fixture.Activation.Begin("revocation");
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Returned_value_holds_its_global_resource_charge_until_recipient_disposes_it()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var baseline = fixture.Hub.Resources.RetainedBytes;
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
|
||||
results[0].Dispose();
|
||||
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Initial_stale_and_invalidated_cached_reads_have_distinct_readiness()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var request = new ReadRequest([new("read", fixture.Raw, TimeSpan.FromSeconds(2))], LocalDataFixture.Budget);
|
||||
var initial = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (initial[0]) initial[0].Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
fixture.Publish(42);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
|
||||
var stale = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (stale[0])
|
||||
{
|
||||
stale[0].Status.ShouldBe(DataItemStatus.Stale);
|
||||
stale[0].Age.ShouldBe(TimeSpan.FromSeconds(3));
|
||||
stale[0].Sample!.SourceTimestampUtc.ShouldBeNull();
|
||||
stale[0].Sample!.StatusCode.ShouldBe(0x00000400u);
|
||||
}
|
||||
fixture.Hub.Invalidate(fixture.Ticket, "overflow");
|
||||
var invalidated = await connection.ReadAsync(request, TestContext.Current.CancellationToken);
|
||||
using (invalidated[0])
|
||||
{
|
||||
invalidated[0].Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
invalidated[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Shared_backing_cache_does_not_share_authorization_between_Raw_and_Uns_aliases()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("raw", fixture.Raw, null), new("uns", fixture.Uns, null),
|
||||
new("forged", fixture.Raw with { Subject = "other" }, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0]) using (results[1]) using (results[2])
|
||||
{
|
||||
results.Select(x => x.CorrelationId).ShouldBe(["raw", "uns", "forged"]);
|
||||
results.Select(x => x.Status).ShouldBe([DataItemStatus.Good, DataItemStatus.Denied, DataItemStatus.Denied]);
|
||||
results[1].Sample!.ShouldBeNull();
|
||||
results[2].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Activation_invalidates_cached_payload_without_a_new_sample()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
fixture.Activation.Begin("new-authority");
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Unavailable);
|
||||
results[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Original_credential_expiry_denies_a_quiet_cached_value_without_a_deploy()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Connection();
|
||||
fixture.Clock.Advance(TimeSpan.FromMinutes(11));
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Denied);
|
||||
results[0].Sample!.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Quiet_initial_acquisition_gets_current_serving_header_without_changing_its_age_or_timestamps()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Publish(7, beforeActivation: true);
|
||||
var acquired = fixture.Clock.GetUtcNow();
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
|
||||
await using var connection = fixture.Connection();
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using (results[0])
|
||||
{
|
||||
results[0].Status.ShouldBe(DataItemStatus.Good);
|
||||
results[0].Sample!.Serving.ShouldBe(fixture.Serving);
|
||||
results[0].Sample!.Version.ShouldBe(1);
|
||||
results[0].Sample!.SourceTimestampUtc.ShouldBeNull();
|
||||
results[0].Sample!.ServerTimestampUtc.ShouldBe(acquired);
|
||||
results[0].Age.ShouldBe(TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
+564
@@ -0,0 +1,564 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
[Collection("opcua-publish-meters")]
|
||||
public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
{
|
||||
private static readonly NodeId Node = NodeId.Parse("node-a");
|
||||
private static readonly ServingIdentity BootIdentity = new("node-a", "process-1", "Primary", 0, 0);
|
||||
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
||||
|
||||
[Fact]
|
||||
public void A_new_attempt_closes_a_completed_catalog_even_when_authority_revision_is_unchanged()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var coordinator = NewCoordinator(authority, activation);
|
||||
var bytes = Artifact();
|
||||
var first = Prepare(coordinator, bytes);
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.Complete(first, topologySucceeded: true).ShouldBeTrue();
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
var oldAuthority = authority.Current.GenerationId;
|
||||
|
||||
var second = coordinator.BeginAttempt(Hash(bytes));
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.InstallAuthority(second, DeploymentArtifact.ParseDataPlaneAuthority(bytes, Node.Value)).ShouldBeTrue();
|
||||
authority.Current.GenerationId.ShouldBe(oldAuthority); // The authority store deduplicates identical bytes.
|
||||
using var parsed = DeploymentArtifact.Open(bytes);
|
||||
coordinator.Stage(second, parsed.ParseLocalCatalogSnapshot(Node.Value)!).ShouldBeTrue();
|
||||
coordinator.Complete(second, topologySucceeded: true).ShouldBeTrue();
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current!.Serving.CatalogEpoch.ShouldBeGreaterThan(old.Serving.CatalogEpoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Stale_attempt_cannot_install_older_authority_or_publish_its_catalog()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var olderBytes = Artifact();
|
||||
var older = Prepare(coordinator, olderBytes);
|
||||
var revokedBytes = Artifact(revoked: true);
|
||||
var newer = Prepare(coordinator, revokedBytes);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
var newerGeneration = authority.Current.GenerationId;
|
||||
|
||||
coordinator.InstallAuthority(older, DeploymentArtifact.ParseDataPlaneAuthority(olderBytes, Node.Value)).ShouldBeFalse();
|
||||
coordinator.Complete(older, topologySucceeded: true).ShouldBeFalse();
|
||||
authority.Current.GenerationId.ShouldBe(newerGeneration);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
coordinator.Complete(newer, topologySucceeded: true).ShouldBeTrue();
|
||||
coordinator.Current.ShouldNotBeNull().Serving.AuthorityEpoch.ShouldBe(newerGeneration);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Failed_topology_never_publishes_the_staged_catalog_or_rolls_back_revocation()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var first = Prepare(coordinator, Artifact());
|
||||
coordinator.Complete(first, topologySucceeded: true).ShouldBeTrue();
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
|
||||
var next = Prepare(coordinator, Artifact(revoked: true));
|
||||
coordinator.Complete(next, topologySucceeded: false).ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Complete(next, topologySucceeded: true).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Headless_fetch_apply_serves_an_authorized_local_catalog_without_a_mount()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acknowledgments = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acknowledgments.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
acknowledgments.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var catalog = coordinator.Current.ShouldNotBeNull();
|
||||
catalog.IsActive.ShouldBeTrue();
|
||||
catalog.Serving.NodeId.ShouldBe(Node.Value);
|
||||
catalog.Serving.Incarnation.ShouldBe(BootIdentity.Incarnation);
|
||||
catalog.Serving.CatalogEpoch.ShouldBeGreaterThan(0);
|
||||
catalog.Serving.AuthorityEpoch.ShouldBeGreaterThan(0);
|
||||
|
||||
using var hub = HubTest.Create();
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
||||
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var capabilities = new DataCapabilitiesProvider("cluster", () => coordinator.Current!.Serving,
|
||||
() => coordinator.Current?.IsActive == true, limits);
|
||||
var services = new LocalDataServices(() => coordinator.Current, hub,
|
||||
new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, hub.Clock), hub.Clock),
|
||||
capabilities, hub.Clock);
|
||||
var key = authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
var context = new DataAuthenticatedContext("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key),
|
||||
DateTimeOffset.UtcNow.AddMinutes(10), authority.Current.GenerationId);
|
||||
await using var connection = services.Create(context, new(DataTargetMode.Node, "cluster", Node.Value));
|
||||
var root = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw);
|
||||
var page = await connection.BrowseAsync(new(root, null, null, Budget), TestContext.Current.CancellationToken);
|
||||
page.Status.ShouldBe(DataItemStatus.Good);
|
||||
page.Items.Select(x => x.BrowseName).ShouldContain("Plant");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_closes_the_old_catalog_before_creating_a_replacement_driver()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var nextBytes = Artifact(includeDriver: true);
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var factory = new ObservingFactory(() => coordinator.Current?.IsActive == true);
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, factory);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
|
||||
fetcher.Bytes = nextBytes;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(nextBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
factory.Called.ShouldBeTrue();
|
||||
factory.CatalogWasActive.ShouldBeFalse();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Invalid_catalog_still_installs_independent_revocation_before_driver_reconciliation()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var badBytes = Artifact(revoked: true, includeDriver: true, invalidExport: true);
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var factory = new ObservingFactory(() => authority.Current.FindUsableKey("peer-key", DateTime.UtcNow) is not null);
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, factory);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
fetcher.Bytes = badBytes;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(badBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
factory.Called.ShouldBeTrue();
|
||||
factory.CatalogWasActive.ShouldBeFalse(); // The callback observes that the key is already revoked.
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldBeNull();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Malformed_desired_artifact_closes_the_old_catalog_before_parsing()
|
||||
{
|
||||
var firstBytes = Artifact();
|
||||
var malformed = Encoding.UTF8.GetBytes("{bad-json");
|
||||
var fetcher = new MutableFetcher(firstBytes);
|
||||
var coordinator = NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation());
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(firstBytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
var old = coordinator.Current.ShouldNotBeNull();
|
||||
old.IsActive.ShouldBeTrue();
|
||||
|
||||
fetcher.Bytes = malformed;
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(malformed), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Failed);
|
||||
coordinator.Current.ShouldBeNull();
|
||||
old.IsActive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_and_publish_actor_join_one_attempt_and_wait_for_successful_topology()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var coordinator = NewCoordinator(authority, activation);
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var sink = NullOpcUaAddressSpaceSink.Instance;
|
||||
var hooks = new OpcUaPublishActor.TestHooks { BeforeComposition = () => { entered.Set(); release.Wait(); } };
|
||||
var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
|
||||
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
|
||||
dataPlaneAuthority: authority, catalogCoordinator: coordinator));
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acks.Ref, publish: publish);
|
||||
try
|
||||
{
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
||||
activation.Current.CatalogEpoch.ShouldBe(1);
|
||||
activation.Current.IsReady.ShouldBeFalse();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
release.Set();
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
activation.Current.CatalogEpoch.ShouldBe(1);
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Role_transition_reuses_the_adjusted_catalog_and_does_not_freshen_the_cached_acquisition()
|
||||
{
|
||||
var role = "Primary";
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
|
||||
() => BootIdentity with { Role = role });
|
||||
var attempt = Prepare(coordinator, Artifact(includeDriver: true, includeTag: true));
|
||||
coordinator.Complete(attempt, topologySucceeded: true).ShouldBeTrue();
|
||||
var original = coordinator.Current.ShouldNotBeNull();
|
||||
var source = original.Nodes.Single(x => x.EntityKind == "RawTag").Source.ShouldNotBeNull();
|
||||
using var hub = HubTest.Create();
|
||||
var ticket = new SourceTicket(source, new SourceGeneration(1, 1));
|
||||
hub.TryBind(ticket).ShouldBeTrue();
|
||||
var timestamp = DateTimeOffset.Parse("2026-01-02T03:04:05Z");
|
||||
hub.TryReserveIngress(ticket, 512, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, timestamp, timestamp,
|
||||
coordinator.Serving, 7);
|
||||
if (!reservation!.TryCommit(sample, 7)) { sample.Dispose(); throw new InvalidOperationException(); }
|
||||
}
|
||||
hub.ProcessPending();
|
||||
using var before = hub.Read(ticket);
|
||||
before.Sample.ShouldNotBeNull();
|
||||
|
||||
role = "Secondary";
|
||||
var secondary = coordinator.Current.ShouldNotBeNull();
|
||||
secondary.Serving.Role.ShouldBe("Secondary");
|
||||
ReferenceEquals(secondary, coordinator.Current).ShouldBeTrue();
|
||||
ReferenceEquals(secondary.Nodes, original.Nodes).ShouldBeTrue();
|
||||
coordinator.Serving.ShouldBe(secondary.Serving);
|
||||
using var after = hub.Read(ticket);
|
||||
after.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
after.Sample.ShouldNotBeNull().SourceTimestampUtc.ShouldBe(timestamp);
|
||||
after.Sample!.Version.ShouldBe(7);
|
||||
after.ReceivedTimestamp.ShouldBe(before.ReceivedTimestamp);
|
||||
secondary.Serving.CatalogEpoch.ShouldBe(original.Serving.CatalogEpoch);
|
||||
secondary.Serving.AuthorityEpoch.ShouldBe(original.Serving.AuthorityEpoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Host_rejects_a_catalog_stamped_with_a_different_serving_node()
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority,
|
||||
() => BootIdentity with { NodeId = "node-b" });
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acks.Ref);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(bytes), CorrelationId.NewId()));
|
||||
var ack = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
(ack.Outcome == ApplyAckOutcome.Failed || ack.Degraded).ShouldBeTrue();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Expected_catalog_failure_is_degraded_and_same_revision_dispatch_retries(bool withPublisher)
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var fetcher = new MutableFetcher(bytes);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var activation = new CatalogActivation();
|
||||
var identityAvailable = false;
|
||||
var coordinator = new LocalCatalogCoordinator(activation, authority, () => Volatile.Read(ref identityAvailable)
|
||||
? BootIdentity : throw new InvalidOperationException("temporary provenance failure"));
|
||||
IActorRef? publish = null;
|
||||
if (withPublisher)
|
||||
{
|
||||
var sink = NullOpcUaAddressSpaceSink.Instance;
|
||||
publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
|
||||
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks: null,
|
||||
localNode: Node, dataPlaneAuthority: authority, catalogCoordinator: coordinator));
|
||||
}
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(fetcher, coordinator, acks.Ref, publish: publish);
|
||||
var revision = Revision(bytes);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var first = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
(first.Outcome == ApplyAckOutcome.Failed || first.Degraded).ShouldBeTrue();
|
||||
coordinator.Current.ShouldBeNull();
|
||||
authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
var epoch = activation.Current.CatalogEpoch;
|
||||
|
||||
Volatile.Write(ref identityAvailable, true);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var repaired = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
repaired.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
repaired.Degraded.ShouldBeFalse();
|
||||
fetcher.Calls.ShouldBe(2);
|
||||
activation.Current.CatalogEpoch.ShouldBeGreaterThan(epoch);
|
||||
coordinator.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void Legacy_artifact_without_data_configuration_remains_clean(bool withCoordinator)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes("{\"DriverInstances\":[]}");
|
||||
var fetcher = new MutableFetcher(bytes);
|
||||
var acks = CreateTestProbe();
|
||||
var coordinator = withCoordinator ? NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation()) : null;
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: Node, ackRouter: acks.Ref,
|
||||
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher,
|
||||
catalogCoordinator: coordinator));
|
||||
var revision = Revision(bytes);
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var first = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
first.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
first.Degraded.ShouldBeFalse();
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), revision, CorrelationId.NewId()));
|
||||
var second = acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
second.Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
second.Degraded.ShouldBeFalse();
|
||||
fetcher.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(false, false)]
|
||||
[InlineData(false, true)]
|
||||
public async Task Cache_and_restore_wait_for_subscription_work_before_sending_the_catalog_to_the_publisher(bool cacheBoot, bool fail)
|
||||
{
|
||||
var bytes = Artifact();
|
||||
var deployment = DeploymentId.NewId();
|
||||
var revision = Revision(bytes);
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> db;
|
||||
IDeploymentArtifactCache? cache = null;
|
||||
if (cacheBoot)
|
||||
{
|
||||
db = new ThrowingDbFactory();
|
||||
cache = new BootCache(new(deployment.ToString(), revision.Value, bytes, DateTimeOffset.UtcNow));
|
||||
}
|
||||
else
|
||||
{
|
||||
db = NewInMemoryDbFactory();
|
||||
using var context = db.CreateDbContext();
|
||||
context.Deployments.Add(new Deployment { DeploymentId = deployment.Value, RevisionHash = revision.Value,
|
||||
Status = DeploymentStatus.Sealed, CreatedBy = "test", SealedAtUtc = DateTime.UtcNow, ArtifactBlob = bytes });
|
||||
context.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = Node.Value, DeploymentId = deployment.Value,
|
||||
Status = NodeDeploymentStatus.Applied, StartedAtUtc = DateTime.UtcNow });
|
||||
context.SaveChanges();
|
||||
}
|
||||
var catalog = NewCoordinator(new DataPlaneAuthorityState(), new CatalogActivation());
|
||||
var publish = CreateTestProbe();
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var cancellationToken = TestContext.Current.CancellationToken;
|
||||
catalog.BeforeSubscriptionApplyForTests = () =>
|
||||
{
|
||||
entered.Set();
|
||||
release.Wait(cancellationToken);
|
||||
if (fail) throw new InvalidOperationException("subscription work failed");
|
||||
};
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(db, Node, localRoles: new HashSet<string> { "driver" },
|
||||
deploymentArtifactCache: cache, opcUaPublishActor: publish.Ref, catalogCoordinator: catalog));
|
||||
try
|
||||
{
|
||||
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
||||
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
release.Set();
|
||||
if (fail)
|
||||
{
|
||||
await host.Ask<ActorIdentity>(new Identify("started"), PresenceBudget, cancellationToken);
|
||||
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
|
||||
catalog.Current.ShouldBeNull();
|
||||
}
|
||||
else
|
||||
{
|
||||
var rebuild = publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(PresenceBudget,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
rebuild.Artifact.ShouldBe(bytes);
|
||||
rebuild.CatalogAttempt.ShouldNotBeNull();
|
||||
}
|
||||
}
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Direct_restore_uses_the_loaded_artifact_to_subscribe_the_real_deferred_driver_without_a_third_db_read()
|
||||
{
|
||||
var bytes = Artifact(includeDriver: true, includeTag: true);
|
||||
var deployment = DeploymentId.NewId();
|
||||
var revision = Revision(bytes);
|
||||
var underlying = NewInMemoryDbFactory();
|
||||
using (var context = underlying.CreateDbContext())
|
||||
{
|
||||
context.Deployments.Add(new Deployment { DeploymentId = deployment.Value, RevisionHash = revision.Value,
|
||||
Status = DeploymentStatus.Sealed, CreatedBy = "test", SealedAtUtc = DateTime.UtcNow, ArtifactBlob = bytes });
|
||||
context.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = Node.Value, DeploymentId = deployment.Value,
|
||||
Status = NodeDeploymentStatus.Applied, StartedAtUtc = DateTime.UtcNow });
|
||||
context.SaveChanges();
|
||||
}
|
||||
var db = new TwoReadDbFactory(underlying);
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var catalog = NewCoordinator(authority, new CatalogActivation());
|
||||
using var hub = HubTest.Create(bytes: 1_000_000);
|
||||
var publisher = new SourceSamplePublisher(hub, () => catalog.Serving, "cluster");
|
||||
var factory = new RecordingSubscribableDriverFactory("Modbus");
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(db, Node, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "driver" }, sourcePublisher: publisher, catalogCoordinator: catalog));
|
||||
|
||||
await host.Ask<ActorIdentity>(new Identify("started"), PresenceBudget, TestContext.Current.CancellationToken);
|
||||
db.Calls.ShouldBe(2); // Bootstrap and artifact load; any third read would have thrown.
|
||||
catalog.Current.ShouldNotBeNull().IsActive.ShouldBeTrue();
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
var driver = factory.Created.ShouldHaveSingleItem();
|
||||
driver.LastSubscribedRefs.ShouldNotBeNull().ShouldContain("Plant/Driver/Device/Speed");
|
||||
}, duration: PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private static LocalCatalogCoordinator NewCoordinator(DataPlaneAuthorityState authority, CatalogActivation activation) =>
|
||||
new(activation, authority, () => BootIdentity);
|
||||
|
||||
private static CatalogAttempt Prepare(LocalCatalogCoordinator coordinator, byte[] bytes)
|
||||
{
|
||||
var attempt = coordinator.BeginAttempt(Hash(bytes));
|
||||
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, Node.Value)).ShouldBeTrue();
|
||||
using var parsed = DeploymentArtifact.Open(bytes);
|
||||
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot(Node.Value)!).ShouldBeTrue();
|
||||
return attempt;
|
||||
}
|
||||
|
||||
private IActorRef NewHost(byte[] bytes, LocalCatalogCoordinator coordinator, IActorRef acks,
|
||||
IDriverFactory? factory = null, IActorRef? publish = null) =>
|
||||
NewHost(new MutableFetcher(bytes), coordinator, acks, factory, publish);
|
||||
|
||||
private IActorRef NewHost(MutableFetcher fetcher, LocalCatalogCoordinator coordinator, IActorRef acks,
|
||||
IDriverFactory? factory = null, IActorRef? publish = null) => Sys.ActorOf(DriverHostActor.Props(
|
||||
dbFactory: null, localNode: Node, ackRouter: acks, driverFactory: factory,
|
||||
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher,
|
||||
opcUaPublishActor: publish, catalogCoordinator: coordinator));
|
||||
|
||||
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
private static RevisionHash Revision(byte[] bytes) => RevisionHash.Parse(Hash(bytes));
|
||||
|
||||
private static byte[] Artifact(bool revoked = false, bool includeDriver = false, bool invalidExport = false, bool includeTag = false)
|
||||
{
|
||||
var root = JsonNode.Parse("""
|
||||
{
|
||||
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
|
||||
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
|
||||
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
|
||||
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":3}],
|
||||
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
|
||||
"DriverInstances":[],"Devices":[],"TagGroups":[],"Tags":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
|
||||
"DataConnections":[],"RemoteNamespaceMappings":[],
|
||||
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":7}]
|
||||
}
|
||||
""")!.AsObject();
|
||||
root["ApiKeys"]![0]!["Enabled"] = !revoked;
|
||||
if (includeDriver)
|
||||
root["DriverInstances"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}
|
||||
"""));
|
||||
if (includeTag)
|
||||
{
|
||||
root["Devices"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}
|
||||
"""));
|
||||
root["Tags"]!.AsArray().Add(JsonNode.Parse("""
|
||||
{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":0,"TagConfig":"{}"}
|
||||
"""));
|
||||
}
|
||||
if (invalidExport) root["DataExports"]![0]!["RootEntityId"] = "missing";
|
||||
return Encoding.UTF8.GetBytes(root.ToJsonString());
|
||||
}
|
||||
|
||||
private sealed class MutableFetcher(byte[] bytes) : IDeploymentArtifactFetcher
|
||||
{
|
||||
private int _calls;
|
||||
public byte[] Bytes { get; set; } = bytes;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public Task<byte[]?> FetchAsync(string deploymentId, string expectedRevisionHash, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult<byte[]?>(Bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingDbFactory : IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
public OtOpcUaConfigDbContext CreateDbContext() => throw new InvalidOperationException("ConfigDb unreachable");
|
||||
}
|
||||
|
||||
private sealed class TwoReadDbFactory(IDbContextFactory<OtOpcUaConfigDbContext> inner) : IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
private int _calls;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public OtOpcUaConfigDbContext CreateDbContext()
|
||||
{
|
||||
if (Interlocked.Increment(ref _calls) > 2) throw new InvalidOperationException("unexpected third ConfigDb read");
|
||||
return inner.CreateDbContext();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class BootCache(CachedDeploymentArtifact artifact) : IDeploymentArtifactCache
|
||||
{
|
||||
public Task StoreAsync(string clusterId, string deploymentId, string revisionHash, byte[] bytes, CancellationToken ct = default) => Task.CompletedTask;
|
||||
public Task<CachedDeploymentArtifact?> GetCurrentAsync(string clusterId, CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
|
||||
public Task<CachedDeploymentArtifact?> GetCurrentUnkeyedAsync(CancellationToken ct = default) => Task.FromResult<CachedDeploymentArtifact?>(artifact);
|
||||
}
|
||||
|
||||
private sealed class ObservingFactory(Func<bool> observe) : IDriverFactory
|
||||
{
|
||||
public bool Called { get; private set; }
|
||||
public bool CatalogWasActive { get; private set; }
|
||||
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
|
||||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
|
||||
{
|
||||
Called = true;
|
||||
CatalogWasActive = observe();
|
||||
return null; // The real host still creates its normal stub child.
|
||||
}
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataIngressOverflowTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(true, true)]
|
||||
[InlineData(true, false)]
|
||||
[InlineData(false, true)]
|
||||
[InlineData(false, false)]
|
||||
public void Repartition_retains_old_source_quota_until_the_last_owner_releases_it(bool holdRead, bool limitSourceCount)
|
||||
{
|
||||
// Both keys are large enough that source metadata, rather than just a scalar lease,
|
||||
// determines admission under the byte-limited cases.
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: limitSourceCount ? 100_000 : 10_000,
|
||||
maxSources: limitSourceCount ? 1 : 10);
|
||||
var old = HubTest.Ticket("driver", new string('a', 2000));
|
||||
var replacement = HubTest.Ticket("driver", new string('b', 2000));
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
|
||||
using var heldRead = holdRead ? hub.Read(old) : null;
|
||||
IIngressReservation? heldReservation = null;
|
||||
if (holdRead) heldRead!.IsValid.ShouldBeTrue();
|
||||
else hub.TryReserveIngress(old, 288, out heldReservation).ShouldBeTrue();
|
||||
using (heldReservation)
|
||||
{
|
||||
hub.Repartition(2);
|
||||
if (holdRead) heldRead!.IsValid.ShouldBeFalse();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(4_000);
|
||||
hub.TryBind(replacement).ShouldBeFalse();
|
||||
|
||||
if (holdRead) heldRead!.Dispose();
|
||||
else
|
||||
{
|
||||
using var stale = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
heldReservation!.TryCommit(stale, 2).ShouldBeFalse();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(replacement).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repartition_retires_the_old_ticket_even_after_its_partition_is_disposed()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 10);
|
||||
var old = HubTest.Ticket("driver", new string('a', 1000));
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.Repartition(2);
|
||||
hub.TryBind(old).ShouldBeFalse();
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
var fresh = new SourceTicket(old.Key, old.Generation);
|
||||
hub.TryBind(fresh).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removed_source_churn_reclaims_bounded_registry_without_resurrecting_old_tickets()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: 100_000, maxSources: 2);
|
||||
var retired = new List<SourceTicket>();
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
var source = HubTest.Ticket("driver", $"churn-{i}");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
HubTest.Publish(hub, source, 1, i);
|
||||
hub.ProcessPending();
|
||||
hub.TryRemove(source, 2).ShouldBeTrue();
|
||||
hub.ProcessPending(); // worker has an opportunity to reclaim safe tombstones
|
||||
retired.Add(source);
|
||||
}
|
||||
foreach (var old in retired)
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
hub.TryBind(HubTest.Ticket("driver", "live")).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclaimed_binding_cannot_be_repaired_or_target_a_fresh_binding_with_the_same_generation()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var oldRead = hub.Read(old);
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
oldRead.IsValid.ShouldBeFalse();
|
||||
oldRead.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(old).ShouldBeFalse(); // even while no replacement source exists
|
||||
var replacement = new SourceTicket(old.Key, old.Generation);
|
||||
hub.TryBind(replacement).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(old.Key, out var resolved).ShouldBeTrue();
|
||||
resolved.ShouldBe(replacement);
|
||||
resolved.ShouldNotBe(old);
|
||||
HubTest.Publish(hub, replacement, 1, 2);
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(old).ShouldBeFalse();
|
||||
hub.TryReserveIngress(old, 288, out _).ShouldBeFalse();
|
||||
hub.Invalidate(old, "late callback");
|
||||
using var current = hub.Read(replacement);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclamation_waits_for_snapshot_references_to_release()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([old], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
hub.TryBind(other).ShouldBeFalse();
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
snapshot.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(other).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Reclamation_waits_for_disposal_of_outstanding_ingress_and_read_leases()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var old = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, old, 1, 1);
|
||||
hub.ProcessPending();
|
||||
var read = hub.Read(old);
|
||||
hub.TryReserveIngress(old, 288, out var reservation).ShouldBeTrue();
|
||||
hub.TryRemove(old, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
hub.TryBind(other).ShouldBeFalse();
|
||||
read.Dispose();
|
||||
reservation!.Dispose();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(other).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registry_overflow_invalidates_in_constant_producer_work_and_defers_cache_cleanup()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, bytes: 100_000, maxSources: 32);
|
||||
var sources = Enumerable.Range(0, 32).Select(i => HubTest.Ticket("driver", $"tag-{i}")).ToArray();
|
||||
foreach (var source in sources)
|
||||
{
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
}
|
||||
var chargedBeforeOverflow = hub.Resources.RetainedBytes;
|
||||
hub.TryBind(HubTest.Ticket("driver", "overflow")).ShouldBeFalse();
|
||||
// No source cache was scanned or released by the producer's failed bind.
|
||||
hub.Resources.RetainedBytes.ShouldBe(chargedBeforeOverflow);
|
||||
hub.ProcessPending();
|
||||
hub.Resources.RetainedBytes.ShouldBeLessThan(chargedBeforeOverflow);
|
||||
foreach (var source in sources)
|
||||
{
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deferred_partition_cleanup_preserves_a_fresh_post_overflow_sample()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.InvalidatePartitionFor(source.Key, "bounded recovery overflow");
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
read.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Admission_and_retirement_do_not_wait_for_a_busy_partition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var cancellationToken = TestContext.Current.CancellationToken;
|
||||
var owner = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => { entered.Set(); release.Wait(cancellationToken); }), cancellationToken);
|
||||
try
|
||||
{
|
||||
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
|
||||
var producer = Task.Run(() =>
|
||||
{
|
||||
hub.TryReserveIngress(source, 288, out _).ShouldBeFalse();
|
||||
hub.TryRemove(source, 2).ShouldBeFalse();
|
||||
hub.IsTicketCurrentNonBlocking(source).ShouldBeFalse();
|
||||
}, cancellationToken);
|
||||
await producer.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
release.Set();
|
||||
await owner.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
|
||||
}
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void In_flight_copy_cannot_restore_readiness_after_an_overflow_fence()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryReserveIngress(source, 288, out var oldReservation).ShouldBeTrue();
|
||||
hub.Invalidate(source, "overflow");
|
||||
HubTest.Publish(hub, source, 3, 3);
|
||||
hub.ProcessPending();
|
||||
using (oldReservation!)
|
||||
using (var old = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2))
|
||||
oldReservation!.TryCommit(old, 2).ShouldBeFalse();
|
||||
using var current = hub.Read(source);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Understated_reservation_is_rejected_without_transferring_sample_ownership()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 287, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
using (var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, null, HubTest.Serving, 1))
|
||||
{
|
||||
reservation!.TryCommit(sample, 1).ShouldBeFalse();
|
||||
sample.Value.GetScalar().ShouldBe(7); // failed commit leaves ownership with caller
|
||||
}
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Source_registry_reuses_capacity_after_tombstone_cleanup()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, maxSources: 1);
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
HubTest.BindAndPublish(hub, first, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryRemove(first, 2).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
hub.TryBind(second).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(first.Key, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Admission_rejects_before_copy_and_synchronously_invalidates_previously_good_cache()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 7);
|
||||
hub.ProcessPending();
|
||||
var copied = false;
|
||||
if (hub.TryReserveIngress(source, 288, out var reservation))
|
||||
{
|
||||
using (reservation!) copied = true; // production copies only after successful admission
|
||||
}
|
||||
copied.ShouldBeFalse();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
read.Status.ShouldNotBe(DataItemStatus.Good);
|
||||
// Recreating a consumer cannot turn the old cache into a fresh Good snapshot.
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!) snapshot!.Items[source].Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Abandoned_reservation_releases_global_quota_exactly_once()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
var before = hub.Resources.RetainedBytes;
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(before);
|
||||
reservation!.Dispose();
|
||||
reservation.Dispose();
|
||||
hub.Resources.RetainedBytes.ShouldBe(before);
|
||||
hub.TryReserveIngress(source, 288, out var replacement).ShouldBeTrue();
|
||||
replacement!.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dirty_table_exhaustion_invalidates_partition_and_resets_existing_consumers()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1, ingress: 1, dirty: 1);
|
||||
var a = HubTest.Ticket("driver", "a");
|
||||
var b = HubTest.Ticket("driver", "b");
|
||||
var c = HubTest.Ticket("driver", "c");
|
||||
foreach (var source in new[] { a, b, c })
|
||||
{
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
}
|
||||
hub.TryCaptureSnapshot([a, b, c], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, a, 2, 2); // fills ingress
|
||||
HubTest.Publish(hub, b, 2, 2); // fills the one-entry coalescing table
|
||||
var admitted = hub.TryReserveIngress(c, 288, out var reservation);
|
||||
if (admitted)
|
||||
{
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
var committed = reservation!.TryCommit(sample, 2);
|
||||
if (!committed) sample.Dispose();
|
||||
committed.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
foreach (var source in new[] { a, b, c })
|
||||
{
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
hub.ProcessPending();
|
||||
// Only a fresh retained sample after invalidation may restore readiness.
|
||||
using var stale = hub.Read(c);
|
||||
stale.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Status_control_overtaking_queued_value_never_resurrects_good_quality()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.TryPublishStatus(source, 3, 0x80310000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
if (read.Sample is not null) read.Sample.StatusCode.ShouldBe(0x80310000u);
|
||||
else read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void New_dirty_generation_is_seen_after_a_previous_delta_was_consumed()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
snapshot!.TryReadDelta(source, out var first).ShouldBeTrue();
|
||||
using (first!) first!.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
HubTest.Publish(hub, source, 3, 3);
|
||||
hub.ProcessPending();
|
||||
snapshot.TryReadDelta(source, out var second).ShouldBeTrue();
|
||||
using (second!) second!.Sample!.Value.GetScalar().ShouldBe(3);
|
||||
}
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
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;
|
||||
|
||||
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 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;
|
||||
internal readonly LocalExportCatalog Catalog;
|
||||
internal readonly DataAuthenticatedContext Context;
|
||||
|
||||
internal LocalDataFixture(int additionalRawNodes = 0)
|
||||
{
|
||||
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 = NodeAclScopeKind.RawFolder,
|
||||
ScopeId = "folder", PermissionFlags = NodePermissions.ReadOnly }],
|
||||
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
||||
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;
|
||||
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
|
||||
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
|
||||
var unsMetadata = rawMetadata with { View = Uns };
|
||||
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"] }, Root, Ticket.Key),
|
||||
new("UnsTagReference", "reference", unsMetadata, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Uns, Segments = ["Area", "Line", "Equipment", "Speed"] }, null, 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 = "UnsTagReference", RootEntityId = "reference", PrincipalId = "peer", AllowedOperations = operations }]);
|
||||
var limits = new DataLimits(100, 100, 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);
|
||||
}
|
||||
|
||||
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", "node-a"));
|
||||
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();
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataLocalExportCatalogTests
|
||||
{
|
||||
[Fact]
|
||||
public void Deployed_origin_catalog_uses_actual_Uns_folder_ids_and_one_backing_source_for_both_realms()
|
||||
{
|
||||
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" }],
|
||||
DriverInstances = [new() { DriverInstanceId = "driver", ClusterId = "cluster", RawFolderId = "folder", Name = "Driver", DriverType = "ModbusTcp", DriverConfig = "{}" }],
|
||||
Devices = [new() { DeviceId = "device", DriverInstanceId = "driver", Name = "Device", DeviceConfig = "{}" }],
|
||||
Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" }],
|
||||
UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }],
|
||||
UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }],
|
||||
Equipment = [new() { EquipmentId = "equipment-id", UnsLineId = "line-id", Name = "Equipment", MachineCode = "E" }],
|
||||
UnsTagReferences = [new() { UnsTagReferenceId = "reference", EquipmentId = "equipment-id", TagId = "tag" }],
|
||||
DataExports = [new() { DataExportId = "raw", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
|
||||
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read },
|
||||
new() { DataExportId = "uns", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Uns,
|
||||
RootKind = "Cluster", RootEntityId = "cluster", PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read }]
|
||||
};
|
||||
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
||||
var raw = catalog.Nodes.Single(x => x.EntityKind == "RawTag");
|
||||
var uns = catalog.Nodes.Single(x => x.EntityKind == "UnsTagReference");
|
||||
raw.Source.ShouldBe(uns.Source);
|
||||
raw.Source.ShouldBe(SourceKey.ForDriver("cluster", "driver", "Plant/Driver/Device/Speed", "node-a", "serving-1"));
|
||||
var area = catalog.Nodes.Single(x => x.EntityKind == "UnsArea");
|
||||
area.Metadata.View.Address.Identifier.ShouldBe("area-id");
|
||||
area.Scope.Segments.ShouldBe(["Area"]);
|
||||
uns.Metadata.View.Address.Identifier.ShouldBe("Area/Line/Equipment/Speed");
|
||||
catalog.Nodes.ShouldNotContain(x => x.EntityKind == "RemoteNamespaceMapping");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void Catalog_rejects_projected_or_foreign_nodes_as_origin_local_exports(bool projected)
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var valid = fixture.Catalog.Nodes.First();
|
||||
var invalidView = projected
|
||||
? valid.Metadata.View with { MappingId = "remote", MappingRevision = 1 }
|
||||
: valid.Metadata.View with { Address = valid.Metadata.View.Address with { OriginClusterId = "foreign" } };
|
||||
var invalid = valid with { Metadata = valid.Metadata with { View = invalidView } };
|
||||
Should.Throw<ArgumentException>(() => new LocalExportCatalog("cluster", fixture.Serving,
|
||||
fixture.Activation.CaptureAuthority(), [invalid], []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catalog_token_is_invalidated_by_a_new_desired_revision()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
fixture.Catalog.IsActive.ShouldBeTrue();
|
||||
fixture.Activation.Begin("next");
|
||||
fixture.Catalog.IsActive.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Catalog_metadata_and_read_batch_limits_are_checked_before_response_allocation()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
await using var connection = fixture.Connection();
|
||||
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
||||
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => connection.GetMetadataAsync(new([fixture.Raw, fixture.Uns], budget), TestContext.Current.CancellationToken));
|
||||
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => connection.ReadAsync(new([new("a", fixture.Raw, null), new("b", fixture.Uns, null)], budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataPartitionTests
|
||||
{
|
||||
[Fact]
|
||||
public void Retiring_producer_fences_all_its_sources_and_existing_snapshots_immediately()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
var independent = HubTest.Ticket("other", "tag");
|
||||
var fence = new ProducerFence(1);
|
||||
hub.TryBind(first, fence).ShouldBeTrue();
|
||||
hub.TryBind(second, fence).ShouldBeTrue();
|
||||
HubTest.Publish(hub, first, 1, 10);
|
||||
HubTest.Publish(hub, second, 1, 20);
|
||||
HubTest.BindAndPublish(hub, independent, 1, 30);
|
||||
hub.ProcessPending();
|
||||
using var captured = hub.Read(first);
|
||||
captured.IsValid.ShouldBeTrue();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
fence.Retire();
|
||||
captured.IsValid.ShouldBeFalse();
|
||||
hub.IsTicketCurrentNonBlocking(first).ShouldBeFalse();
|
||||
hub.TryGetCurrentTicket(second.Key, out _).ShouldBeFalse();
|
||||
using var rejected = hub.Read(first);
|
||||
rejected.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
hub.TryRemove(first, 2).ShouldBeTrue(); // closed producer still permits deferred tombstone cleanup
|
||||
using var unaffected = hub.Read(independent);
|
||||
unaffected.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
unaffected.Sample!.Value.GetScalar().ShouldBe(30);
|
||||
hub.TryBind(first, new ProducerFence(1)).ShouldBeFalse();
|
||||
var replacement = new SourceTicket(first.Key, new SourceGeneration(2, 1));
|
||||
hub.TryBind(replacement, new ProducerFence(2)).ShouldBeTrue();
|
||||
HubTest.Publish(hub, replacement, 1, 40);
|
||||
hub.ProcessPending();
|
||||
using var rebound = hub.Read(replacement);
|
||||
rebound.Sample!.Value.GetScalar().ShouldBe(40);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_read_validity_survives_new_values_but_not_source_invalidation_or_disposal()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
var other = HubTest.Ticket("driver", "other");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
HubTest.BindAndPublish(hub, other, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.IsValid.ShouldBeTrue();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
hub.Invalidate(other, "unrelated source");
|
||||
read.IsValid.ShouldBeTrue();
|
||||
read.Sample!.Value.GetScalar().ShouldBe(1);
|
||||
hub.Invalidate(source, "source overload");
|
||||
read.IsValid.ShouldBeFalse();
|
||||
read.Dispose();
|
||||
read.IsValid.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Retained_read_validity_tracks_partition_reset_removal_and_repartition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
using var beforeReset = hub.Read(source);
|
||||
hub.InvalidatePartitionFor(source.Key, "overload");
|
||||
beforeReset.IsValid.ShouldBeFalse();
|
||||
HubTest.Publish(hub, source, 2, 2);
|
||||
hub.ProcessPending();
|
||||
using var beforeRemove = hub.Read(source);
|
||||
beforeRemove.IsValid.ShouldBeTrue();
|
||||
hub.TryRemove(source, 3).ShouldBeTrue();
|
||||
beforeRemove.IsValid.ShouldBeFalse();
|
||||
var next = new SourceTicket(source.Key, new SourceGeneration(1, 2));
|
||||
hub.TryBind(next).ShouldBeTrue();
|
||||
HubTest.Publish(hub, next, 1, 3);
|
||||
hub.ProcessPending();
|
||||
using var beforeRepartition = hub.Read(next);
|
||||
beforeRepartition.IsValid.ShouldBeTrue();
|
||||
hub.Repartition(2);
|
||||
beforeRepartition.IsValid.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Quiet_initial_acquisition_is_retained_before_catalog_activation_without_inventing_epochs()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "quiet");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var serving = HubTest.Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 };
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 23), 0, null, null, serving, 1);
|
||||
reservation!.TryCommit(sample, 1).ShouldBeTrue();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
using var acquisition = hub.Read(source);
|
||||
acquisition.Sample!.Value.GetScalar().ShouldBe(23);
|
||||
acquisition.Sample.Serving.CatalogEpoch.ShouldBe(0);
|
||||
acquisition.Sample.Serving.AuthorityEpoch.ShouldBe(0);
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => acquisition.Sample.Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Views_share_the_backing_sample_but_distinct_acquisitions_and_replicas_do_not()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver-a", "tag");
|
||||
var otherAcquisition = HubTest.Ticket("driver-b", "tag");
|
||||
var otherReplica = HubTest.Ticket("driver-a", "tag", "node-b");
|
||||
HubTest.BindAndPublish(hub, source, 1, 42);
|
||||
hub.TryBind(otherAcquisition).ShouldBeTrue();
|
||||
hub.TryBind(otherReplica).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
|
||||
// Both view descriptors resolve to the same explicit catalog source; a view is never a cache key.
|
||||
var raw = new DataView(HubTest.Address, DataRealm.Raw, null, 0, "raw/tag");
|
||||
var uns = new DataView(HubTest.Address, DataRealm.Uns, null, 0, "uns/tag");
|
||||
raw.Realm.ShouldNotBe(uns.Realm);
|
||||
using var rawRead = hub.Read(source);
|
||||
using var unsRead = hub.Read(source);
|
||||
using var acquisitionRead = hub.Read(otherAcquisition);
|
||||
using var replicaRead = hub.Read(otherReplica);
|
||||
rawRead.Sample!.Value.GetScalar().ShouldBe(42);
|
||||
unsRead.Sample!.Value.GetScalar().ShouldBe(42);
|
||||
acquisitionRead.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
replicaRead.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Removal_fences_queued_values_and_rebind_rejects_old_ticket_without_harming_new_sample()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var first = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, first, 1, 10);
|
||||
hub.ProcessPending();
|
||||
HubTest.Publish(hub, first, 2, 20); // remains queued while the removal is admitted
|
||||
hub.TryRemove(first, 3).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using (var removed = hub.Read(first)) removed.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
hub.TryGetCurrentTicket(first.Key, out _).ShouldBeFalse();
|
||||
|
||||
var next = new SourceTicket(first.Key, new SourceGeneration(1, 2));
|
||||
hub.TryBind(next).ShouldBeTrue();
|
||||
hub.TryGetCurrentTicket(next.Key, out var resolved).ShouldBeTrue();
|
||||
resolved.ShouldBe(next);
|
||||
HubTest.Publish(hub, next, 4, 30);
|
||||
hub.ProcessPending();
|
||||
hub.Invalidate(first, "late callback");
|
||||
hub.TryReserveIngress(first, 288, out _).ShouldBeFalse();
|
||||
using var current = hub.Read(next);
|
||||
current.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
current.Sample!.Value.GetScalar().ShouldBe(30);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Status_is_ordered_and_retains_payload_without_manufacturing_a_good_initial_sample()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryPublishStatus(source, 1, 0x80000000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using (var initial = hub.Read(source))
|
||||
{
|
||||
initial.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
initial.Sample.ShouldBeNull();
|
||||
}
|
||||
HubTest.Publish(hub, source, 2, 12);
|
||||
hub.ProcessPending();
|
||||
var timestamp = new DateTimeOffset(2026, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
hub.TryPublishStatus(source, 3, 0x80310001u, timestamp, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var status = hub.Read(source);
|
||||
status.Sample!.Value.GetScalar().ShouldBe(12);
|
||||
status.Sample.StatusCode.ShouldBe(0x80310001u);
|
||||
status.Sample.SourceTimestampUtc.ShouldBe(timestamp);
|
||||
status.Sample.ServerTimestampUtc.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Synthetic_status_preserves_original_acquisition_timestamps()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
var sourceTime = new DateTimeOffset(2026, 2, 1, 2, 3, 4, TimeSpan.Zero);
|
||||
var serverTime = sourceTime.AddMilliseconds(37);
|
||||
hub.TryBind(source).ShouldBeTrue();
|
||||
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 12), 0,
|
||||
sourceTime, serverTime, HubTest.Serving, 1);
|
||||
reservation!.TryCommit(sample, 1).ShouldBeTrue();
|
||||
}
|
||||
hub.ProcessPending();
|
||||
hub.TryPublishStatus(source, 2, 0x80310000u, null, null).ShouldBeTrue();
|
||||
hub.ProcessPending();
|
||||
using var read = hub.Read(source);
|
||||
read.Sample!.Value.GetScalar().ShouldBe(12);
|
||||
read.Sample.StatusCode.ShouldBe(0x80310000u);
|
||||
read.Sample.SourceTimestampUtc.ShouldBe(sourceTime);
|
||||
read.Sample.ServerTimestampUtc.ShouldBe(serverTime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Repartition_resets_existing_snapshots_and_does_not_make_old_values_fresh()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 42);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
hub.Repartition(3);
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
using var read = hub.Read(source);
|
||||
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static class HubTest
|
||||
{
|
||||
internal static readonly DataAddress Address = new("cluster", "urn:raw", "string", "tag");
|
||||
internal static readonly DataBudget Budget = new(TimeSpan.FromMinutes(1), 100, 100_000);
|
||||
internal static readonly ServingIdentity Serving = new("node-a", "serving-1", "Primary", 1, 1);
|
||||
|
||||
internal static PartitionedSampleHub Create(int partitions = 2, long bytes = 10_000,
|
||||
int ingress = 10, int dirty = 10, TimeProvider? clock = null, int maxSources = 100) =>
|
||||
new(new DataResourceLimits
|
||||
{
|
||||
PartitionCount = partitions, MaxRetainedBytes = bytes, MaxTrackedSources = maxSources,
|
||||
MaxIngressItemsPerPartition = ingress, MaxDirtySourcesPerPartition = dirty,
|
||||
MaxControlItemsPerPartition = 10, MaxSnapshotItems = 100,
|
||||
MaxSnapshotBytes = 10_000, MaxSnapshotCatchUpItems = 1,
|
||||
MaxSnapshotLifetime = TimeSpan.FromMinutes(1)
|
||||
}, clock ?? new ManualTimeProvider(), autoDrain: false);
|
||||
|
||||
internal static SourceTicket Ticket(string driver, string tag, string node = "node-a") =>
|
||||
new(new BackingSourceKey("cluster", "driver", $"{driver.Length}:{driver}{tag.Length}:{tag}", node, "serving-1"),
|
||||
new SourceGeneration(1, 1));
|
||||
|
||||
internal static void BindAndPublish(PartitionedSampleHub hub, SourceTicket ticket, long version, int value)
|
||||
{
|
||||
hub.TryBind(ticket).ShouldBeTrue();
|
||||
Publish(hub, ticket, version, value);
|
||||
}
|
||||
|
||||
internal static void Publish(PartitionedSampleHub hub, SourceTicket ticket, long version, int value)
|
||||
{
|
||||
hub.TryReserveIngress(ticket, 288, out var reservation).ShouldBeTrue();
|
||||
using (reservation!)
|
||||
{
|
||||
var serving = Serving with { NodeId = ticket.Key.ServingNodeId, Incarnation = ticket.Key.ServingIncarnation };
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, value), 0, null, null, serving, version);
|
||||
if (!reservation!.TryCommit(sample, version)) { sample.Dispose(); throw new InvalidOperationException("Commit rejected"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P04")]
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GrpcDataSampleOwnershipTests : RuntimeActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public async Task Single_callback_copies_bytes_before_the_producer_reuses_them()
|
||||
{
|
||||
var driver = new CallbackDriver();
|
||||
var parent = CreateTestProbe();
|
||||
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver), TestContext.Current.CancellationToken);
|
||||
await Subscribe(actor, driver);
|
||||
|
||||
var bytes = new byte[] { 1, 2, 3 };
|
||||
driver.Fire("source", new DataValueSnapshot(bytes, OpcUaStatus.Good, null, null));
|
||||
Array.Fill(bytes, (byte)99);
|
||||
|
||||
var item = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(
|
||||
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Items.Single();
|
||||
item.Value.ShouldBeOfType<byte[]>().ShouldBe(new byte[] { 1, 2, 3 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Batch_callback_copies_the_collection_and_each_mutable_array()
|
||||
{
|
||||
var driver = new BatchCallbackDriver();
|
||||
var parent = CreateTestProbe();
|
||||
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
||||
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver), TestContext.Current.CancellationToken);
|
||||
await Subscribe(actor, driver);
|
||||
|
||||
var numbers = new[] { 10, 20 };
|
||||
var bytes = new byte[] { 4, 5 };
|
||||
var items = new[]
|
||||
{
|
||||
new DataChangeItem("numbers", new DataValueSnapshot(numbers, OpcUaStatus.Good, null, null)),
|
||||
new DataChangeItem("bytes", new DataValueSnapshot(bytes, OpcUaStatus.Good, null, null)),
|
||||
};
|
||||
driver.Fire(items);
|
||||
numbers[0] = 999;
|
||||
bytes[0] = 99;
|
||||
items[1] = new DataChangeItem("replacement", new DataValueSnapshot(0, OpcUaStatus.Good, null, null));
|
||||
|
||||
var batch = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(
|
||||
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
batch.Items.Count.ShouldBe(2);
|
||||
batch.Items[0].Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 10, 20 });
|
||||
batch.Items[1].FullReference.ShouldBe("bytes");
|
||||
batch.Items[1].Value.ShouldBeOfType<byte[]>().ShouldBe(new byte[] { 4, 5 });
|
||||
}
|
||||
|
||||
private async Task Subscribe(IActorRef actor, StubDriver driver)
|
||||
{
|
||||
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
||||
AwaitCondition(() => driver.InitializeCount > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
||||
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
|
||||
new DriverInstanceActor.Subscribe(new[] { "source", "numbers", "bytes" }, TimeSpan.FromMilliseconds(100)),
|
||||
PresenceBudget, TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private sealed class CallbackDriver : StubDriver, ISubscribable
|
||||
{
|
||||
private readonly StubHandle _handle = new();
|
||||
public event EventHandler<DataChangeEventArgs>? OnDataChange;
|
||||
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) => Task.FromResult<ISubscriptionHandle>(_handle);
|
||||
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
||||
public void Fire(string reference, DataValueSnapshot snapshot) => OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, reference, snapshot));
|
||||
}
|
||||
|
||||
private sealed class BatchCallbackDriver : StubDriver, IBatchSubscribable
|
||||
{
|
||||
private readonly StubHandle _handle = new();
|
||||
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
|
||||
public event EventHandler<DataChangeBatchEventArgs>? OnDataChangeBatch;
|
||||
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) => Task.FromResult<ISubscriptionHandle>(_handle);
|
||||
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
||||
public void Fire(IReadOnlyList<DataChangeItem> items) => OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(_handle, items));
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Category", "Unit")]
|
||||
[Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataSnapshotTests
|
||||
{
|
||||
[Fact]
|
||||
public void Snapshot_freezes_samples_and_its_watermarks_cover_every_participating_partition()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 2);
|
||||
var first = HubTest.Ticket("driver", "a");
|
||||
var second = Enumerable.Range(0, 1000).Select(i => HubTest.Ticket("driver", $"other-{i}"))
|
||||
.First(t => hub.GetPartition(t.Key) != hub.GetPartition(first.Key));
|
||||
HubTest.BindAndPublish(hub, first, 1, 10);
|
||||
HubTest.BindAndPublish(hub, second, 1, 20);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
snapshot!.Watermarks.Count.ShouldBe(2);
|
||||
snapshot.Items[first].Sample!.Value.GetScalar().ShouldBe(10);
|
||||
snapshot.Items[second].Sample!.Value.GetScalar().ShouldBe(20);
|
||||
HubTest.Publish(hub, first, 2, 11);
|
||||
hub.ProcessPending();
|
||||
snapshot.Items[first].Sample!.Value.GetScalar().ShouldBe(10);
|
||||
snapshot.TryReadDelta(first, out var delta).ShouldBeTrue();
|
||||
using (delta!) delta!.Sample!.Value.GetScalar().ShouldBe(11);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Racing_registration_and_update_cannot_lose_the_newer_value()
|
||||
{
|
||||
using var hub = HubTest.Create();
|
||||
var source = HubTest.Ticket("driver", "race");
|
||||
HubTest.BindAndPublish(hub, source, 1, 1);
|
||||
hub.ProcessPending();
|
||||
SnapshotLease? snapshot = null;
|
||||
var captured = false;
|
||||
var accepted = false;
|
||||
Parallel.Invoke(
|
||||
() => captured = hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out snapshot),
|
||||
() =>
|
||||
{
|
||||
if (hub.TryReserveIngress(source, 288, out var reservation))
|
||||
{
|
||||
using (reservation!)
|
||||
{
|
||||
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 2), 0, null, null, HubTest.Serving, 2);
|
||||
accepted = reservation!.TryCommit(sample, 2);
|
||||
if (!accepted) sample.Dispose();
|
||||
}
|
||||
}
|
||||
hub.ProcessPending();
|
||||
});
|
||||
if (!accepted)
|
||||
{
|
||||
if (captured) { snapshot!.IsReset.ShouldBeTrue(); snapshot.Dispose(); }
|
||||
using var invalidated = hub.Read(source);
|
||||
invalidated.Readiness.ShouldNotBe(DataReadiness.Ready);
|
||||
return;
|
||||
}
|
||||
if (!captured) return; // a reset during registration is an explicit retry boundary
|
||||
using (snapshot!)
|
||||
{
|
||||
var capturedValue = (int)snapshot!.Items[source].Sample!.Value.GetScalar();
|
||||
if (capturedValue == 1)
|
||||
{
|
||||
snapshot.TryReadDelta(source, out var delta).ShouldBeTrue();
|
||||
using (delta!) delta!.Sample!.Value.GetScalar().ShouldBe(2);
|
||||
}
|
||||
else capturedValue.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cancellation_and_deadline_actively_release_all_snapshot_resources()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
using var hub = HubTest.Create(clock: clock);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 9);
|
||||
hub.ProcessPending();
|
||||
var baseline = hub.Resources.RetainedBytes;
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, cancellation.Token, out var canceled).ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
|
||||
cancellation.Cancel();
|
||||
canceled!.IsReset.ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
canceled.Dispose(); // cancellation and explicit disposal are idempotent
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
|
||||
var shortBudget = HubTest.Budget with { Timeout = TimeSpan.FromSeconds(2) };
|
||||
hub.TryCaptureSnapshot([source], shortBudget, CancellationToken.None, out var expired).ShouldBeTrue();
|
||||
clock.Advance(TimeSpan.FromSeconds(2));
|
||||
expired!.IsReset.ShouldBeTrue();
|
||||
hub.Resources.RetainedBytes.ShouldBe(baseline);
|
||||
expired.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Snapshot_admission_is_global_and_rejects_before_retaining_more_payload()
|
||||
{
|
||||
using var hub = HubTest.Create(bytes: 1700);
|
||||
var source = HubTest.Ticket("driver", "tag");
|
||||
HubTest.BindAndPublish(hub, source, 1, 5);
|
||||
hub.ProcessPending();
|
||||
var before = hub.Resources.RetainedBytes;
|
||||
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var rejected).ShouldBeFalse();
|
||||
rejected.ShouldBeNull();
|
||||
hub.Resources.RetainedBytes.ShouldBe(before);
|
||||
using var read = hub.Read(source);
|
||||
read.Status.ShouldBe(DataItemStatus.ResourceExhausted);
|
||||
read.Sample.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Catch_up_overflow_resets_snapshot_instead_of_silently_losing_deltas()
|
||||
{
|
||||
using var hub = HubTest.Create(partitions: 1);
|
||||
var first = HubTest.Ticket("driver", "first");
|
||||
var second = HubTest.Ticket("driver", "second");
|
||||
HubTest.BindAndPublish(hub, first, 1, 1);
|
||||
HubTest.BindAndPublish(hub, second, 1, 1);
|
||||
hub.ProcessPending();
|
||||
hub.TryCaptureSnapshot([first, second], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
|
||||
using (snapshot!)
|
||||
{
|
||||
HubTest.Publish(hub, first, 2, 2);
|
||||
HubTest.Publish(hub, second, 2, 2);
|
||||
hub.ProcessPending();
|
||||
snapshot!.IsReset.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1011
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user