Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/GrpcDataDriverDemandActorTests.cs
T

492 lines
32 KiB
C#

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 Baseline_quiet_acquisitions_refresh_receipt_without_fabricating_change_or_source_time()
{
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 BaselineAcquisitionDriver();
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);
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(["tag"], TimeSpan.FromSeconds(1)), PresenceBudget, TestContext.Current.CancellationToken);
driver.Entered.Task.IsCompletedSuccessfully.ShouldBeTrue("baseline must observe actual acquisitions");
var original = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc);
driver.FireAcquired("tag", 41, original);
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
cancellationToken: TestContext.Current.CancellationToken).Items.ShouldHaveSingleItem().Value.ShouldBe(41);
hub.ProcessPending();
using (var first = hub.Read(ticket))
{
first.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41);
first.ReceivedTimestamp.ShouldBe(clock.GetTimestamp());
}
clock.Advance(TimeSpan.FromMinutes(2));
driver.FireAcquired("tag", 41, original);
hub.ProcessPending();
using var second = hub.Read(ticket);
second.Sample.ShouldNotBeNull().Value.GetScalar().ShouldBe(41);
second.Sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(original));
second.Sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(original));
second.ReceivedTimestamp.ShouldBe(clock.GetTimestamp());
second.Sample.Version.ShouldBe(2);
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
}
[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 BaselineAcquisitionDriver : StubDriver, ISubscribable, IAcknowledgedBaselineAcquisitionSource
{
internal readonly TaskCompletionSource<AcquisitionSubscriptionRequest> Entered =
new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly ISubscriptionHandle _handle = new Handle();
private Action<AcquisitionBatch>? _callback;
private AcquisitionSubscriptionRequest? _request;
private int? _last;
public event EventHandler<DataChangeEventArgs>? OnDataChange;
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> references, TimeSpan interval, CancellationToken ct) =>
Task.FromResult(_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;
Entered.TrySetResult(request);
return Task.FromResult(new AcquisitionSubscriptionResult(_handle, request.RequestedSamplingInterval,
request.DesiredRevision, request.ProducerIncarnation));
}
internal void FireAcquired(string reference, int value, DateTime timestamp)
{
var snapshot = new DataValueSnapshot(value, 0, timestamp, timestamp);
_callback!(new(_request!.DesiredRevision, _request.ProducerIncarnation, [new(reference, snapshot)]));
if (_last == value) return;
_last = value;
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, reference, snapshot));
}
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "baseline"; }
}
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, DateTime? timestamp = null) => _callback!(new(_request!.DesiredRevision,
_request.ProducerIncarnation, [new(reference, new DataValueSnapshot(value, 0, timestamp ?? DateTime.UtcNow, timestamp ?? DateTime.UtcNow))]));
private sealed class Handle : ISubscriptionHandle { public string DiagnosticId => "controlled"; }
}
}