feat: add bounded shared grpc subscriptions and delivery scheduling

This commit is contained in:
Joseph Doherty
2026-11-16 07:31:57 -05:00
parent 92e6430e06
commit b710bf9f74
51 changed files with 9182 additions and 184 deletions
@@ -0,0 +1,115 @@
using Shouldly;
using Xunit;
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", "P06")]
public sealed class GrpcDataDeliveryFairnessTests
{
[Fact(Timeout = 30000)]
public async Task A_quota_blocked_waiter_does_not_strand_another_principal_with_a_free_global_slot()
{
var capacity = new SubscriptionTransportCapacity(2, 1, 1_000);
capacity.TryReserve("a", 100, out var active).ShouldBeTrue();
using var cancellation = new CancellationTokenSource();
var blockedA = capacity.ReserveAsync("a", 100, cancellation.Token).AsTask();
blockedA.IsCompleted.ShouldBeFalse();
var waitingB = capacity.ReserveAsync("b", 100, TestContext.Current.CancellationToken).AsTask();
try
{
var grantedB = await waitingB.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
grantedB.ShouldNotBeNull();
blockedA.IsCompleted.ShouldBeFalse();
grantedB.Dispose();
}
finally
{
cancellation.Cancel(); active!.Dispose();
try { await blockedA; } catch (OperationCanceledException) { }
}
}
[Fact]
public void Command_rate_limit_is_shared_by_case_insensitive_principal_and_uses_monotonic_time()
{
var clock = new ManualTimeProvider();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000, clock: clock, maxCommandsPerSecond: 2);
capacity.TryAdmitCommand("peer").ShouldBeTrue();
capacity.TryAdmitCommand("PEER").ShouldBeTrue();
capacity.TryAdmitCommand("peer").ShouldBeFalse();
capacity.TryAdmitCommand("other").ShouldBeTrue();
clock.Advance(TimeSpan.FromSeconds(1));
capacity.TryAdmitCommand("peer").ShouldBeTrue();
}
[Fact]
public async Task A_waiting_principal_gets_the_next_physical_writer_slot_before_a_hot_stream_reacquires_it()
{
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000);
capacity.TryReserve("busy", 500, out var busy).ShouldBeTrue();
var quiet = capacity.ReserveAsync("quiet", 500, TestContext.Current.CancellationToken).AsTask();
quiet.IsCompleted.ShouldBeFalse();
busy!.Dispose();
capacity.TryReserve("busy", 500, out _).ShouldBeFalse();
var granted = await quiet.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
granted.ShouldNotBeNull();
granted.Dispose();
capacity.ActiveOperations.ShouldBe(0);
}
[Fact]
public async Task Canceling_a_waiter_removes_it_without_consuming_a_future_slot()
{
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000);
capacity.TryReserve("busy", 500, out var busy).ShouldBeTrue();
using var cancellation = new CancellationTokenSource();
var waiting = capacity.ReserveAsync("quiet", 500, cancellation.Token).AsTask();
cancellation.Cancel();
await Should.ThrowAsync<OperationCanceledException>(async () => await waiting);
busy!.Dispose();
capacity.TryReserve("next", 500, out var next).ShouldBeTrue();
next!.Dispose();
}
[Fact]
public void Changing_hot_source_during_traversal_does_not_restart_or_starve_other_work()
{
var scheduler = new DeliveryScheduler(maxSources: 4, maxInterests: 16);
var hot = HubTest.Ticket("driver", "hot").Key;
var quiet = HubTest.Ticket("driver", "quiet").Key;
for (var i = 0; i < 8; i++) scheduler.TryRegister(hot, i + 1).ShouldBeTrue();
scheduler.TryRegister(quiet, 100).ShouldBeTrue();
scheduler.TryMarkDirty(hot, 1).ShouldBeTrue();
scheduler.TryMarkDirty(quiet, 1).ShouldBeTrue();
var first = scheduler.TakeSlice(2);
first.Count.ShouldBeLessThanOrEqualTo(2);
scheduler.TryMarkDirty(hot, 2).ShouldBeTrue();
var seen = first.ToList();
for (var i = 0; i < 16; i++)
{
var slice = scheduler.TakeSlice(2);
slice.Count.ShouldBeLessThanOrEqualTo(2);
seen.AddRange(slice);
}
seen.ShouldContain(x => x.Source == quiet && x.InterestId == 100);
foreach (var interest in Enumerable.Range(1, 8))
seen.ShouldContain(x => x.Source == hot && x.InterestId == interest);
seen.ShouldContain(x => x.Source == hot && x.Generation == 2);
}
[Fact]
public void Interest_and_dirty_capacity_are_enforced_before_allocating_more_work()
{
var scheduler = new DeliveryScheduler(maxSources: 1, maxInterests: 1);
var first = HubTest.Ticket("driver", "first").Key;
var second = HubTest.Ticket("driver", "second").Key;
scheduler.TryRegister(first, 1).ShouldBeTrue();
scheduler.TryRegister(first, 2).ShouldBeFalse();
scheduler.TryRegister(second, 3).ShouldBeFalse();
scheduler.TryMarkDirty(first, 1).ShouldBeTrue();
scheduler.TryMarkDirty(first, 2).ShouldBeTrue();
scheduler.TryMarkDirty(second, 1).ShouldBeFalse();
}
}
@@ -0,0 +1,146 @@
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", "P06")]
public sealed class GrpcDataDemandSharingTests
{
private static readonly DataSubscriptionSettings Slow = new(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2),
DataChangeTrigger.StatusValue, null);
private static readonly DataSubscriptionSettings Fast = Slow with { SamplingInterval = TimeSpan.FromMilliseconds(100) };
[Fact]
public void Ref_counts_are_shared_only_within_the_full_upstream_authority_key()
{
var registry = new UpstreamDemandRegistry(maxKeys: 8, maxInterests: 8);
var key = Key();
registry.TryAdd(key, Slow, out var first).ShouldBeTrue();
registry.TryAdd(key, Fast, out var second).ShouldBeTrue();
var otherPrincipal = key with { PrincipalId = "other" };
registry.TryAdd(otherPrincipal, Slow, out var isolated).ShouldBeTrue();
registry.GetState(key)!.InterestCount.ShouldBe(2);
registry.GetState(otherPrincipal)!.InterestCount.ShouldBe(1);
registry.GetState(key)!.Desired.SamplingInterval.ShouldBe(Fast.SamplingInterval);
second!.Dispose();
registry.GetState(key)!.InterestCount.ShouldBe(1);
first!.Dispose();
registry.GetState(key).ShouldBeNull();
registry.GetState(otherPrincipal)!.InterestCount.ShouldBe(1);
isolated!.Dispose();
registry.GetState(otherPrincipal).ShouldBeNull();
}
[Fact]
public void Principal_case_variants_share_the_same_demand_and_limits()
{
var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 2);
var key = Key();
registry.TryAdd(key, Slow, out var first).ShouldBeTrue();
registry.TryAdd(key with { PrincipalId = "PRINCIPAL" }, Fast, out var second).ShouldBeTrue();
registry.GetState(key)!.InterestCount.ShouldBe(2);
registry.GetState(key with { PrincipalId = "PRINCIPAL" })!.Desired.SamplingInterval.ShouldBe(Fast.SamplingInterval);
first!.Dispose(); second!.Dispose();
}
[Fact]
public void Adding_and_removing_interests_does_not_copy_the_whole_existing_registration_set()
{
var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 2048);
var key = Key();
var leases = new List<IDisposable>(1100);
for (var i = 0; i < 1024; i++)
{
registry.TryAdd(key, Slow, out var lease).ShouldBeTrue();
leases.Add(lease!);
}
var beforeAdd = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 64; i++)
{
if (!registry.TryAdd(key, Slow, out var lease)) throw new InvalidOperationException();
leases.Add(lease!);
}
var addBytes = GC.GetAllocatedBytesForCurrentThread() - beforeAdd;
var beforeRemove = GC.GetAllocatedBytesForCurrentThread();
for (var i = 1024; i < 1088; i++) leases[i].Dispose();
var removeBytes = GC.GetAllocatedBytesForCurrentThread() - beforeRemove;
addBytes.ShouldBeLessThan(128 * 1024, "an add must not copy all 1,000 existing interests");
removeBytes.ShouldBeLessThan(128 * 1024, "a remove must not copy all 1,000 existing interests");
foreach (var lease in leases) lease.Dispose();
}
[Fact]
public void Removing_interests_recomputes_each_extreme_only_after_its_last_holder_leaves()
{
var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 4);
var key = Key();
var first = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(100),
DataChangeTrigger.Status, 5);
var second = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(200),
DataChangeTrigger.StatusValueTimestamp, 10);
var third = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(30), TimeSpan.FromMilliseconds(100),
DataChangeTrigger.StatusValueTimestamp, null);
registry.TryAdd(key, first, out var firstLease).ShouldBeTrue();
registry.TryAdd(key, second, out var secondLease).ShouldBeTrue();
registry.TryAdd(key, third, out var thirdLease).ShouldBeTrue();
var combined = registry.GetState(key)!;
combined.Desired.ShouldBe(new DataSubscriptionSettings(TimeSpan.FromMilliseconds(10),
TimeSpan.FromMilliseconds(100), DataChangeTrigger.StatusValueTimestamp, null));
secondLease!.Dispose();
var afterSecond = registry.GetState(key)!;
afterSecond.Desired.ShouldBe(combined.Desired);
afterSecond.DesiredRevision.ShouldBe(combined.DesiredRevision);
firstLease!.Dispose();
var afterFirst = registry.GetState(key)!;
afterFirst.Desired.ShouldBe(third with { Deadband = null });
afterFirst.DesiredRevision.ShouldBeGreaterThan(afterSecond.DesiredRevision);
thirdLease!.Dispose();
registry.GetState(key).ShouldBeNull();
}
[Fact]
public void Removing_the_last_strong_trigger_reduces_the_shared_trigger()
{
var registry = new UpstreamDemandRegistry(maxKeys: 1, maxInterests: 3);
var key = Key();
var low = Slow with { Trigger = DataChangeTrigger.Status };
var high = Slow with { Trigger = DataChangeTrigger.StatusValueTimestamp };
registry.TryAdd(key, low, out var lowLease).ShouldBeTrue();
registry.TryAdd(key, Slow, out var middleLease).ShouldBeTrue();
registry.TryAdd(key, high, out var highLease).ShouldBeTrue();
var strongRevision = registry.GetState(key)!.DesiredRevision;
highLease!.Dispose();
registry.GetState(key)!.Desired.Trigger.ShouldBe(DataChangeTrigger.StatusValue);
registry.GetState(key)!.DesiredRevision.ShouldBeGreaterThan(strongRevision);
middleLease!.Dispose();
registry.GetState(key)!.Desired.Trigger.ShouldBe(DataChangeTrigger.Status);
lowLease!.Dispose();
}
[Fact]
public void A_late_physical_ack_cannot_claim_a_newer_stronger_demand_is_applied()
{
var registry = new UpstreamDemandRegistry(maxKeys: 4, maxInterests: 4);
var key = Key();
registry.TryAdd(key, Slow, out var slow).ShouldBeTrue();
var oldRevision = registry.GetState(key)!.DesiredRevision;
registry.TryAdd(key, Fast, out var fast).ShouldBeTrue();
var current = registry.GetState(key)!;
current.DesiredRevision.ShouldBeGreaterThan(oldRevision);
registry.TryAcknowledge(key, oldRevision, Slow, 1).ShouldBeFalse();
registry.GetState(key)!.AppliedRevision.ShouldNotBe(current.DesiredRevision);
registry.TryAcknowledge(key, current.DesiredRevision, Fast, 2).ShouldBeTrue();
registry.GetState(key)!.AppliedRevision.ShouldBe(current.DesiredRevision);
fast!.Dispose();
slow!.Dispose();
}
private static DemandSharingKey Key() => new(HubTest.Ticket("driver", "tag").Key,
new DataTarget(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary,
"principal", "export", 1, 1);
}
@@ -0,0 +1,99 @@
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", "P06")]
public sealed class GrpcDataFilterAggregationTests
{
[Fact]
public void Shared_upstream_is_a_superset_of_fast_filtered_and_slow_unfiltered_consumers()
{
var fast = new DataSubscriptionSettings(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(200),
DataChangeTrigger.StatusValueTimestamp, 10);
var slow = new DataSubscriptionSettings(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3),
DataChangeTrigger.StatusValue, null);
var aggregate = SubscriptionSettingsAggregator.Aggregate([fast, slow]);
aggregate.SamplingInterval.ShouldBe(fast.SamplingInterval);
aggregate.PublishingInterval.ShouldBe(fast.PublishingInterval);
aggregate.Trigger.ShouldBe(DataChangeTrigger.StatusValueTimestamp);
aggregate.Deadband.ShouldBeNull();
}
[Fact]
public void Committed_baselines_are_independent_and_quality_changes_bypass_deadband()
{
var filtered = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, 10);
var unfiltered = filtered with { Deadband = null };
using var narrow = new ClientFilterState();
using var broad = new ClientFilterState();
using var initial = Sample(1, 100, 0);
using var small = Sample(2, 105, 0);
using var bad = Sample(3, 105, 0x80000000u);
narrow.ShouldDeliver(initial, filtered).ShouldBeTrue();
broad.ShouldDeliver(initial, unfiltered).ShouldBeTrue();
narrow.Commit(initial);
broad.Commit(initial);
narrow.ShouldDeliver(small, filtered).ShouldBeFalse();
broad.ShouldDeliver(small, unfiltered).ShouldBeTrue();
broad.Commit(small);
narrow.ShouldDeliver(bad, filtered).ShouldBeTrue();
broad.ShouldDeliver(bad, unfiltered).ShouldBeTrue();
}
[Fact]
public void Considering_a_candidate_does_not_advance_the_committed_baseline()
{
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, 10);
using var state = new ClientFilterState();
using var initial = Sample(1, 100, 0);
using var candidate = Sample(2, 111, 0);
using var later = Sample(3, 95, 0);
state.Commit(initial);
state.ShouldDeliver(candidate, settings).ShouldBeTrue();
state.ShouldDeliver(later, settings).ShouldBeFalse("the unsent candidate is not a delivered baseline");
state.Commit(candidate);
state.ShouldDeliver(later, settings).ShouldBeTrue();
using var farther = Sample(4, 99, 0);
state.ShouldDeliver(farther, settings).ShouldBeTrue();
}
[Fact]
public void Comparing_large_equal_byte_values_does_not_copy_payloads_per_delivery()
{
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var bytes = Enumerable.Range(0, 1024 * 1024).Select(i => (byte)i).ToArray();
using var first = new DataSample(DataValue.FromBytes(bytes), 0, null, null, HubTest.Serving, 1);
using var second = new DataSample(DataValue.FromBytes(bytes), 0, null, null, HubTest.Serving, 2);
using var state = new ClientFilterState();
state.Commit(first);
state.ShouldDeliver(second, settings).ShouldBeFalse(); // warm JIT before measuring
var before = GC.GetAllocatedBytesForCurrentThread();
var deliver = state.ShouldDeliver(second, settings);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
deliver.ShouldBeFalse();
allocated.ShouldBeLessThan(64 * 1024, "comparing a 1 MiB value should not copy either payload");
}
[Fact]
public void Comparing_large_equal_arrays_does_not_copy_elements_per_delivery()
{
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var elements = Enumerable.Range(0, 100_000).Select(i => (object)i).ToArray();
using var first = new DataSample(DataValue.FromArray(DataValueKind.Int32, elements, [elements.Length]), 0, null, null, HubTest.Serving, 1);
using var second = new DataSample(DataValue.FromArray(DataValueKind.Int32, elements, [elements.Length]), 0, null, null, HubTest.Serving, 2);
using var state = new ClientFilterState();
state.Commit(first);
state.ShouldDeliver(second, settings).ShouldBeFalse();
var before = GC.GetAllocatedBytesForCurrentThread();
var deliver = state.ShouldDeliver(second, settings);
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
deliver.ShouldBeFalse();
allocated.ShouldBeLessThan(64 * 1024, "comparing an array should not allocate a copy of its elements");
}
private static DataSample Sample(long version, int value, uint status) =>
new(DataValue.FromScalar(DataValueKind.Int32, value), status, null, null, HubTest.Serving, version);
}
@@ -107,7 +107,10 @@ internal sealed class LocalDataFixture : IDisposable
internal readonly LocalExportCatalog Catalog;
internal readonly DataAuthenticatedContext Context;
internal LocalDataFixture(int additionalRawNodes = 0)
internal LocalDataFixture(int additionalRawNodes = 0,
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
bool advanceAuthority = false)
{
Hub = HubTest.Create(clock: Clock, bytes: 1_000_000);
Hub.TryBind(Ticket).ShouldBeTrue();
@@ -116,6 +119,14 @@ internal sealed class LocalDataFixture : IDisposable
[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"])] });
if (advanceAuthority)
{
Authority.Apply("cluster", "second", [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"])] });
Serving = Serving with { AuthorityEpoch = Authority.Current.GenerationId };
}
var epoch = Activation.Begin("first");
Activation.AuthorityInstalled(epoch, Authority.Current.GenerationId);
Activation.Complete(epoch, true);
@@ -140,7 +151,8 @@ internal sealed class LocalDataFixture : IDisposable
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);
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, subscriptions: subscriptions,
targetSubscriptions: targetSubscriptions);
}
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", "node-a"));
@@ -0,0 +1,218 @@
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", "P06")]
public sealed class GrpcDataRecoveryAdmissionTests
{
[Fact(Timeout = 30000)]
public async Task Canceling_unopened_stream_releases_its_slot_without_explicit_disposal()
{
var demand = new DeferredSubscriptionDemand();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
using (var cancellation = new CancellationTokenSource())
{
await using var firstConnection = fixture.Connection();
await using var secondConnection = fixture.Connection();
var first = await firstConnection.SubscribeAsync(cancellation.Token);
try
{
var session = first.ShouldBeOfType<DataSubscriptionSession>();
cancellation.Cancel();
await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken);
}
finally { await first.DisposeAsync(); }
}
}
[Fact(Timeout = 30000)]
public async Task Unopened_stream_expires_on_a_bounded_handshake_deadline()
{
var demand = new DeferredSubscriptionDemand();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1),
PreOpenTimeout: TimeSpan.FromSeconds(3));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
await using var firstConnection = fixture.Connection();
await using var secondConnection = fixture.Connection();
var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken);
try
{
var session = first.ShouldBeOfType<DataSubscriptionSession>();
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
await session.Completion.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken);
}
finally { await first.DisposeAsync(); }
}
}
[Fact(Timeout = 30000)]
public async Task Oversized_ack_timeout_is_rejected_without_poisoning_the_command_id()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var invalid = new OpenSubscription("s", 1, "same-command", TimeSpan.MaxValue, [], true,
TimeSpan.FromSeconds(30), LocalDataFixture.Budget);
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => subscription.SendAsync(invalid, TestContext.Current.CancellationToken));
await subscription.SendAsync(invalid with { AcknowledgementTimeout = TimeSpan.FromSeconds(5) }, TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().CommandId.ShouldBe("same-command");
}
}
[Fact]
public void Expired_snapshot_permit_retains_its_quota_while_a_physical_owner_is_alive()
{
var clock = new ManualTimeProvider();
var scheduler = new SnapshotAdmissionScheduler(1, 1, 1_000, maxLifetime: TimeSpan.FromSeconds(2), clock: clock);
scheduler.TryAcquire("peer", 1, out var lease, out _).ShouldBeTrue();
var permit = lease.ShouldBeOfType<SnapshotAdmissionScheduler.Permit>();
permit.TryGrow(500).ShouldBeTrue();
permit.TryRetain(out var physicalOwner).ShouldBeTrue();
clock.Advance(TimeSpan.FromSeconds(2));
permit.IsValid.ShouldBeFalse();
scheduler.TryAcquire("peer", 1, out _, out _).ShouldBeFalse("expired physical ownership remains charged");
physicalOwner!.Dispose();
scheduler.TryAcquire("peer", 1, out var next, out _).ShouldBeTrue();
next!.Dispose(); permit.Dispose();
}
[Fact]
public void Snapshot_permits_grow_before_retention_and_respect_global_and_principal_bytes()
{
var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700);
scheduler.TryAcquire("a", 1, out var first, out _).ShouldBeTrue();
scheduler.TryAcquire("b", 1, out var second, out _).ShouldBeTrue();
var firstPermit = first.ShouldBeOfType<SnapshotAdmissionScheduler.Permit>();
var secondPermit = second.ShouldBeOfType<SnapshotAdmissionScheduler.Permit>();
firstPermit.TryGrow(600).ShouldBeTrue();
firstPermit.TryGrow(100).ShouldBeFalse();
secondPermit.TryGrow(400).ShouldBeFalse();
secondPermit.TryGrow(398).ShouldBeTrue();
firstPermit.Dispose(); secondPermit.Dispose();
scheduler.TryAcquire("a", 700, out var replacement, out _).ShouldBeTrue();
replacement!.Dispose();
}
[Fact(Timeout = 30000)]
public async Task Stream_open_rejects_old_authority_epoch_while_current_epoch_and_same_key_succeed()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(advanceAuthority: true, targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Context.AuthorityEpoch.ShouldBe(2);
var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a");
await using var fresh = fixture.Services.Create(fixture.Context, target);
await using var accepted = await fresh.SubscribeAsync(TestContext.Current.CancellationToken);
var staleContext = fixture.Context with { AuthorityEpoch = 1 };
await using var stale = fixture.Services.Create(staleContext, target);
await Should.ThrowAsync<InvalidOperationException>(() => stale.SubscribeAsync(TestContext.Current.CancellationToken));
}
}
[Fact]
public void Snapshot_admission_bounds_principal_bytes_send_rate_lifetime_and_retry_guidance()
{
var clock = new ManualTimeProvider();
var scheduler = new SnapshotAdmissionScheduler(4, 2, 1_000, maxPrincipalBytes: 700,
globalBytesPerSecond: 100, principalBytesPerSecond: 60,
maxLifetime: TimeSpan.FromSeconds(2), clock: clock);
scheduler.TryAcquire("peer", 600, out var first, out _).ShouldBeTrue();
scheduler.TryAcquire("PEER", 101, out _, out var quotaRetry).ShouldBeFalse();
quotaRetry.ShouldBeGreaterThan(TimeSpan.Zero);
scheduler.TryConsume("peer", 60, out _).ShouldBeTrue();
scheduler.TryConsume("PEER", 1, out var retry).ShouldBeFalse();
retry.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(1));
retry.ShouldBeLessThan(TimeSpan.FromSeconds(2));
scheduler.TryConsume("other", 41, out _).ShouldBeFalse();
clock.Advance(TimeSpan.FromSeconds(1));
scheduler.TryConsume("other", 41, out _).ShouldBeTrue();
clock.Advance(TimeSpan.FromSeconds(1));
first.ShouldBeOfType<SnapshotAdmissionScheduler.Permit>().IsValid.ShouldBeFalse();
scheduler.TryAcquire("PEER", 700, out var afterExpiry, out _).ShouldBeTrue();
first!.Dispose(); afterExpiry!.Dispose();
}
[Fact(Timeout = 30000)]
public async Task Idle_streams_obey_shared_principal_admission_and_disposal_releases_the_slot()
{
var demand = new DeferredSubscriptionDemand();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
await using var firstConnection = fixture.Connection();
await using var secondConnection = fixture.Connection();
var first = await firstConnection.SubscribeAsync(TestContext.Current.CancellationToken);
await Should.ThrowAsync<InvalidOperationException>(() => secondConnection.SubscribeAsync(TestContext.Current.CancellationToken));
await first.DisposeAsync();
await using var replacement = await secondConnection.SubscribeAsync(TestContext.Current.CancellationToken);
}
}
[Fact]
public void Transport_capacity_is_shared_across_sessions_and_principals()
{
var capacity = new SubscriptionTransportCapacity(2, 1, 1_000);
capacity.TryReserve("a", 400, out var first).ShouldBeTrue();
capacity.TryReserve("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive");
capacity.TryReserve("a", 100, out _).ShouldBeFalse();
capacity.TryReserve("b", 700, out _).ShouldBeFalse();
capacity.TryReserve("b", 600, out var second).ShouldBeTrue();
capacity.TryReserve("c", 1, out _).ShouldBeFalse();
first!.Dispose();
first.Dispose();
capacity.TryReserve("c", 400, out var third).ShouldBeTrue();
third!.Dispose();
second!.Dispose();
capacity.ActiveOperations.ShouldBe(0);
}
[Fact]
public void Snapshot_capacity_is_global_and_per_principal_and_disposal_releases_it_once()
{
var scheduler = new SnapshotAdmissionScheduler(maxConcurrent: 2, maxPerPrincipal: 1, maxBytes: 1000);
scheduler.TryAcquire("a", 400, out var first).ShouldBeTrue();
scheduler.TryAcquire("A", 100, out _).ShouldBeFalse("principal quota is case-insensitive");
scheduler.TryAcquire("a", 100, out _).ShouldBeFalse();
scheduler.TryAcquire("b", 700, out _).ShouldBeFalse();
scheduler.TryAcquire("b", 600, out var second).ShouldBeTrue();
scheduler.TryAcquire("c", 1, out _).ShouldBeFalse();
first!.Dispose();
first.Dispose();
scheduler.TryAcquire("c", 400, out var replacement).ShouldBeTrue();
replacement!.Dispose();
second!.Dispose();
scheduler.TryAcquire("a", 1000, out var last).ShouldBeTrue();
last!.Dispose();
}
}
@@ -11,6 +11,446 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Phase", "P04")]
public sealed class GrpcDataSnapshotTests
{
[Fact]
public async Task Nonblocking_ticket_validation_rejects_old_partition_during_repartition()
{
using var hub = HubTest.Create(partitions: 1);
var ticket = HubTest.Ticket("driver", "routing-gap");
hub.TryBind(ticket).ShouldBeTrue();
var epoch = hub.RoutingEpoch;
var cancellationToken = TestContext.Current.CancellationToken;
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
var holder = Task.Run(() => hub.WithPartitionLockForTest(ticket.Key, () =>
{
entered.Set();
release.Wait(cancellationToken);
}), cancellationToken);
Task? repartition = null;
try
{
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
repartition = Task.Run(() => hub.Repartition(2), cancellationToken);
SpinWait.SpinUntil(() =>
{
cancellationToken.ThrowIfCancellationRequested();
return hub.RoutingEpoch != epoch;
}, TimeSpan.FromSeconds(5)).ShouldBeTrue();
var isCurrent = await Task.Run(() => hub.IsTicketCurrentNonBlocking(ticket), cancellationToken)
.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
isCurrent.ShouldBeFalse();
}
finally
{
release.Set();
await holder.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
if (repartition is not null) await repartition.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Steady_interest_detects_quiet_source_invalidation_after_snapshot_disposal(bool retireProducer)
{
using var hub = HubTest.Create(partitions: 1);
var ticket = HubTest.Ticket("driver", "quiet-control");
var producer = new ProducerFence(1);
hub.TryBind(ticket, producer).ShouldBeTrue();
HubTest.Publish(hub, ticket, 1, 1);
hub.ProcessPending();
hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None,
out var snapshot, out var interest).ShouldBeTrue();
using (interest!)
{
snapshot!.Dispose();
if (retireProducer) producer.Retire();
else hub.Invalidate(ticket, "source invalidated");
(interest!.IsReset || !interest.TryReadChanges(1, out _)).ShouldBeTrue();
}
}
[Fact]
public void Status_changes_remain_observable_through_steady_interest_history()
{
using var hub = HubTest.Create(partitions: 1);
var ticket = HubTest.Ticket("driver", "status-history");
HubTest.BindAndPublish(hub, ticket, 1, 1);
hub.ProcessPending();
hub.TryCaptureInterestSnapshot([ticket], HubTest.Budget, CancellationToken.None,
out var snapshot, out var interest).ShouldBeTrue();
using (interest!)
{
snapshot!.Dispose();
hub.TryPublishStatus(ticket, 2, 0x80000000, null, null).ShouldBeTrue();
hub.ProcessPending();
interest!.IsReset.ShouldBeFalse();
interest.TryReadChanges(1, out var changes).ShouldBeTrue();
changes.ShouldHaveSingleItem().Ticket.ShouldBe(ticket);
}
}
[Fact]
public void Source_control_and_status_reset_the_snapshot_but_ordinary_values_do_not()
{
using var hub = HubTest.Create(partitions: 1);
var source = HubTest.Ticket("driver", "control");
HubTest.BindAndPublish(hub, source, 1, 1);
hub.ProcessPending();
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var frozen).ShouldBeTrue();
using (frozen!)
{
HubTest.Publish(hub, source, 2, 2);
hub.ProcessPending();
frozen!.IsReset.ShouldBeFalse();
frozen.IsItemCurrent(source).ShouldBeTrue();
frozen.Items[source].Sample!.Value.GetScalar().ShouldBe(1);
hub.TryPublishStatus(source, 3, 0x80000000, null, null).ShouldBeTrue();
frozen.IsReset.ShouldBeTrue();
}
}
[Fact]
public void Active_partition_control_cannot_be_accepted_by_snapshot_validation()
{
using var hub = HubTest.Create(partitions: 1);
var source = HubTest.Ticket("driver", "active-control");
HubTest.BindAndPublish(hub, source, 1, 1);
hub.ProcessPending();
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
{
var signal = hub.ControlSignalForTests(source.Key);
signal.Begin();
try { snapshot!.IsReset.ShouldBeTrue(); }
finally { signal.End(); }
}
}
[Fact]
public void Control_counter_overflow_permanently_rejects_snapshots()
{
var signal = new PartitionControlSignal();
typeof(PartitionControlSignal).GetField("_generation", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(signal, long.MaxValue);
signal.Begin();
signal.TryCapture(out _).ShouldBeFalse();
signal.End();
signal.TryCapture(out _).ShouldBeFalse();
}
[Fact]
public void Routing_epoch_exhaustion_rejects_repartition_before_mutation()
{
using var hub = HubTest.Create(partitions: 1);
typeof(PartitionedSampleHub).GetField("_routingEpoch", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(hub, long.MaxValue);
Should.Throw<InvalidOperationException>(() => hub.Repartition(2));
hub.RoutingEpoch.ShouldBe(long.MaxValue);
hub.GetPartition(HubTest.Ticket("driver", "epoch-limit").Key).ShouldBe(0);
}
[Fact]
public async Task Retirement_help_covers_all_partitions_when_first_caller_pauses_mid_vector()
{
using var hub = HubTest.Create(partitions: 2);
var firstSource = HubTest.Ticket("driver", "first-signal");
var secondSource = Enumerable.Range(0, 1000).Select(i => HubTest.Ticket("driver", "second-signal-" + i))
.First(t => hub.GetPartition(t.Key) != hub.GetPartition(firstSource.Key));
var producer = new ProducerFence(1);
foreach (var source in new[] { firstSource, secondSource })
{
hub.TryBind(source, producer).ShouldBeTrue();
HubTest.Publish(hub, source, 1, 1);
}
hub.ProcessPending();
hub.TryCaptureSnapshot([firstSource, secondSource], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
using (var entered = new ManualResetEventSlim())
using (var release = new ManualResetEventSlim())
{
var cancellationToken = TestContext.Current.CancellationToken;
var calls = 0;
producer.AfterSignalBegunForTests = () =>
{
if (Interlocked.Increment(ref calls) == 1) { entered.Set(); release.Wait(); }
};
var first = Task.Run(producer.Retire, cancellationToken);
try
{
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
snapshot!.IsReset.ShouldBeTrue();
await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
producer.IsRetired.ShouldBeTrue();
}
finally { release.Set(); await first.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); }
}
}
[Fact]
public async Task Concurrent_retire_helps_complete_while_first_caller_is_paused()
{
using var hub = HubTest.Create(partitions: 1);
var source = HubTest.Ticket("driver", "retire-help");
var producer = new ProducerFence(1);
hub.TryBind(source, producer).ShouldBeTrue();
HubTest.Publish(hub, source, 1, 1);
hub.ProcessPending();
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
using (var entered = new ManualResetEventSlim())
using (var release = new ManualResetEventSlim())
{
var cancellationToken = TestContext.Current.CancellationToken;
var calls = 0;
producer.BeforeRetirementPublicationForTests = () =>
{
if (Interlocked.Increment(ref calls) == 1) { entered.Set(); release.Wait(); }
};
var first = Task.Run(producer.Retire, cancellationToken);
try
{
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
producer.IsRetired.ShouldBeTrue();
snapshot!.IsReset.ShouldBeTrue();
hub.TryBind(HubTest.Ticket("driver", "late"), producer).ShouldBeFalse();
}
finally { release.Set(); await first.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); }
}
}
[Fact]
public void Producer_is_owned_by_one_hub_and_routing_replaces_old_signal_vectors()
{
using var first = HubTest.Create(partitions: 2);
using var second = HubTest.Create(partitions: 2);
var producer = new ProducerFence(1);
first.TryBind(HubTest.Ticket("driver", "first"), producer).ShouldBeTrue();
second.TryBind(HubTest.Ticket("driver", "second"), producer).ShouldBeFalse();
for (var i = 0; i < 10; i++)
{
first.Repartition(2);
first.TryBind(HubTest.Ticket("driver", "epoch-" + i), producer).ShouldBeTrue();
producer.AttachedSignalCountForTests.ShouldBeLessThanOrEqualTo(2);
}
}
[Fact]
public async Task Producer_retirement_never_waits_for_a_partition_lock()
{
using var hub = HubTest.Create(partitions: 1);
var source = HubTest.Ticket("driver", "locked-partition");
var producer = new ProducerFence(1);
hub.TryBind(source, producer).ShouldBeTrue();
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
var cancellationToken = TestContext.Current.CancellationToken;
var holder = Task.Run(() => hub.WithPartitionLockForTest(source.Key, () => { entered.Set(); release.Wait(); }), cancellationToken);
try
{
entered.Wait(TimeSpan.FromSeconds(5), cancellationToken).ShouldBeTrue();
await Task.Run(producer.Retire, cancellationToken).WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
producer.IsRetired.ShouldBeTrue();
}
finally { release.Set(); await holder.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken); }
}
[Fact]
public void Producer_rejects_stale_epoch_attachment_after_repartition()
{
using var hub = HubTest.Create(partitions: 1);
var producer = new ProducerFence(1);
hub.TryBind(HubTest.Ticket("driver", "before"), producer).ShouldBeTrue();
var oldEpoch = hub.RoutingEpoch;
hub.Repartition(1);
hub.TryBind(HubTest.Ticket("driver", "after"), producer).ShouldBeTrue();
producer.TryAttach(hub, oldEpoch, new PartitionControlSignal()).ShouldBeFalse();
}
[Fact]
public void Missing_ticket_cannot_be_accepted_as_a_captured_source()
{
using var hub = HubTest.Create(partitions: 1);
var missing = HubTest.Ticket("driver", "missing");
hub.TryCaptureSnapshot([missing], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeFalse();
snapshot.ShouldBeNull();
}
[Fact]
public void Delta_positions_advance_the_partition_history_minimum()
{
using var hub = HubTest.Create(partitions: 1);
var source = HubTest.Ticket("driver", "cursor");
HubTest.BindAndPublish(hub, source, 1, 1);
hub.ProcessPending();
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
for (var version = 2; version <= 5; version++)
{
HubTest.Publish(hub, source, version, version);
hub.ProcessPending();
snapshot!.TryReadDelta(source, out var delta).ShouldBeTrue();
delta!.Dispose();
snapshot.IsReset.ShouldBeFalse();
}
}
[Fact]
public void Repeated_snapshot_validity_checks_do_not_rebuild_groups_for_every_captured_item()
{
var limits = new DataResourceLimits
{
PartitionCount = 4, MaxRetainedBytes = 16_000_000, MaxTrackedSources = 512,
MaxIngressItemsPerPartition = 512, MaxDirtySourcesPerPartition = 512,
MaxControlItemsPerPartition = 32, MaxSnapshotItems = 512, MaxSnapshotBytes = 8_000_000,
MaxSnapshotCatchUpItems = 512, MaxSnapshotLifetime = TimeSpan.FromMinutes(1)
};
using var hub = new PartitionedSampleHub(limits, new ManualTimeProvider(), autoDrain: false);
var tickets = Enumerable.Range(0, 256).Select(i => HubTest.Ticket("driver", "snapshot-" + i)).ToArray();
foreach (var ticket in tickets) HubTest.BindAndPublish(hub, ticket, 1, 1);
hub.ProcessPending();
hub.TryCaptureSnapshot(tickets, new DataBudget(TimeSpan.FromSeconds(30), 512, 8_000_000),
CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
{
snapshot!.IsReset.ShouldBeFalse(); // warm JIT outside measured work
var before = GC.GetAllocatedBytesForCurrentThread();
var workBefore = hub.SnapshotValidationWorkForTests;
for (var i = 0; i < 128; i++) if (snapshot.IsReset) throw new InvalidOperationException();
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
allocated.ShouldBeLessThan(64 * 1024, "each check must not regroup all 256 source entries");
(hub.SnapshotValidationWorkForTests - workBefore).ShouldBeLessThan(128 * 16,
"a validity check must not walk every source in the snapshot");
}
}
[Fact]
public void Delayed_reserved_ingress_commit_keeps_original_normalized_receipt_time()
{
var clock = new ManualTimeProvider();
using var hub = HubTest.Create(clock: clock);
var source = HubTest.Ticket("driver", "staged");
hub.TryBind(source).ShouldBeTrue();
var received = clock.GetTimestamp();
hub.TryReserveIngress(source, 288, out var reservation).ShouldBeTrue();
using (reservation!)
{
clock.Advance(TimeSpan.FromSeconds(5));
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 8), 0, null, null, HubTest.Serving, 1);
if (!reservation!.TryCommit(sample, 1)) { sample.Dispose(); throw new InvalidOperationException(); }
}
hub.ProcessPending();
using var read = hub.Read(source);
read.ReceivedTimestamp.ShouldBe(received);
clock.GetElapsedTime(read.ReceivedTimestamp).ShouldBe(TimeSpan.FromSeconds(5));
}
[Fact]
public void Steady_interest_survives_snapshot_disposal_and_observes_later_dirty_generation()
{
using var hub = HubTest.Create();
var source = HubTest.Ticket("driver", "interest");
HubTest.BindAndPublish(hub, source, 1, 10);
hub.ProcessPending();
hub.TryCaptureInterestSnapshot([source], HubTest.Budget, CancellationToken.None,
out var snapshot, out var interest).ShouldBeTrue();
using (interest!)
{
snapshot!.Items[source].Sample!.Value.GetScalar().ShouldBe(10);
snapshot.Dispose();
HubTest.Publish(hub, source, 2, 20);
hub.ProcessPending();
interest!.TryReadChanges(1, out var changes).ShouldBeTrue();
changes.ShouldHaveSingleItem().Ticket.ShouldBe(source);
using var latest = hub.Read(source);
latest.Sample!.Value.GetScalar().ShouldBe(20);
}
}
[Fact]
public void Atomic_interest_registration_cannot_lose_a_racing_source_update()
{
using var hub = HubTest.Create();
var source = HubTest.Ticket("driver", "interest-race");
HubTest.BindAndPublish(hub, source, 1, 10);
hub.ProcessPending();
SnapshotLease? snapshot = null;
SourceInterestLease? interest = null;
var accepted = false;
var captured = false;
Parallel.Invoke(
() => captured = hub.TryCaptureInterestSnapshot([source], HubTest.Budget, CancellationToken.None,
out snapshot, out interest),
() =>
{
if (!hub.TryReserveIngress(source, 288, out var reservation)) return;
using (reservation!)
{
var sample = new DataSample(DataValue.FromScalar(DataValueKind.Int32, 20), 0, null, null, HubTest.Serving, 2);
accepted = reservation!.TryCommit(sample, 2);
if (!accepted) sample.Dispose();
}
hub.ProcessPending();
});
if (!captured) return; // bounded contention is an explicit retry boundary
using (snapshot!)
using (interest!)
{
if (!accepted) { snapshot!.IsReset.ShouldBeTrue(); return; }
var value = (int)snapshot!.Items[source].Sample!.Value.GetScalar();
if (value == 10)
{
interest!.TryReadChanges(1, out var changes).ShouldBeTrue();
changes.ShouldContain(x => x.Ticket == source);
}
else value.ShouldBe(20);
}
}
[Fact]
public void Snapshot_retains_original_monotonic_acquisition_time_after_status_and_reconnect()
{
var clock = new ManualTimeProvider();
using var hub = HubTest.Create(clock: clock);
var source = HubTest.Ticket("driver", "age");
var acquired = clock.GetTimestamp();
HubTest.BindAndPublish(hub, source, 1, 42);
hub.ProcessPending();
clock.Advance(TimeSpan.FromSeconds(3));
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var first).ShouldBeTrue();
using (first!)
{
first!.Items[source].ReceivedTimestamp.ShouldBe(acquired);
first.Items[source].Sample!.SourceTimestampUtc.ShouldBeNull();
first.Items[source].Sample!.ServerTimestampUtc.ShouldBeNull();
}
hub.TryPublishStatus(source, 2, 0x80000000, null, null).ShouldBeTrue();
hub.ProcessPending();
clock.Advance(TimeSpan.FromSeconds(4));
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var reconnected).ShouldBeTrue();
using (reconnected!)
{
reconnected!.Items[source].ReceivedTimestamp.ShouldBe(acquired);
clock.GetElapsedTime(reconnected.Items[source].ReceivedTimestamp!.Value).ShouldBe(TimeSpan.FromSeconds(7));
reconnected.Items[source].Sample!.StatusCode.ShouldBe(0x80000000u);
}
}
[Fact]
public void Snapshot_with_no_sample_has_no_acquisition_timestamp()
{
using var hub = HubTest.Create();
var source = HubTest.Ticket("driver", "waiting");
hub.TryBind(source).ShouldBeTrue();
hub.TryCaptureSnapshot([source], HubTest.Budget, CancellationToken.None, out var snapshot).ShouldBeTrue();
using (snapshot!)
{
snapshot!.Items[source].Sample.ShouldBeNull();
snapshot.Items[source].ReceivedTimestamp.ShouldBeNull();
}
}
[Fact]
public void Snapshot_freezes_samples_and_its_watermarks_cover_every_participating_partition()
{
@@ -0,0 +1,995 @@
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", "P06")]
public sealed class GrpcDataStreamOrderingTests
{
[Fact(Timeout = 30000)]
public async Task Coalescing_notice_is_delivered_when_the_latest_value_returns_to_the_baseline()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 8, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 2); fixture.Hub.ProcessPending();
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(10), []),
TestContext.Current.CancellationToken);
sink.ReleaseFirst();
await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(5));
await sink.Heartbeat.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var events = sink.Events.ToArray();
events.ShouldContain("coalesced", "a suppressed replacement must not hide the loss indication");
events.ShouldNotContain("value-3");
events.ShouldNotContain("value-4");
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Direct_modify_ack_is_not_published_when_authority_is_revoked_during_commit_cleanup()
{
using var demand = new BlockingFirstLeaseDemand();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings with { SamplingInterval = TimeSpan.FromMilliseconds(100) })]), TestContext.Current.CancellationToken);
var next = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken);
try
{
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-during-modify-cleanup");
}
finally { demand.Release(); }
(await next.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeFalse();
}
}
[Fact(Timeout = 30000)]
public async Task A_queued_candidate_rechecks_due_time_after_the_previous_blocked_write_commits()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "probe", TimeSpan.FromSeconds(5),
[new("probe", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
sink.ReleaseFirst();
await sink.ProbeAck.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.Version3Written.Task.IsCompleted.ShouldBeFalse("the preceding write advanced the next due time");
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
await sink.Version3Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Superseded_queued_value_emits_coalescing_control_before_the_newest_delta()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 4, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var queued = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.OnCandidateQueuedForTests = (_, version) => { if (version == 3) queued.TrySetResult(true); };
var sink = new SequencedLiveSink();
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>().RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.FirstLiveEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 3, 3); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await queued.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 4, 4); fixture.Hub.ProcessPending();
sink.ReleaseFirst();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
await sink.Version4Written.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var events = sink.Events.ToArray();
Array.IndexOf(events, "coalesced").ShouldBeGreaterThanOrEqualTo(0);
Array.IndexOf(events, "coalesced").ShouldBeLessThan(Array.IndexOf(events, "value-4"));
events.ShouldNotContain("value-3");
await subscription.DisposeAsync();
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
}
}
[Fact(Timeout = 30000)]
public async Task Revocation_during_post_prepare_snapshot_validation_prevents_transport_handoff()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: true);
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
try
{
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-after-check");
}
finally { sink.Release(); }
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.BlockedValueWrites.ShouldBe(0);
}
}
[Fact(Timeout = 30000)]
public async Task Revocation_during_post_prepare_live_eligibility_prevents_transport_handoff()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var sink = new PostPrepareGateSink(fixture.Hub, blockSnapshot: false);
var writer = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>()
.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2); fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
try
{
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Activation.Begin("revoke-after-eligibility-start");
}
finally { sink.Release(); }
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
sink.BlockedValueWrites.ShouldBe(0);
}
}
[Fact(Timeout = 30000)]
public async Task Direct_handoff_does_not_certify_stale_age_after_a_blocking_final_check()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
using (var release = new ManualResetEventSlim())
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var session = subscription.ShouldBeOfType<DataSubscriptionSession>();
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue(); // ack
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
var entered = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
session.BeforeDirectCommitForTests = () =>
{
session.BeforeDirectCommitForTests = null; entered.TrySetResult(true);
if (!release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
};
var move = Task.Run(async () => await reader.MoveNextAsync(), TestContext.Current.CancellationToken);
try
{
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
}
finally { release.Set(); }
(await move.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
var bounds = values.Items.ShouldHaveSingleItem().AgeBounds;
bounds.IsFresh(TimeSpan.FromSeconds(1)).ShouldBeFalse();
if (bounds.Upper is { } upper) upper.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2));
}
}
[Fact(Timeout = 30000)]
public async Task Local_facades_preserve_node_and_cluster_target_identity_in_demand_admission()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
fixture.Publish(3);
var nodeTarget = new DataTarget(DataTargetMode.Node, "cluster", "node-a");
var clusterTarget = new DataTarget(DataTargetMode.Cluster, "cluster", null);
await using var node = fixture.Services.Create(fixture.Context, nodeTarget);
await using var cluster = fixture.Services.Create(fixture.Context, clusterTarget);
await using var nodeSubscription = await node.SubscribeAsync(TestContext.Current.CancellationToken);
await using var clusterSubscription = await cluster.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await nodeSubscription.SendAsync(new OpenSubscription("node", 1, "open-node", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await clusterSubscription.SendAsync(new OpenSubscription("cluster", 1, "open-cluster", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var nodeReader = nodeSubscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
await using var clusterReader = clusterSubscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await nodeReader.MoveNextAsync()).ShouldBeTrue();
(await clusterReader.MoveNextAsync()).ShouldBeTrue();
demand.AuthorizedViews.Select(x => x.Target).ShouldContain(nodeTarget);
demand.AuthorizedViews.Select(x => x.Target).ShouldContain(clusterTarget);
demand.AuthorizedViews.Select(x => x.Target.Mode).Distinct().Count().ShouldBe(2);
var views = demand.AuthorizedViews.ToArray();
views[0].Source.ShouldBe(views[1].Source);
var registry = new UpstreamDemandRegistry(2, 2);
var firstKey = new DemandSharingKey(views[0].Source, views[0].Target, views[0].Consistency,
views[0].PrincipalId, views[0].ExportScope, views[0].Serving.CatalogEpoch, views[0].Serving.AuthorityEpoch);
var secondKey = firstKey with { Target = views[1].Target };
registry.TryAdd(firstKey, settings, out var firstLease).ShouldBeTrue();
registry.TryAdd(secondKey, settings, out var secondLease).ShouldBeTrue();
registry.GetState(firstKey)!.InterestCount.ShouldBe(1);
registry.GetState(secondKey)!.InterestCount.ShouldBe(1);
firstLease!.Dispose(); secondLease!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task Local_connection_waits_for_physical_ack_before_acknowledging_and_sending_snapshot()
{
var demand = new DeferredSubscriptionDemand();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var item = new DataSubscriptionItem("one", fixture.Raw,
new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null));
var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [item], false,
TimeSpan.FromSeconds(30), LocalDataFixture.Budget);
var send = subscription.SendAsync(open, TestContext.Current.CancellationToken);
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
var first = reader.MoveNextAsync().AsTask();
first.IsCompleted.ShouldBeFalse("an unacknowledged physical subscription is not ready");
demand.Accept();
await send;
(await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items.ShouldHaveSingleItem().Status.ShouldBe(DataItemStatus.Good);
ack.Items[0].Handle.ShouldNotBeNull();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using (var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
{
values.IsSnapshot.ShouldBeTrue();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42);
values.Items[0].Readiness.ShouldBe(DataReadiness.Ready);
}
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
}
}
[Fact(Timeout = 30000)]
public async Task Accepted_command_owns_its_item_list_before_the_caller_can_mutate_it()
{
var demand = new DeferredSubscriptionDemand();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("first", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await demand.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var mutable = new List<DataSubscriptionItem> { new("second", fixture.Raw, settings) };
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), mutable),
TestContext.Current.CancellationToken);
mutable.Clear();
demand.Accept();
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
while (true)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues values) values.Dispose();
if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack)
{
ack.Items.ShouldHaveSingleItem().ClientItemId.ShouldBe("second");
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
break;
}
}
}
}
[Fact(Timeout = 30000)]
public async Task A_denied_alias_cannot_inherit_authority_from_a_shared_backing_source()
{
var demand = new DeferredSubscriptionDemand();
demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("allowed", fixture.Raw, settings), new("denied", fixture.Uns, settings)], false,
TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
ack.Items[1].Status.ShouldBe(DataItemStatus.Denied);
ack.Items[1].Handle.ShouldBeNull();
demand.AuthorizedViews.ShouldHaveSingleItem().View.ShouldBe(fixture.Raw);
}
}
[Fact(Timeout = 30000)]
public async Task A_bound_source_without_a_sample_is_waiting_until_a_real_acquisition_arrives()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.Items[0].Status.ShouldBe(DataItemStatus.WaitingForInitialData);
ack.Items[0].Handle.ShouldNotBeNull();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
fixture.Publish(9);
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(9);
values.Items[0].Readiness.ShouldBe(DataReadiness.Ready);
}
}
[Fact(Timeout = 30000)]
public async Task Snapshot_larger_than_queue_finishes_frozen_values_before_a_racing_delta()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 4, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(additionalRawNodes: 4, subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
var items = Enumerable.Range(0, 5).Select(i =>
{
var view = i == 0 ? fixture.Raw : fixture.Raw with
{
Address = fixture.Raw.Address with { Identifier = fixture.Raw.Address.Identifier + (i - 1) },
Subject = fixture.Raw.Subject + (i - 1)
};
return new DataSubscriptionItem("item-" + i, view, settings);
}).ToArray();
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10), items,
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items.Count.ShouldBe(5);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using (var first = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
first.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1);
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
fixture.Hub.ProcessPending();
var frozen = 1;
while (true)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) break;
using var values = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
values.IsSnapshot.ShouldBeTrue();
values.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1);
values.Items[0].AgeBounds.Lower.ShouldNotBeNull();
values.Items[0].AgeBounds.Lower!.Value.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2));
frozen++;
}
frozen.ShouldBe(5);
fixture.Clock.Advance(TimeSpan.FromMilliseconds(200));
var delivered = new HashSet<ulong>();
while (delivered.Count < 5)
{
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
if (reader.Current is DataSubscriptionControl control)
{
control.Kind.ShouldBe(DataStreamControlKind.Heartbeat, $"Unexpected {control.Kind}: {control.Diagnostic}");
continue;
}
using var delta = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
delta.IsSnapshot.ShouldBeFalse();
delta.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(2);
delivered.Add(delta.Items[0].Handle.Handle);
}
}
}
[Fact(Timeout = 30000)]
public async Task Direct_frame_retains_its_resource_charge_after_session_disposal()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(7);
var baseline = fixture.Hub.Resources.RetainedBytes;
await using var connection = fixture.Connection();
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue(); // ack
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
(await reader.MoveNextAsync()).ShouldBeTrue();
var frame = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
await subscription.DisposeAsync();
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse("escaped snapshot frame still owns its snapshot permit");
frame.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(7);
frame.Dispose();
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue();
next!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task Expired_original_key_fences_a_value_blocked_in_transport_preparation()
{
var demand = new DeferredSubscriptionDemand();
demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
var baselineBytes = fixture.Hub.Resources.RetainedBytes;
var shortKey = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(2) };
await using var connection = fixture.Services.Create(shortKey, new(DataTargetMode.Node, "cluster", "node-a"));
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var transport = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>();
var sink = new BlockingValuePreparationSink();
var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
capacity.ActiveOperations.ShouldBe(1, "a sink ignoring cancellation still owns its physical slot");
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baselineBytes);
capacity.Snapshots.TryAcquire("peer", 1, out _).ShouldBeFalse();
sink.Release();
await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
catch (OperationCanceledException) { }
sink.ValueWrites.ShouldBe(0, "the final key/authority gate follows preparation");
capacity.ActiveOperations.ShouldBe(0);
fixture.Hub.Resources.RetainedBytes.ShouldBe(baselineBytes);
capacity.Snapshots.TryAcquire("peer", 1, out var next).ShouldBeTrue();
next!.Dispose();
}
}
[Fact(Timeout = 30000)]
public async Task A_write_ignoring_cancellation_retains_frame_and_capacity_until_its_actual_completion()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(1, 1, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(42);
var baseline = fixture.Hub.Resources.RetainedBytes;
await using var connection = fixture.Connection();
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var transport = subscription.ShouldBeAssignableTo<IDataSubscriptionTransport>();
var sink = new BlockingValueWriteSink();
var writer = transport.RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(2), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
fixture.Clock.Advance(TimeSpan.FromSeconds(3));
await subscription.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
capacity.ActiveOperations.ShouldBe(1);
fixture.Hub.Resources.RetainedBytes.ShouldBeGreaterThan(baseline);
sink.Value!.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(42);
sink.Release();
await sink.ValueDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
try { await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
catch (OperationCanceledException) { }
capacity.ActiveOperations.ShouldBe(0);
fixture.Hub.Resources.RetainedBytes.ShouldBe(baseline);
}
}
[Fact(Timeout = 30000)]
public async Task Remove_ack_is_a_barrier_before_readding_the_same_client_item()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(1);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1),
DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var old = reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items[0].Handle!;
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotEnd);
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
fixture.Hub.ProcessPending();
fixture.Clock.Advance(TimeSpan.FromSeconds(1));
var remove = subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [old]),
TestContext.Current.CancellationToken);
while (true)
{
(await reader.MoveNextAsync()).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues earlier) earlier.Dispose();
if (reader.Current is DataSubscriptionAck { CommandId: "remove" }) break;
}
await remove;
var add = subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)]), TestContext.Current.CancellationToken);
DataItemHandle? replacement = null;
while (replacement is null)
{
(await reader.MoveNextAsync()).ShouldBeTrue();
if (reader.Current is DataSubscriptionValues values)
{
values.Items.ShouldNotContain(x => x.Handle == old);
values.Dispose();
}
if (reader.Current is DataSubscriptionAck { CommandId: "add" } ack)
{
ack.Items[0].Status.ShouldBe(DataItemStatus.Good);
ack.Items[0].Handle.ShouldNotBeNull();
replacement = ack.Items[0].Handle;
}
}
await add;
replacement.Handle.ShouldNotBe(old.Handle);
}
}
[Fact(Timeout = 30000)]
public async Task Changing_the_filter_acknowledges_a_new_revision_before_its_snapshot()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(subscriptions: context =>
new LocalSubscriptionService(fixture!.Services, context,
new(DataTargetMode.Node, "cluster", "node-a"), demand, limits, capacity)))
{
fixture.Publish(10);
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
var settings = new DataSubscriptionSettings(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, settings)], false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget),
TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
var original = reader.Current.ShouldBeOfType<DataSubscriptionAck>().Items[0].Handle!;
(await reader.MoveNextAsync()).ShouldBeTrue(); // begin
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionValues>().Dispose();
(await reader.MoveNextAsync()).ShouldBeTrue(); // end
var modified = settings with { Deadband = 5 };
await subscription.SendAsync(new ModifySubscriptionItems("s", 1, "modify", TimeSpan.FromSeconds(5),
[new("one", fixture.Raw, modified)]), TestContext.Current.CancellationToken);
(await reader.MoveNextAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue();
var ack = reader.Current.ShouldBeOfType<DataSubscriptionAck>();
ack.CommandId.ShouldBe("modify");
var replacement = ack.Items.ShouldHaveSingleItem().Handle;
replacement.ShouldNotBeNull();
replacement.ShouldNotBe(original);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionControl>().Kind.ShouldBe(DataStreamControlKind.SnapshotBegin);
(await reader.MoveNextAsync()).ShouldBeTrue();
using var snapshot = reader.Current.ShouldBeOfType<DataSubscriptionValues>();
snapshot.Items.ShouldHaveSingleItem().Handle.ShouldBe(replacement);
snapshot.Items[0].Sample.Value.GetScalar().ShouldBe(10);
}
}
[Fact(Timeout = 30000)]
public async Task Quiet_control_only_session_expires_without_renewal_or_further_commands()
{
var demand = new DeferredSubscriptionDemand(); demand.Accept();
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
LocalDataFixture? fixture = null;
using (fixture = new LocalDataFixture(targetSubscriptions: (context, target) =>
new LocalSubscriptionService(fixture!.Services, context, target, demand, limits, capacity)))
{
await using var connection = fixture.Connection();
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("watch", 1, "open", TimeSpan.FromSeconds(5), [], true,
TimeSpan.FromSeconds(2), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken)
.GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await reader.MoveNextAsync()).ShouldBeTrue();
reader.Current.ShouldBeOfType<DataSubscriptionAck>().CommandId.ShouldBe("open");
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
await Should.ThrowAsync<InvalidOperationException>(() => subscription.SendAsync(
new AddSubscriptionItems("watch", 1, "late", TimeSpan.FromSeconds(1), []), TestContext.Current.CancellationToken));
(await reader.MoveNextAsync()).ShouldBeFalse();
}
}
[Fact]
public void Removed_handle_never_becomes_current_after_readd()
{
var handles = new SubscriptionItemHandleTable("stream", 1, 4);
var first = handles.Add("item");
handles.IsCurrent(first).ShouldBeTrue();
handles.Remove(first).ShouldBeTrue();
var second = handles.Add("item");
second.Handle.ShouldNotBe(first.Handle);
handles.IsCurrent(first).ShouldBeFalse();
handles.IsCurrent(second).ShouldBeTrue();
}
[Fact]
public void Revision_and_epoch_are_checked_even_if_the_numeric_handle_matches()
{
var handles = new SubscriptionItemHandleTable("stream", 7, 4);
var current = handles.Add("item");
handles.IsCurrent(current with { ItemRevision = current.ItemRevision + 1 }).ShouldBeFalse();
handles.IsCurrent(current with { StreamEpoch = current.StreamEpoch + 1 }).ShouldBeFalse();
handles.IsCurrent(current with { SubscriptionId = "other" }).ShouldBeFalse();
handles.IsCurrent(current).ShouldBeTrue();
}
}
internal sealed class DeferredSubscriptionDemand : ISubscriptionDemandSource
{
private readonly TaskCompletionSource<bool> _accepted = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly List<SubscriptionAuthorizedView> AuthorizedViews = [];
public async ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
lock (AuthorizedViews) AuthorizedViews.Add(view);
Entered.TrySetResult(true);
await _accepted.Task.WaitAsync(cancellationToken);
return new(DataItemStatus.Good, settings, 1, new NoopLease());
}
internal void Accept() => _accepted.TrySetResult(true);
private sealed class NoopLease : IDisposable { public void Dispose() { } }
}
internal sealed class BlockingFirstLeaseDemand : ISubscriptionDemandSource, IDisposable
{
private readonly ManualResetEventSlim _release = new();
private int _calls;
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public ValueTask<SubscriptionDemandResult> AcquireAsync(SubscriptionAuthorizedView view,
DataSubscriptionSettings settings, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return ValueTask.FromResult(new SubscriptionDemandResult(DataItemStatus.Good, settings, 1,
new Lease(this, Interlocked.Increment(ref _calls) == 1)));
}
internal void Release() => _release.Set();
public void Dispose() { _release.Set(); _release.Dispose(); }
private sealed class Lease(BlockingFirstLeaseDemand owner, bool blocks) : IDisposable
{
public void Dispose()
{
if (!blocks) return;
owner.Entered.TrySetResult(true);
if (!owner._release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
}
}
}
internal sealed class BlockingValuePreparationSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int ValueWrites;
public async ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame,
long reservedBytes, CancellationToken cancellationToken)
{
if (frame is DataSubscriptionValues)
{
Entered.TrySetResult(true);
await _release.Task; // intentionally ignores cancellation
}
return new Prepared(frame is DataSubscriptionValues, ValueDisposed);
}
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
if (((Prepared)prepared).Value) Interlocked.Increment(ref ValueWrites);
return ValueTask.CompletedTask;
}
internal void Release() => _release.TrySetResult(true);
private sealed class Prepared(bool value, TaskCompletionSource<bool> disposed) : IDataPreparedSubscriptionDelivery
{
internal bool Value { get; } = value;
public long RetainedBytes => 1;
public void Dispose() { if (Value) disposed.TrySetResult(true); }
}
}
internal sealed class PostPrepareGateSink(PartitionedSampleHub hub, bool blockSnapshot) : IDataSubscriptionDeliverySink
{
private readonly ManualResetEventSlim _release = new();
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int BlockedValueWrites;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken)
{
if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot)
{
if (blockSnapshot) hub.BeforeSnapshotValidationForTests = Block;
else hub.BeforeReadForTests = _ => Block();
}
return ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
}
private void Block()
{
hub.BeforeSnapshotValidationForTests = null; hub.BeforeReadForTests = null;
Entered.TrySetResult(true);
if (!_release.Wait(TimeSpan.FromSeconds(5))) throw new TimeoutException();
}
public ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
if (frame is DataSubscriptionValues values && values.IsSnapshot == blockSnapshot)
Interlocked.Increment(ref BlockedValueWrites);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true);
return ValueTask.CompletedTask;
}
internal void Release() => _release.Set();
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
internal sealed class SequencedLiveSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> FirstLiveEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ProbeAck = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Version3Written = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Version4Written = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> Heartbeat = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly System.Collections.Concurrent.ConcurrentQueue<string> Events = new();
private readonly TaskCompletionSource<bool> _releaseFirst = new(TaskCreationOptions.RunContinuationsAsynchronously);
private ulong _firstHandle;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
var frame = ((Prepared)prepared).Frame;
if (frame is DataSubscriptionAck { CommandId: "open" } open) _firstHandle = open.Items[0].Handle!.Handle;
if (frame is DataSubscriptionAck { CommandId: "probe" }) ProbeAck.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Heartbeat }) Heartbeat.TrySetResult(true);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Events.Enqueue("coalesced");
if (frame is not DataSubscriptionValues { IsSnapshot: false } values || values.Items[0].Handle.Handle != _firstHandle) return;
var version = values.Items[0].Sample.Version;
if (version == 2)
{
FirstLiveEntered.TrySetResult(true);
await _releaseFirst.Task; // intentionally gated transport write
}
Events.Enqueue("value-" + version);
if (version == 3) Version3Written.TrySetResult(true);
if (version == 4) Version4Written.TrySetResult(true);
}
internal void ReleaseFirst() => _releaseFirst.TrySetResult(true);
private sealed class Prepared(DataSubscriptionFrame frame) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { }
}
}
internal sealed class BlockingValueWriteSink : IDataSubscriptionDeliverySink
{
internal readonly TaskCompletionSource<bool> Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource<bool> ValueDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal DataSubscriptionValues? Value;
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame, ValueDisposed));
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
{
if (((Prepared)prepared).Frame is not DataSubscriptionValues value) return;
Value = value; Entered.TrySetResult(true);
await _release.Task; // intentionally ignores cancellation after transport handoff
}
internal void Release() => _release.TrySetResult(true);
private sealed class Prepared(DataSubscriptionFrame frame, TaskCompletionSource<bool> disposed) : IDataPreparedSubscriptionDelivery
{
internal DataSubscriptionFrame Frame { get; } = frame;
public long RetainedBytes => 1;
public void Dispose() { if (Frame is DataSubscriptionValues) disposed.TrySetResult(true); }
}
}
@@ -0,0 +1,202 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataAcquisitionCapacityTests : RuntimeActorTestBase
{
[Fact]
public async Task Abandoned_establishment_pins_shared_driver_capacity_until_the_late_handle_is_released()
{
var capacity = new SubscriptionAcquisitionCapacity(2);
var parent = CreateTestProbe();
var firstDriver = new GateDriver("same", blocked: true, blockCleanup: true);
var first = parent.ChildActorOf(DriverInstanceActor.Props(firstDriver, commsLossTimeout: TimeSpan.Zero,
clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity), TestContext.Current.CancellationToken);
first.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
first.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true));
await firstDriver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var watcher = CreateTestProbe();
watcher.Watch(first);
Sys.Stop(first);
watcher.ExpectTerminated(first, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => !m.Connected && m.ProducerIncarnation == 7,
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacementDriver = new GateDriver("same", blocked: false, blockCleanup: false);
var replacement = parent.ChildActorOf(DriverInstanceActor.Props(replacementDriver, commsLossTimeout: TimeSpan.Zero,
clusterId: "cluster", sourceIncarnation: 8, acquisitionCapacity: capacity), TestContext.Current.CancellationToken);
replacement.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var denied = await replacement.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 2, 8, true), PresenceBudget,
TestContext.Current.CancellationToken);
denied.Succeeded.ShouldBeFalse();
replacementDriver.Entered.Task.IsCompleted.ShouldBeFalse();
var otherDriver = new GateDriver("other", blocked: false, blockCleanup: false);
var other = parent.ChildActorOf(DriverInstanceActor.Props(otherDriver, commsLossTimeout: TimeSpan.Zero,
clusterId: "cluster", sourceIncarnation: 9, acquisitionCapacity: capacity), TestContext.Current.CancellationToken);
other.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var otherAck = await other.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 3, 9, true), PresenceBudget,
TestContext.Current.CancellationToken);
otherAck.Succeeded.ShouldBeTrue();
firstDriver.Complete();
await firstDriver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
denied = await replacement.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 4, 8, true), PresenceBudget,
TestContext.Current.CancellationToken);
denied.Succeeded.ShouldBeFalse("a late handle's unsubscribe is still in flight");
firstDriver.CompleteCleanup();
AwaitAssert(() => capacity.ReservedDriverCount.ShouldBe(1), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var accepted = await replacement.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 5, 8, true), PresenceBudget,
TestContext.Current.CancellationToken);
accepted.Succeeded.ShouldBeTrue();
firstDriver.CleanupCount.ShouldBe(1);
}
[Fact]
public async Task Replacement_keeps_capacity_until_previous_handle_actually_finishes_cleanup()
{
var capacity = new SubscriptionAcquisitionCapacity(2);
var parent = CreateTestProbe();
var driver = new GateDriver("same", blocked: false, blockCleanup: true);
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero,
clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var first = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
first.Succeeded.ShouldBeTrue();
var replacement = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag", "next"], TimeSpan.FromSeconds(1), [], 2, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
(await replacement.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
var third = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag", "third"], TimeSpan.FromSeconds(1), [], 3, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
third.Succeeded.ShouldBeFalse();
capacity.ReservedDriverCount.ShouldBe(1);
driver.CompleteCleanup();
}
[Fact]
public async Task Timed_out_replacement_blocks_further_dispatch_until_late_handle_cleanup_finishes()
{
var clock = new ManualTimeProvider();
var capacity = new SubscriptionAcquisitionCapacity(2);
var parent = CreateTestProbe();
var driver = new SlowReplacementDriver();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero,
clusterId: "cluster", sourceIncarnation: 7, acquisitionCapacity: capacity,
acquisitionTimeout: TimeSpan.FromSeconds(5), acquisitionClock: clock), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var first = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
first.Succeeded.ShouldBeTrue();
var deadline = clock.GetUtcNow().AddSeconds(5);
var second = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag", "b"], TimeSpan.FromSeconds(1), [], 2, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await clock.WaitForTimerDueAtAsync(deadline, PresenceBudget);
clock.Advance(TimeSpan.FromSeconds(5));
(await second.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeFalse();
var denied = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag", "c"], TimeSpan.FromSeconds(1), [], 3, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
denied.Succeeded.ShouldBeFalse();
denied.Busy.ShouldBeTrue();
var ready = denied.RetryWhenReady.ShouldNotBeNull();
driver.CallCount.ShouldBe(2);
driver.CompleteLate();
await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
ready.IsCompleted.ShouldBeFalse();
driver.CompleteCleanup();
(await ready.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeTrue();
var fourth = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag", "d"], TimeSpan.FromSeconds(1), [], 4, 7, true), PresenceBudget,
TestContext.Current.CancellationToken);
fourth.Succeeded.ShouldBeTrue();
driver.CallCount.ShouldBe(3);
}
private sealed class SlowReplacementDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
private readonly TaskCompletionSource _late = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _cleanup = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int CallCount;
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) =>
Task.FromResult<ISubscriptionHandle>(new Handle());
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct)
{
CleanupEntered.TrySetResult();
await _cleanup.Task;
}
public async Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
if (Interlocked.Increment(ref CallCount) == 2)
{
Entered.TrySetResult();
await _late.Task; // deliberate cancellation-ignoring late operation
}
return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation);
}
internal void CompleteLate() => _late.TrySetResult();
internal void CompleteCleanup() => _cleanup.TrySetResult();
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "late-replacement"; }
}
private sealed class GateDriver(string id, bool blocked, bool blockCleanup) : StubDriver, IDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
string IDriver.DriverInstanceId => id;
private readonly TaskCompletionSource _result = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _cleanup = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal int CleanupCount;
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) =>
Task.FromResult<ISubscriptionHandle>(new Handle());
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct)
{
Interlocked.Increment(ref CleanupCount);
CleanupEntered.TrySetResult();
if (blockCleanup) await _cleanup.Task;
}
public async Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
Entered.TrySetResult();
if (blocked) await _result.Task; // deliberately ignores actor cancellation
return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation);
}
internal void Complete() => _result.TrySetResult();
internal void CompleteCleanup() => _cleanup.TrySetResult();
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "capacity"; }
}
}
@@ -0,0 +1,202 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataAcquisitionStatusTests : RuntimeActorTestBase
{
private const uint Bad = 0x80050000u;
private static readonly DateTime SourceTime = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
private static readonly DateTime ServerTime = SourceTime.AddSeconds(1);
private static (PartitionedSampleHub Hub, SourceSamplePublisher Publisher, SourceTicket Ticket, long Incarnation, ManualTimeProvider Clock) Setup()
{
var clock = new ManualTimeProvider();
var hub = HubTest.Create(clock: clock);
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
var incarnation = publisher.RegisterDriverIncarnation("stub-driver-1");
publisher.RegisterDriverShape("stub-driver-1", "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", "stub-driver-1", "tag", incarnation).ShouldBeTrue();
publisher.TryCaptureDriver("stub-driver-1", "tag", incarnation, out var ticket).ShouldBeTrue();
return (hub, publisher, ticket, incarnation, clock);
}
[Fact]
public async Task Bad_null_acquisition_updates_status_without_refreshing_a_previous_value()
{
var (hub, publisher, ticket, incarnation, clock) = Setup();
using (hub)
{
publisher.TryPublish(ticket, new(42, 0, SourceTime, ServerTime)).ShouldBeTrue();
hub.ProcessPending();
using var before = hub.Read(ticket);
var received = before.ReceivedTimestamp;
var version = before.Sample.ShouldNotBeNull().Version;
clock.Advance(TimeSpan.FromMinutes(3));
var driver = new StatusDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var ack = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken);
ack.Succeeded.ShouldBeTrue();
driver.Emit(null, Bad);
hub.ProcessPending();
using var after = hub.Read(ticket);
after.Readiness.ShouldBe(DataReadiness.Ready);
var sample = after.Sample.ShouldNotBeNull();
sample.Value.GetScalar().ShouldBe(42);
sample.StatusCode.ShouldBe(Bad);
sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(ServerTime));
sample.Version.ShouldBeGreaterThan(version);
after.ReceivedTimestamp.ShouldBe(received);
}
}
[Fact]
public void First_status_only_result_remains_waiting_without_a_fabricated_sample()
{
var (hub, publisher, ticket, _, _) = Setup();
using (hub)
{
publisher.TryPublishAcquisitionStatus(ticket, Bad).ShouldBeTrue();
hub.ProcessPending();
using var read = hub.Read(ticket);
read.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
read.Sample.ShouldBeNull();
}
}
[Fact]
public async Task Pre_ack_callback_is_dropped_and_waiting_ends_only_after_a_later_real_read()
{
var (hub, publisher, ticket, incarnation, _) = Setup();
using (hub)
{
var driver = new EarlyDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var pending = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
hub.ProcessPending();
using (var early = hub.Read(ticket))
{
early.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
early.Sample.ShouldBeNull();
}
driver.Acknowledge();
(await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
hub.ProcessPending();
using (var afterAck = hub.Read(ticket))
{
afterAck.Readiness.ShouldBe(DataReadiness.WaitingForInitialData);
afterAck.Sample.ShouldBeNull();
}
driver.Emit(42);
hub.ProcessPending();
using var observed = hub.Read(ticket);
observed.Readiness.ShouldBe(DataReadiness.Ready);
observed.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(42);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Status_ingress_never_waits_for_publisher_or_slot_contention_and_invalidates_old_good(bool publisherGate)
{
var (hub, publisher, ticket, _, _) = Setup();
using (hub)
using (var entered = new ManualResetEventSlim())
using (var release = new ManualResetEventSlim())
{
publisher.TryPublish(ticket, new(42, 0, SourceTime, ServerTime)).ShouldBeTrue();
hub.ProcessPending();
var holder = Task.Run(() => publisher.WithAcquisitionStatusLockForTest(ticket, publisherGate, () =>
{
entered.Set(); release.Wait(TestContext.Current.CancellationToken);
}), TestContext.Current.CancellationToken);
try
{
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
var result = Task.Run(() => publisher.TryPublishAcquisitionStatus(ticket, Bad), TestContext.Current.CancellationToken);
(await result.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBe(publisherGate);
}
finally { release.Set(); await holder.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken); }
hub.ProcessPending();
using var read = hub.Read(ticket);
if (publisherGate)
{
read.Readiness.ShouldBe(DataReadiness.Ready);
read.Sample.ShouldNotBeNull().StatusCode.ShouldBe(Bad);
}
else read.Readiness.ShouldNotBe(DataReadiness.Ready);
}
}
private sealed class StatusDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
private AcquisitionSubscriptionRequest? _request;
private Action<AcquisitionBatch>? _callback;
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) =>
Task.FromResult<ISubscriptionHandle>(new Handle());
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
_request = request; _callback = callback;
return Task.FromResult(new AcquisitionSubscriptionResult(new Handle(), request.RequestedSamplingInterval,
request.DesiredRevision, request.ProducerIncarnation));
}
internal void Emit(object? value, uint status) => _callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation,
[new("tag", new DataValueSnapshot(value, status, null, DateTime.UtcNow))]));
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "status"; }
}
private sealed class EarlyDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
private readonly TaskCompletionSource _ack = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
private AcquisitionSubscriptionRequest? _request;
private Action<AcquisitionBatch>? _callback;
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) =>
Task.FromResult<ISubscriptionHandle>(new Handle());
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public async Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
_request = request; _callback = callback;
Emit(41);
Entered.TrySetResult();
await _ack.Task.WaitAsync(ct);
return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation);
}
internal void Acknowledge() => _ack.TrySetResult();
internal void Emit(int value) => _callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation,
[new("tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))]));
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "early"; }
}
}
@@ -0,0 +1,415 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataDriverDemandActorTests : RuntimeActorTestBase
{
[Fact]
public async Task Desired_revision_is_acknowledged_only_after_the_actual_driver_operation()
{
var driver = new ControlledAcquisitionDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero,
sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var requested = new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"],
TimeSpan.FromMilliseconds(200), ["alarm"], DesiredRevision: 17, ProducerIncarnation: 7,
RequireAcquisition: true);
var response = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(requested,
PresenceBudget, TestContext.Current.CancellationToken);
var request = await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
request.FullReferences.ShouldBe(["legacy", "grpc"]);
request.DesiredRevision.ShouldBe(17);
request.ProducerIncarnation.ShouldBe(7);
response.IsCompleted.ShouldBeFalse("the real SubscribeAcquisitionAsync has not completed");
driver.Complete();
var ack = await response;
ack.DesiredRevision.ShouldBe(17);
ack.ProducerIncarnation.ShouldBe(7);
ack.NominalSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200));
ack.Succeeded.ShouldBeTrue();
}
[Fact]
public async Task Failed_replacement_preserves_the_existing_legacy_subscription()
{
var driver = new ControlledAcquisitionDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero,
sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(["legacy"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken);
var response = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"], TimeSpan.FromMilliseconds(200), [],
DesiredRevision: 18, ProducerIncarnation: 7, RequireAcquisition: true), PresenceBudget, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
driver.Fail();
(await response).Succeeded.ShouldBeFalse();
driver.FireLegacy(11);
var published = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
published.Items.ShouldHaveSingleItem().Value.ShouldBe(11);
driver.UnsubscribeCount.ShouldBe(0, "the failed stronger demand must not tear down independent legacy acquisition");
}
[Fact]
public async Task Unsupported_acquisition_is_rejected_before_touching_the_legacy_handle()
{
var driver = new SubscribableStubDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, commsLossTimeout: TimeSpan.Zero,
sourceIncarnation: 7, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)), TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(["legacy"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken);
var ack = await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["legacy", "grpc"], TimeSpan.FromMilliseconds(200), [],
DesiredRevision: 19, ProducerIncarnation: 7, RequireAcquisition: true), PresenceBudget, TestContext.Current.CancellationToken);
ack.Succeeded.ShouldBeFalse();
driver.UnsubscribeCount.ShouldBe(0);
driver.FireDataChange("legacy", 12, 0);
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken).Items.ShouldHaveSingleItem().Value.ShouldBe(12);
}
[Fact]
public async Task Raw_callback_cannot_publish_a_reference_outside_its_acknowledged_set()
{
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
const string driverId = "stub-driver-1";
var incarnation = publisher.RegisterDriverIncarnation(driverId);
var shape = new SourceValueShape(DataValueKind.Int32, null, -1);
publisher.RegisterDriverShape(driverId, "tag", shape).ShouldBeTrue();
publisher.RegisterDriverShape(driverId, "other", shape).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "other", incarnation).ShouldBeTrue();
publisher.TryCaptureDriver(driverId, "tag", incarnation, out var tag).ShouldBeTrue();
publisher.TryCaptureDriver(driverId, "other", incarnation, out var other).ShouldBeTrue();
var driver = new ControlledAcquisitionDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var pending = actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken);
await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
driver.Complete();
(await pending).Succeeded.ShouldBeTrue();
driver.FireAcquired("other", 40);
driver.FireAcquired("tag", 41);
hub.ProcessPending();
using var valid = hub.Read(tag);
using var outside = hub.Read(other);
valid.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41);
outside.Sample.ShouldBeNull();
}
[Fact]
public async Task Retiring_acquisition_handle_cannot_publish_through_the_replacement_legacy_handler()
{
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
const string driverId = "stub-driver-1";
var incarnation = publisher.RegisterDriverIncarnation(driverId);
publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue();
publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue();
var driver = new RetiringDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
(await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
try
{
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), []));
await driver.CleanupEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await driver.LegacyEntered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var initial = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
initial.Items.ShouldHaveSingleItem().Value.ShouldBe(123, "the initial legacy callback can precede its subscribe return");
hub.ProcessPending();
using (var first = hub.Read(ticket)) first.Sample.ShouldNotBeNull().Version.ShouldBe(1);
driver.FireOld(999);
driver.FireCurrent(124);
var current = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
current.Items.ShouldHaveSingleItem().Value.ShouldBe(124);
hub.ProcessPending();
using var read = hub.Read(ticket);
read.Sample.ShouldNotBeNull().Version.ShouldBe(2, "a late old-handle event cannot reach the source hub");
read.Sample.Value.GetScalar().ShouldBe(124);
}
finally { driver.ReleaseCleanup(); }
}
[Fact]
public async Task Captured_old_delegate_during_retire_cannot_publish_before_new_legacy_gate_exists()
{
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
const string driverId = "stub-driver-1";
var incarnation = publisher.RegisterDriverIncarnation(driverId);
publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue();
publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue();
var driver = new RetireWindowDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
(await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
try
{
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), []));
await driver.RetireCallbackFired.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await driver.LegacyCallbackFired.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var initial = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
initial.Items.ShouldHaveSingleItem().Value.ShouldBe(123, "the captured old event must not cross the retire/detach gap");
hub.ProcessPending();
using var read = hub.Read(ticket);
read.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(123);
read.Sample.Version.ShouldBe(1, "the stale event must not reach the source hub");
}
finally { driver.ReleaseCleanup(); }
}
private sealed class RetireWindowDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
private readonly Handle _old = new("old"), _legacy = new("legacy");
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
private EventHandler<DataChangeEventArgs>? _events, _captured;
internal readonly TaskCompletionSource RetireCallbackFired = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource LegacyCallbackFired = new(TaskCreationOptions.RunContinuationsAsynchronously);
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { _events += value; } remove { _events -= value; } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
{
_events?.Invoke(this, Event(_legacy, 123));
LegacyCallbackFired.TrySetResult();
return Task.FromResult<ISubscriptionHandle>(_legacy);
}
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct)
{
if (!ReferenceEquals(handle, _old)) return;
_captured?.Invoke(this, Event(_old, 999));
RetireCallbackFired.TrySetResult();
await _release.Task;
}
public Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
_captured = _events;
return Task.FromResult(new AcquisitionSubscriptionResult(_old, request.RequestedSamplingInterval,
request.DesiredRevision, request.ProducerIncarnation));
}
internal void ReleaseCleanup() => _release.TrySetResult();
private static DataChangeEventArgs Event(ISubscriptionHandle handle, int value) =>
new(handle, "tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow));
private sealed record Handle(string DiagnosticId) : ISubscriptionHandle;
}
[Fact]
public async Task Restoration_preserves_all_130_synchronous_legacy_initials_despite_hub_pressure_and_missing_shapes()
{
using var hub = HubTest.Create(bytes: 10_000, ingress: 1, dirty: 1, maxSources: 1);
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
const string driverId = "stub-driver-1";
var incarnation = publisher.RegisterDriverIncarnation(driverId);
publisher.RegisterDriverShape(driverId, "tag-0", new(DataValueKind.Int32, null, -1)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "tag-0", incarnation).ShouldBeTrue();
var driver = new ManyInitialDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
(await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag-0"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
var refs = Enumerable.Range(0, 130).Select(i => $"tag-{i}").ToArray();
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(refs, TimeSpan.FromSeconds(1), []));
for (var i = 0; i < refs.Length; i++)
{
var batch = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
batch.Items.ShouldHaveSingleItem().FullReference.ShouldBe(refs[i]);
batch.Items[0].Value.ShouldBe(i);
}
}
[Fact]
public async Task Staged_legacy_initial_keeps_its_original_ingress_age_while_subscribe_ack_is_delayed()
{
var clock = new ManualTimeProvider();
using var hub = HubTest.Create(clock: clock);
var publisher = new SourceSamplePublisher(hub, new("node-a", "serving-1", "Primary", 1, 1));
const string driverId = "stub-driver-1";
var incarnation = publisher.RegisterDriverIncarnation(driverId);
publisher.RegisterDriverShape(driverId, "tag", new(DataValueKind.Int32, null, -1)).ShouldBeTrue();
publisher.EnsureDriverBinding("cluster", driverId, "tag", incarnation).ShouldBeTrue();
publisher.TryCaptureDriver(driverId, "tag", incarnation, out var ticket).ShouldBeTrue();
var driver = new DelayedLegacyDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster", commsLossTimeout: TimeSpan.Zero,
sourcePublisher: publisher, sourceIncarnation: incarnation, acquisitionCapacity: new SubscriptionAcquisitionCapacity(4)),
TestContext.Current.CancellationToken);
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
parent.ExpectMsg<DriverInstanceActor.ConnectivityChanged>(m => m.Connected, PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
(await actor.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), [], 1, incarnation, true),
PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
var originalReceipt = clock.GetTimestamp();
try
{
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(["tag"], TimeSpan.FromSeconds(1), []));
await driver.Entered.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
clock.Advance(TimeSpan.FromMinutes(3));
driver.Complete();
var initial = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
initial.Items.ShouldHaveSingleItem().Value.ShouldBe(42);
hub.ProcessPending();
using var read = hub.Read(ticket);
read.ReceivedTimestamp.ShouldBe(originalReceipt);
read.Sample.ShouldNotBeNull().SourceTimestampUtc.ShouldBe(new DateTimeOffset(DelayedLegacyDriver.SourceTime));
}
finally { driver.Complete(); }
}
private sealed class DelayedLegacyDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
internal static readonly DateTime SourceTime = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public async Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
{
var handle = new Handle("legacy");
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, "tag", new DataValueSnapshot(42, 0, SourceTime, SourceTime)));
Entered.TrySetResult();
await _release.Task.WaitAsync(ct);
return handle;
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct) => Task.FromResult(
new AcquisitionSubscriptionResult(new Handle("acquisition"), request.RequestedSamplingInterval,
request.DesiredRevision, request.ProducerIncarnation));
internal void Complete() => _release.TrySetResult();
private sealed record Handle(string DiagnosticId) : ISubscriptionHandle;
}
private sealed class ManyInitialDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
{
var handle = new Handle("legacy");
for (var i = 0; i < refs.Count; i++)
OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, refs[i],
new DataValueSnapshot(i, 0, DateTime.UtcNow, DateTime.UtcNow)));
return Task.FromResult<ISubscriptionHandle>(handle);
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct) => Task.FromResult(
new AcquisitionSubscriptionResult(new Handle("acquisition"), request.RequestedSamplingInterval,
request.DesiredRevision, request.ProducerIncarnation));
private sealed record Handle(string DiagnosticId) : ISubscriptionHandle;
}
private sealed class RetiringDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
private readonly Handle _old = new("old"), _current = new("current");
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource CleanupEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly TaskCompletionSource LegacyEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
{
Fire(_current, 123);
LegacyEntered.TrySetResult();
return Task.FromResult<ISubscriptionHandle>(_current);
}
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct)
{
if (!ReferenceEquals(handle, _old)) return;
CleanupEntered.TrySetResult();
await _release.Task;
}
public Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct) => Task.FromResult(
new AcquisitionSubscriptionResult(_old, request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation));
internal void FireOld(int value) => Fire(_old, value);
internal void FireCurrent(int value) => Fire(_current, value);
internal void ReleaseCleanup() => _release.TrySetResult();
private void Fire(ISubscriptionHandle handle, int value) => OnDataChange?.Invoke(this,
new DataChangeEventArgs(handle, "tag", new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow)));
private sealed record Handle(string DiagnosticId) : ISubscriptionHandle;
}
private sealed class ControlledAcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedAcquisitionSource
{
internal readonly TaskCompletionSource<AcquisitionSubscriptionRequest> Entered =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _complete = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Handle _legacy = new();
private Action<AcquisitionBatch>? _callback;
private AcquisitionSubscriptionRequest? _request;
internal int UnsubscribeCount;
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> fullReferences,
TimeSpan publishingInterval, CancellationToken cancellationToken) =>
Task.FromResult<ISubscriptionHandle>(_legacy);
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{ Interlocked.Increment(ref UnsubscribeCount); return Task.CompletedTask; }
public async Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> onAcquired, CancellationToken cancellationToken)
{
_callback = onAcquired;
_request = request;
Entered.TrySetResult(request);
await _complete.Task.WaitAsync(cancellationToken);
return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation);
}
internal void Complete() => _complete.TrySetResult(true);
internal void Fail() => _complete.TrySetException(new InvalidOperationException("device rejected replacement"));
internal void FireLegacy(int value) => OnDataChange?.Invoke(this,
new DataChangeEventArgs(_legacy, "legacy", new DataValueSnapshot(value, 0, null, null)));
internal void FireAcquired(string reference, int value) => _callback!(new(_request!.DesiredRevision,
_request.ProducerIncarnation, [new(reference, new DataValueSnapshot(value, 0, DateTime.UtcNow, DateTime.UtcNow))]));
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "controlled"; }
}
}
@@ -0,0 +1,225 @@
using Akka.Actor;
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.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataDriverDemandBridgeTests : RuntimeActorTestBase
{
private static readonly DataSubscriptionSettings Settings = new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
private static SubscriptionAuthorizedView View()
{
var view = new DataView(new("cluster", "urn:raw", "string", "tag"), DataRealm.Raw, null, 0, "subject");
var source = SourceKey.ForDriver("cluster", "driver", "tag", "node", "inc");
return new SubscriptionAuthorizedView(view, source, new("node", "inc", "Primary", 1, 1),
new(view, "tag", "Variable", DataValueKind.Int32, -1, [], false, DataOperations.Subscribe, 1, "tag", null, false),
"principal", "export", new(DataTargetMode.Node, "cluster", "node"), DataConsistency.Primary, () => true);
}
[Fact]
public async Task Shared_interests_wait_for_driver_ack_and_last_release_removes_physical_demand()
{
var host = CreateTestProbe();
var registry = new UpstreamDemandRegistry(8, 16);
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8));
var firstTask = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var demand = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
demand.DriverInstanceId.ShouldBe("driver");
demand.FullReferences.ShouldBe(["tag"]);
firstTask.IsCompleted.ShouldBeFalse();
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, Settings.SamplingInterval, true));
var first = await firstTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
first.Status.ShouldBe(DataItemStatus.Good);
first.Boundary.ShouldBe(demand.DesiredRevision);
var secondPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var verified = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
verified.DesiredRevision.ShouldBe(demand.DesiredRevision);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(verified.DesiredRevision, 7, Settings.SamplingInterval, true));
var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Status.ShouldBe(DataItemStatus.Good);
first.Lease.ShouldNotBeNull().Dispose();
second.Lease.ShouldNotBeNull().Dispose();
var removed = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
removed.FullReferences.ShouldBeEmpty();
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true));
}
[Fact]
public async Task Slower_physical_floor_rejects_interest_and_restores_previous_demand()
{
var host = CreateTestProbe();
var registry = new UpstreamDemandRegistry(8, 16);
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, maxDrivers: 8, maxInterests: 16, timeout: PresenceBudget, ownership: new SubscriptionAcquisitionCapacity(8));
var request = Settings with { SamplingInterval = TimeSpan.FromMilliseconds(1) };
var pending = source.AcquireAsync(View(), request, TestContext.Current.CancellationToken).AsTask();
var demand = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(demand.DesiredRevision, 7, TimeSpan.FromMilliseconds(100), true));
var result = await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
result.Status.ShouldNotBe(DataItemStatus.Good);
result.Lease.ShouldBeNull();
var removed = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
removed.FullReferences.ShouldBeEmpty();
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true));
}
[Fact]
public async Task Relaxation_waits_for_proven_busy_cleanup_then_applies_latest_refs()
{
var host = CreateTestProbe();
var registry = new UpstreamDemandRegistry(8, 16);
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8));
var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var firstApply = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(firstApply.DesiredRevision, 7, Settings.SamplingInterval, true));
var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var secondView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") };
var secondPending = source.AcquireAsync(secondView, Settings, TestContext.Current.CancellationToken).AsTask();
var expanded = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
expanded.FullReferences.ShouldBe(["next", "tag"]);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true));
var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Lease.ShouldNotBeNull().Dispose();
var relaxation = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
relaxation.FullReferences.ShouldBe(["tag"]);
var cleanup = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relaxation.DesiredRevision, 7, TimeSpan.Zero, false,
Busy: true, RetryWhenReady: cleanup.Task));
cleanup.SetResult(true);
var retried = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
retried.FullReferences.ShouldBe(["tag"]);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(retried.DesiredRevision, 7, Settings.SamplingInterval, true));
first.Lease.ShouldNotBeNull().Dispose();
var removed = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
removed.FullReferences.ShouldBeEmpty();
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(removed.DesiredRevision, 7, TimeSpan.Zero, true));
}
[Fact]
public async Task A_busy_driver_does_not_block_a_different_driver()
{
var host = CreateTestProbe();
var registry = new UpstreamDemandRegistry(8, 16);
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), registry, 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8));
var firstPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var initial = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(initial.DesiredRevision, 7, Settings.SamplingInterval, true));
var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var nextView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") };
var secondPending = source.AcquireAsync(nextView, Settings, TestContext.Current.CancellationToken).AsTask();
var expanded = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(expanded.DesiredRevision, 7, Settings.SamplingInterval, true));
var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Lease.ShouldNotBeNull().Dispose();
var relax = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var blocked = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(relax.DesiredRevision, 7, TimeSpan.Zero, false,
Busy: true, RetryWhenReady: blocked.Task));
var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") };
var otherPending = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask();
var otherApply = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
otherApply.DriverInstanceId.ShouldBe("driver2");
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(otherApply.DesiredRevision, 8, Settings.SamplingInterval, true));
var other = await otherPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
other.Status.ShouldBe(DataItemStatus.Good);
blocked.TrySetResult(false);
first.Lease.ShouldNotBeNull().Dispose();
other.Lease.ShouldNotBeNull().Dispose();
}
[Fact]
public async Task A_driver_with_an_unanswered_first_ack_does_not_block_another_driver()
{
var host = CreateTestProbe();
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8));
var pendingA = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var requestA = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replyA = host.LastSender;
var otherView = View() with { Source = SourceKey.ForDriver("cluster", "driver2", "tag", "node", "inc") };
var pendingB = source.AcquireAsync(otherView, Settings, TestContext.Current.CancellationToken).AsTask();
var requestB = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
requestB.DriverInstanceId.ShouldBe("driver2");
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(requestB.DesiredRevision, 8, Settings.SamplingInterval, true));
var second = await pendingB.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Status.ShouldBe(DataItemStatus.Good);
pendingA.IsCompleted.ShouldBeFalse();
replyA.Tell(new DriverInstanceActor.AcquisitionDemandApplied(requestA.DesiredRevision, 7, Settings.SamplingInterval, true));
var first = await pendingA.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
first.Status.ShouldBe(DataItemStatus.Good);
first.Lease?.Dispose(); second.Lease?.Dispose();
}
[Fact]
public async Task Identical_interest_churn_does_not_rescan_all_existing_interests()
{
var host = Sys.ActorOf(Props.Create(() => new AutomaticAckHost()));
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(4, 2048), 4, 2048, PresenceBudget, new SubscriptionAcquisitionCapacity(4));
var leases = new List<IDisposable>();
for (var i = 0; i < 1024; i++)
{
var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken);
leases.Add(result.Lease.ShouldNotBeNull());
}
var before = source.ReferenceVisitCount;
for (var i = 0; i < 64; i++)
{
var result = await source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken);
leases.Add(result.Lease.ShouldNotBeNull());
}
(source.ReferenceVisitCount - before).ShouldBeLessThan(1024L, "each add must not scan the existing 1,000 interests");
foreach (var lease in leases) lease.Dispose();
}
[Fact]
public async Task Canceled_expansion_rolls_back_with_a_revision_newer_than_the_late_expansion()
{
var host = CreateTestProbe();
using var source = new DriverHostSubscriptionDemandSource(Wrap(host.Ref), new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, new SubscriptionAcquisitionCapacity(8));
var aPending = source.AcquireAsync(View(), Settings, TestContext.Current.CancellationToken).AsTask();
var a = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(a.DesiredRevision, 7, Settings.SamplingInterval, true));
var first = await aPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var bView = View() with { Source = SourceKey.ForDriver("cluster", "driver", "next", "node", "inc") };
var bPending = source.AcquireAsync(bView, Settings, cancel.Token).AsTask();
var b = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
b.DesiredRevision.ShouldBeGreaterThan(a.DesiredRevision);
var lateReply = host.LastSender;
cancel.Cancel();
await Should.ThrowAsync<OperationCanceledException>(() => bPending);
var rollback = host.ExpectMsg<DriverHostActor.ApplyAcquisitionDemand>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
rollback.FullReferences.ShouldBe(["tag"]);
rollback.DesiredRevision.ShouldBeGreaterThan(b.DesiredRevision);
lateReply.Tell(new DriverInstanceActor.AcquisitionDemandApplied(b.DesiredRevision, 7, Settings.SamplingInterval, true));
host.Reply(new DriverInstanceActor.AcquisitionDemandApplied(rollback.DesiredRevision, 7, Settings.SamplingInterval, true));
first.Lease.ShouldNotBeNull().Dispose();
}
private IActorRef Wrap(IActorRef target) => Sys.ActorOf(Props.Create(() => new OwnerProxy(target)));
private sealed class OwnerProxy : ReceiveActor
{
public OwnerProxy(IActorRef target)
{
Receive<DriverHostActor.RegisterAcquisitionOwner>(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1)));
Receive<DriverHostActor.OpenAcquisitionDemand>(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration)));
Receive<DriverHostActor.AbortOpenAcquisitionDemand>(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true)));
Receive<DriverHostActor.ApplyAcquisitionDemand>(message => target.Forward(message));
}
}
private sealed class AutomaticAckHost : ReceiveActor
{
public AutomaticAckHost()
{
Receive<DriverHostActor.RegisterAcquisitionOwner>(_ => Sender.Tell(new DriverHostActor.AcquisitionOwnerRegistered(true, 1)));
Receive<DriverHostActor.OpenAcquisitionDemand>(message => Sender.Tell(new DriverHostActor.AcquisitionDemandOpened(true, message.RequestedKeyGeneration)));
Receive<DriverHostActor.AbortOpenAcquisitionDemand>(_ => Sender.Tell(new DriverHostActor.AcquisitionOpenAborted(true)));
Receive<DriverHostActor.ApplyAcquisitionDemand>(message => Sender.Tell(new DriverInstanceActor.AcquisitionDemandApplied(
message.DesiredRevision, 7, message.SamplingInterval == TimeSpan.Zero ? TimeSpan.FromMilliseconds(100) : message.SamplingInterval, true)));
}
}
}
@@ -0,0 +1,656 @@
using System.Collections.Concurrent;
using System.Threading.Channels;
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P06")]
public sealed class GrpcDataDriverHostDemandTests : RuntimeActorTestBase
{
[Fact]
public async Task Real_host_merges_legacy_refs_then_restores_them_after_last_grpc_interest()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('a', 64));
var deploy = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deploy, revision);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var driver = factory.Driver!;
const string legacy = "Plant/Modbus/dev1/speed";
AwaitAssert(() => driver.LegacyRefs.ShouldContain(legacy), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var pending = host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17),
PresenceBudget, TestContext.Current.CancellationToken);
var request = await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
request.FullReferences.ShouldContain(legacy);
request.FullReferences.ShouldContain("grpc");
request.RequestedSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200));
pending.IsCompleted.ShouldBeFalse();
driver.Complete();
(await pending).Succeeded.ShouldBeTrue();
host.Tell(new DriverHostActor.ApplyAcquisitionDemand("DI-1", [], TimeSpan.Zero, 18));
AwaitAssert(() => driver.LegacyRefs.ShouldBe([legacy]), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => driver.LegacySubscribeCount.ShouldBeGreaterThanOrEqualTo(2), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task Same_interest_after_real_driver_restart_never_reuses_an_old_producer_ack()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('b', 64));
var deploy = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(8);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deploy, revision);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var original = factory.Driver!;
AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var view = new DataView(new("cluster", "urn:raw", "string", "speed"), DataRealm.Raw, null, 0, "subject");
var auth = new SubscriptionAuthorizedView(view, SourceKey.ForDriver("cluster", "DI-1", "Plant/Modbus/dev1/speed", "node-a", "inc"),
new("node-a", "inc", "Primary", 1, 1),
new(view, "speed", "Variable", DataValueKind.Double, -1, [], false, DataOperations.Subscribe, 1, "speed", null, false),
"principal", "export", new(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, () => true);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(8, 16), 8, 16, PresenceBudget, capacity);
var firstPending = source.AcquireAsync(auth, settings, TestContext.Current.CancellationToken).AsTask();
await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
original.Complete();
var first = await firstPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
first.Status.ShouldBe(DataItemStatus.Good);
host.Tell(new RestartDriver("cluster", "DI-1", "test", Guid.NewGuid()));
AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacement = factory.Driver!;
var secondPending = source.AcquireAsync(auth, settings, TestContext.Current.CancellationToken).AsTask();
var entered = replacement.Requests.Reader.WaitToReadAsync(TestContext.Current.CancellationToken).AsTask();
var winner = await Task.WhenAny(secondPending, entered).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
if (ReferenceEquals(winner, secondPending))
(await secondPending).Status.ShouldNotBe(DataItemStatus.Good, "the new producer has not acknowledged a subscription");
else
{
(await entered).ShouldBeTrue();
secondPending.IsCompleted.ShouldBeFalse("a request to the replacement is still awaiting its acknowledgment");
replacement.Complete();
var second = await secondPending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Lease?.Dispose();
}
first.Lease?.Dispose();
}
[Fact]
public async Task Deployment_while_first_demand_is_pending_reconciles_latest_legacy_and_grpc_refs()
{
var db = NewInMemoryDbFactory();
var revA = RevisionHash.Parse(new string('c', 64));
var revB = RevisionHash.Parse(new string('d', 64));
var deployA = V3ArtifactSeeder.SeedV3Deployment(db, revA,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deployA, revA);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var original = factory.Driver!;
AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var pending = host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17),
PresenceBudget, TestContext.Current.CancellationToken);
await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
pending.IsCompleted.ShouldBeFalse();
var deployB = V3ArtifactSeeder.SeedV3Deployment(db, revB,
[("DI-1", "Modbus", "dev1", "speed", "Double", false),
("DI-1", "Modbus", "dev1", "flow", "Double", false)], [], enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, deployB, revB);
AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacement = factory.Driver!;
original.Complete();
var reconciled = await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
reconciled.FullReferences.ShouldContain("Plant/Modbus/dev1/speed");
reconciled.FullReferences.ShouldContain("Plant/Modbus/dev1/flow");
reconciled.FullReferences.ShouldContain("grpc");
reconciled.RequestedSamplingInterval.ShouldBe(TimeSpan.FromMilliseconds(200));
replacement.Complete();
}
[Fact]
public async Task Removing_last_demand_while_driver_is_absent_prevents_ghost_polling_after_readd()
{
var db = NewInMemoryDbFactory();
var revA = RevisionHash.Parse(new string('e', 64));
var revB = RevisionHash.Parse(new string('f', 64));
var revC = RevisionHash.Parse(new string('1', 64));
var tags = new[] { ("DI-1", "Modbus", "dev1", "speed", "Double", false) };
var deployA = V3ArtifactSeeder.SeedV3Deployment(db, revA, tags, [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deployA, revA);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var original = factory.Driver!;
AwaitAssert(() => original.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var demand = host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17),
PresenceBudget, TestContext.Current.CancellationToken);
await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
original.Complete();
(await demand).Succeeded.ShouldBeTrue();
var remove = V3ArtifactSeeder.SeedV3Deployment(db, revB, [], [], enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, remove, revB);
var cleared = await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", [], TimeSpan.Zero, 18), PresenceBudget,
TestContext.Current.CancellationToken);
cleared.Succeeded.ShouldBeTrue();
var readd = V3ArtifactSeeder.SeedV3Deployment(db, revC, tags, [], enabled: true);
V3ArtifactSeeder.Dispatch(host, coordinator, readd, revC);
AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacement = factory.Driver!;
AwaitAssert(() => replacement.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
replacement.Requests.Reader.TryRead(out _).ShouldBeFalse();
}
[Fact]
public async Task Reclaimed_driver_histories_do_not_exhaust_capacity_and_old_owner_or_key_commands_are_fenced()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('2', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true);
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(2);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
localRoles: new HashSet<string> { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()),
virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref,
acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
var oldOwnerId = Guid.NewGuid();
var oldSerial = capacity.NextOwnerSerial();
var owner = await host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(oldOwnerId, oldSerial), PresenceBudget, TestContext.Current.CancellationToken);
owner.Generation.ShouldBeGreaterThan(0);
for (var i = 0; i < 10; i++)
{
var id = $"retired-{i}";
var opened = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand(id, owner.Generation), PresenceBudget, TestContext.Current.CancellationToken);
opened.Succeeded.ShouldBeTrue();
var closed = await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand(id, [], TimeSpan.Zero, 1,
OwnerGeneration: owner.Generation, KeyGeneration: opened.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken);
closed.Succeeded.ShouldBeTrue();
}
var old = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand("same", owner.Generation), PresenceBudget, TestContext.Current.CancellationToken);
(await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"same", [], TimeSpan.Zero, 1, OwnerGeneration: owner.Generation, KeyGeneration: old.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
var current = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand("same", owner.Generation), PresenceBudget, TestContext.Current.CancellationToken);
current.KeyGeneration.ShouldBeGreaterThan(old.KeyGeneration);
var stale = await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"same", [], TimeSpan.Zero, 2, OwnerGeneration: owner.Generation, KeyGeneration: old.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken);
stale.Succeeded.ShouldBeFalse("a late clear from a retired key must not close its replacement");
var newSerial = capacity.NextOwnerSerial();
var newOwner = await host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(Guid.NewGuid(), newSerial), PresenceBudget, TestContext.Current.CancellationToken);
newOwner.Generation.ShouldBeGreaterThan(owner.Generation);
var delayedRegistration = await host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(oldOwnerId, oldSerial), PresenceBudget, TestContext.Current.CancellationToken);
delayedRegistration.Succeeded.ShouldBeFalse();
var oldOwnerCommand = await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"same", [], TimeSpan.Zero, 3, OwnerGeneration: owner.Generation, KeyGeneration: current.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken);
oldOwnerCommand.Succeeded.ShouldBeFalse();
var newOwnerKey = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand("same", newOwner.Generation), PresenceBudget, TestContext.Current.CancellationToken);
newOwnerKey.Succeeded.ShouldBeTrue();
(await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"same", [], TimeSpan.Zero, 1, OwnerGeneration: newOwner.Generation, KeyGeneration: newOwnerKey.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue("a recreated bridge can restart its per-key revision sequence");
}
[Fact]
public async Task Alarm_only_desired_change_while_acquisition_is_pending_reaches_the_same_driver()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('3', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var driver = factory.Driver!;
const string speed = "Plant/Modbus/dev1/speed";
AwaitAssert(() => driver.LegacyRefs.ShouldContain(speed), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var pending = host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17),
PresenceBudget, TestContext.Current.CancellationToken);
await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await host.Ask<DriverHostActor.LegacySubscriptionsTestApplied>(
new DriverHostActor.SetLegacySubscriptionsForTest("DI-1", [speed], ["alarm-X"]), PresenceBudget,
TestContext.Current.CancellationToken);
driver.Complete();
(await pending.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
var alarms = await driver.AlarmRequests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
alarms.ShouldBe(["alarm-X"]);
factory.Driver.ShouldBeSameAs(driver);
}
[Fact]
public async Task Supervised_host_restart_gives_same_bridge_a_new_proof_and_fences_old_commands()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('6', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true);
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(2);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
localRoles: new HashSet<string> { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()),
virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref,
acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
var ownerId = Guid.NewGuid();
var serial = capacity.NextOwnerSerial();
var first = await host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(ownerId, serial), PresenceBudget, TestContext.Current.CancellationToken);
var oldKey = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand("driver", first.Generation), PresenceBudget, TestContext.Current.CancellationToken);
var priorControl = capacity.ControlGeneration;
host.Tell(new DriverHostActor.CrashForTest());
AwaitAssert(() => capacity.ControlGeneration.ShouldBeGreaterThan(priorControl), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var restarted = await host.Ask<DriverHostActor.AcquisitionOwnerRegistered>(
new DriverHostActor.RegisterAcquisitionOwner(ownerId, serial), PresenceBudget, TestContext.Current.CancellationToken);
restarted.Succeeded.ShouldBeTrue();
restarted.Generation.ShouldBeGreaterThan(first.Generation);
var newKey = await host.Ask<DriverHostActor.AcquisitionDemandOpened>(
new DriverHostActor.OpenAcquisitionDemand("driver", restarted.Generation), PresenceBudget, TestContext.Current.CancellationToken);
newKey.Succeeded.ShouldBeTrue();
var stale = await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"driver", [], TimeSpan.Zero, 1, OwnerGeneration: first.Generation, KeyGeneration: oldKey.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken);
stale.Succeeded.ShouldBeFalse();
(await host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(new DriverHostActor.ApplyAcquisitionDemand(
"driver", [], TimeSpan.Zero, 1, OwnerGeneration: restarted.Generation, KeyGeneration: newKey.KeyGeneration), PresenceBudget,
TestContext.Current.CancellationToken)).Succeeded.ShouldBeTrue();
}
[Fact]
public async Task Idle_bridge_re_registers_after_real_host_restart_before_opening_a_new_key()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('7', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(4);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var original = factory.Driver!;
const string reference = "Plant/Modbus/dev1/speed";
AwaitAssert(() => original.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(4, 8), 4, 8, PresenceBudget, capacity);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
var firstTask = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask();
await original.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
original.Complete();
var first = await firstTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
first.Status.ShouldBe(DataItemStatus.Good);
first.Lease.ShouldNotBeNull().Dispose();
await source.WaitForDriverIdleForTest("DI-1").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var priorControl = capacity.ControlGeneration;
host.Tell(new DriverHostActor.CrashForTest());
AwaitAssert(() => capacity.ControlGeneration.ShouldBeGreaterThan(priorControl), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(original), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacement = factory.Driver!;
AwaitAssert(() => replacement.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var secondTask = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask();
await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
secondTask.IsCompleted.ShouldBeFalse();
replacement.Complete();
var second = await secondTask.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
second.Status.ShouldBe(DataItemStatus.Good);
second.Lease.ShouldNotBeNull().Dispose();
}
[Fact]
public async Task Canceled_opens_release_host_keys_even_if_their_allocated_replies_arrive_late()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('8', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision, [], [], enabled: true);
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(2);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
localRoles: new HashSet<string> { "driver" }, dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()),
virtualTagEvaluator: NullVirtualTagEvaluator.Instance, virtualTagHostOverride: CreateTestProbe().Ref,
acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 2, 4, PresenceBudget, capacity);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
for (var i = 0; i < 6; i++)
{
var driver = $"canceled-{i}";
var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await host.Ask<DriverHostActor.OpenReplyGateInstalledForTest>(
new DriverHostActor.GateOpenReplyForTest(driver, allocated, release.Task), PresenceBudget,
TestContext.Current.CancellationToken);
using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var pending = source.AcquireAsync(Authorized(driver, "tag"), settings, canceled.Token).AsTask();
try
{
await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
canceled.Cancel();
await Should.ThrowAsync<OperationCanceledException>(() => pending);
}
finally { release.TrySetResult(); }
await source.WaitForDriverIdleForTest(driver).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var count = await host.Ask<DriverHostActor.OpenAcquisitionCountForTest>(
new DriverHostActor.GetOpenAcquisitionCountForTest(), PresenceBudget, TestContext.Current.CancellationToken);
count.Count.ShouldBe(0, "cancellation must reclaim the key even when the Open reply was lost");
}
}
[Fact]
public async Task Lost_abort_ack_is_reconciled_before_a_fresh_acquisition_uses_the_key()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('9', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(2);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var driver = factory.Driver!;
const string reference = "Plant/Modbus/dev1/speed";
AwaitAssert(() => driver.LegacyRefs.ShouldContain(reference), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 2, 4,
TimeSpan.FromSeconds(2), capacity, abortRetryDelay: TimeSpan.Zero);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseOpen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var aborted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseAbort = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await host.Ask<DriverHostActor.OpenReplyGateInstalledForTest>(
new DriverHostActor.GateOpenReplyForTest("DI-1", allocated, releaseOpen.Task), PresenceBudget,
TestContext.Current.CancellationToken);
await host.Ask<DriverHostActor.AbortReplyGateInstalledForTest>(
new DriverHostActor.GateAbortReplyForTest("DI-1", aborted, releaseAbort.Task), PresenceBudget,
TestContext.Current.CancellationToken);
using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var canceledOpen = source.AcquireAsync(Authorized("DI-1", reference), settings, canceled.Token).AsTask();
try
{
await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
canceled.Cancel();
await Should.ThrowAsync<OperationCanceledException>(() => canceledOpen);
releaseOpen.TrySetResult();
await aborted.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await source.WaitForOpenAbortFailureForTest("DI-1").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var count = await host.Ask<DriverHostActor.OpenAcquisitionCountForTest>(
new DriverHostActor.GetOpenAcquisitionCountForTest(), PresenceBudget, TestContext.Current.CancellationToken);
count.Count.ShouldBe(0, "the host processed the abort even though its acknowledgement was lost");
releaseAbort.TrySetResult();
var retry = source.AcquireAsync(Authorized("DI-1", reference), settings, TestContext.Current.CancellationToken).AsTask();
await driver.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
retry.IsCompleted.ShouldBeFalse("the fresh driver operation still needs its own acknowledgement");
driver.Complete();
var accepted = await retry.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
accepted.Status.ShouldBe(DataItemStatus.Good);
accepted.Lease.ShouldNotBeNull().Dispose();
}
finally { releaseOpen.TrySetResult(); releaseAbort.TrySetResult(); }
}
[Fact]
public async Task Capacity_pressure_reconciles_lost_abort_ack_for_an_inactive_different_driver()
{
var db = NewInMemoryDbFactory();
var revision = RevisionHash.Parse(new string('a', 64));
var deployment = V3ArtifactSeeder.SeedV3Deployment(db, revision,
[("DI-A", "Modbus", "devA", "speedA", "Double", false),
("DI-B", "ModbusB", "devB", "speedB", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var capacity = new SubscriptionAcquisitionCapacity(1);
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher, acquisitionCapacity: capacity));
V3ArtifactSeeder.Dispatch(host, coordinator, deployment, revision);
AwaitAssert(() => factory.Drivers.Count.ShouldBe(2), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var driverB = factory.Drivers["DI-B"];
const string referenceB = "Plant/ModbusB/devB/speedB";
AwaitAssert(() => driverB.LegacyRefs.ShouldContain(referenceB), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
using var source = new DriverHostSubscriptionDemandSource(host, new UpstreamDemandRegistry(2, 4), 1, 4,
TimeSpan.FromSeconds(2), capacity, abortRetryDelay: TimeSpan.Zero);
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
var allocated = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseOpen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var aborted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseAbort = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await host.Ask<DriverHostActor.OpenReplyGateInstalledForTest>(
new DriverHostActor.GateOpenReplyForTest("DI-A", allocated, releaseOpen.Task), PresenceBudget, TestContext.Current.CancellationToken);
await host.Ask<DriverHostActor.AbortReplyGateInstalledForTest>(
new DriverHostActor.GateAbortReplyForTest("DI-A", aborted, releaseAbort.Task), PresenceBudget, TestContext.Current.CancellationToken);
using var canceled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
var old = source.AcquireAsync(Authorized("DI-A", "Plant/Modbus/devA/speedA"), settings, canceled.Token).AsTask();
try
{
await allocated.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
canceled.Cancel();
await Should.ThrowAsync<OperationCanceledException>(() => old);
releaseOpen.TrySetResult();
await aborted.Task.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
await source.WaitForOpenAbortFailureForTest("DI-A").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
releaseAbort.TrySetResult();
var current = source.AcquireAsync(Authorized("DI-B", referenceB), settings, TestContext.Current.CancellationToken).AsTask();
var entered = driverB.Requests.Reader.WaitToReadAsync(TestContext.Current.CancellationToken).AsTask();
var winner = await Task.WhenAny(current, entered).WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
if (ReferenceEquals(winner, current))
{
(await current).Status.ShouldBe(DataItemStatus.ResourceExhausted);
await source.WaitForDriverIdleForTest("DI-A").WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
current = source.AcquireAsync(Authorized("DI-B", referenceB), settings, TestContext.Current.CancellationToken).AsTask();
}
(await entered.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeTrue();
driverB.Complete();
var accepted = await current.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
accepted.Status.ShouldBe(DataItemStatus.Good);
accepted.Lease.ShouldNotBeNull().Dispose();
}
finally { releaseOpen.TrySetResult(); releaseAbort.TrySetResult(); }
}
private static SubscriptionAuthorizedView Authorized(string driver, string reference)
{
var view = new DataView(new("cluster", "urn:raw", "string", reference), DataRealm.Raw, null, 0, "subject");
return new(view, SourceKey.ForDriver("cluster", driver, reference, "node-a", "inc"),
new("node-a", "inc", "Primary", 1, 1),
new(view, reference, "Variable", DataValueKind.Double, -1, [], false, DataOperations.Subscribe, 1, reference, null, false),
"principal", "export", new(DataTargetMode.Node, "cluster", "node-a"), DataConsistency.Primary, () => true);
}
[Fact]
public async Task Alarm_deployment_during_pending_acquisition_reaches_the_replacement_driver()
{
var db = NewInMemoryDbFactory();
var revA = RevisionHash.Parse(new string('4', 64));
var revB = RevisionHash.Parse(new string('5', 64));
var firstDeploy = V3ArtifactSeeder.SeedV3Deployment(db, revA,
[("DI-1", "Modbus", "dev1", "speed", "Double", false)], [], enabled: true);
var factory = new Factory();
using var hub = HubTest.Create();
var publisher = new SourceSamplePublisher(hub, new("node-a", "inc", "Primary", 1, 1));
var coordinator = CreateTestProbe();
var host = Sys.ActorOf(DriverHostActor.Props(db, NodeId.Parse("node-a"), coordinator.Ref,
driverFactory: factory, localRoles: new HashSet<string> { "driver" },
dependencyMux: Sys.ActorOf(DependencyMuxActor.Props()), virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref, sourcePublisher: publisher,
acquisitionCapacity: new SubscriptionAcquisitionCapacity(8)));
V3ArtifactSeeder.Dispatch(host, coordinator, firstDeploy, revA);
AwaitAssert(() => factory.Driver.ShouldNotBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var old = factory.Driver!;
AwaitAssert(() => old.LegacyRefs.ShouldContain("Plant/Modbus/dev1/speed"), PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken);
var pending = host.Ask<DriverInstanceActor.AcquisitionDemandApplied>(
new DriverHostActor.ApplyAcquisitionDemand("DI-1", ["grpc"], TimeSpan.FromMilliseconds(200), 17),
PresenceBudget, TestContext.Current.CancellationToken);
await old.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
var secondDeploy = V3ArtifactSeeder.SeedV3Deployment(db, revB,
[("DI-1", "Modbus", "dev1", "speed", "Double", false),
("DI-1", "Modbus", "dev1", "alarmX", "Double", false)], [], enabled: true,
tagConfigByTag: new Dictionary<string, string> { ["alarmX"] = """{"alarm":{"alarmType":"AlarmCondition","severity":500}}""" });
V3ArtifactSeeder.Dispatch(host, coordinator, secondDeploy, revB);
AwaitAssert(() => factory.Driver.ShouldNotBeSameAs(old), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
var replacement = factory.Driver!;
old.Complete();
var acquisition = await replacement.Requests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
acquisition.FullReferences.ShouldContain("grpc");
replacement.Complete();
var alarms = await replacement.AlarmRequests.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask()
.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
alarms.ShouldContain("Plant/Modbus/dev1/alarmX");
_ = pending;
}
private sealed class Factory : IDriverFactory
{
internal TestDriver? Driver;
internal readonly ConcurrentDictionary<string, TestDriver> Drivers = new(StringComparer.Ordinal);
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];
public IDriver? TryCreate(string type, string id, string config)
{
var driver = new TestDriver(id);
Drivers[id] = driver;
return Driver = driver;
}
}
private sealed class TestDriver(string id) : StubDriver, IDriver, ISubscribable, IAcknowledgedAcquisitionSource, IAlarmSource
{
string IDriver.DriverInstanceId => id;
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal readonly Channel<AcquisitionSubscriptionRequest> Requests = Channel.CreateUnbounded<AcquisitionSubscriptionRequest>();
internal readonly Channel<IReadOnlyList<string>> AlarmRequests = Channel.CreateUnbounded<IReadOnlyList<string>>();
internal IReadOnlyList<string> LegacyRefs = [];
internal int LegacySubscribeCount;
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
public event EventHandler<AlarmEventArgs>? OnAlarmEvent { add { } remove { } }
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
{
LegacyRefs = refs.ToArray();
Interlocked.Increment(ref LegacySubscribeCount);
return Task.FromResult<ISubscriptionHandle>(new Handle());
}
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public async Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> callback, CancellationToken ct)
{
Requests.Writer.TryWrite(request);
await _completion.Task.WaitAsync(ct);
return new(new Handle(), request.RequestedSamplingInterval, request.DesiredRevision, request.ProducerIncarnation);
}
internal void Complete() => _completion.TrySetResult();
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(IReadOnlyList<string> refs, CancellationToken ct)
{
AlarmRequests.Writer.TryWrite(refs.ToArray());
return Task.FromResult<IAlarmSubscriptionHandle>(new AlarmHandle());
}
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
public Task AcknowledgeAsync(IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken ct) => Task.CompletedTask;
private sealed class AlarmHandle : IAlarmSubscriptionHandle { public string DiagnosticId => "alarm"; }
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "host-test"; }
}
}