1012 lines
59 KiB
C#
1012 lines
59 KiB
C#
using Akka.Actor;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
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.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
|
|
using static ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness.V3ArtifactSeeder;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
[Trait("Feature", "GrpcData")]
|
|
[Trait("Phase", "P04")]
|
|
[Trait("Category", "Unit")]
|
|
public sealed class GrpcDataSourceFeedParityTests : RuntimeActorTestBase
|
|
{
|
|
private static readonly DateTime SourceTime = new DateTime(2026, 11, 15, 8, 10, 12, 123, DateTimeKind.Utc).AddTicks(4567);
|
|
private static readonly DateTime ServerTime = SourceTime.AddSeconds(3);
|
|
private static readonly ServingIdentity Serving = new("node-a", "instance-a", "Primary", 1, 1);
|
|
|
|
[Theory]
|
|
[InlineData(true, true)]
|
|
[InlineData(true, false)]
|
|
[InlineData(false, true)]
|
|
[InlineData(false, false)]
|
|
public async Task Callback_keeps_original_timestamps_independent(bool hasSource, bool hasServer)
|
|
{
|
|
var driver = new CallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver), TestContext.Current.CancellationToken);
|
|
await Subscribe(actor, driver);
|
|
|
|
DateTime? source = hasSource ? SourceTime : null;
|
|
DateTime? server = hasServer ? ServerTime : null;
|
|
driver.Fire(new DataValueSnapshot(17, 0x80740000u, source, server));
|
|
|
|
var item = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(
|
|
PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Items.Single();
|
|
item.SourceTimestampUtc.ShouldBe(source);
|
|
item.ServerTimestampUtc.ShouldBe(server);
|
|
item.StatusCode.ShouldBe(0x80740000u);
|
|
item.TimestampUtc.ShouldBe(source ?? server ?? DateTime.MinValue);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Driver_callback_publishes_source_before_its_actor_mailbox_and_without_sdk_sink()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "stub-driver-1", "source", "node-a", "instance-a");
|
|
var ticket = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var driver = new CallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, sourcePublisher: publisher), TestContext.Current.CancellationToken);
|
|
await Subscribe(actor, driver);
|
|
|
|
var bytes = new byte[] { 7, 8, 9 };
|
|
driver.Fire(new DataValueSnapshot(bytes, 0x80740000u, SourceTime, ServerTime));
|
|
// Fire returns only after the callback. A probe for an actor message would not prove that
|
|
// the hub was admitted before the asynchronous mailbox handoff.
|
|
hub.Commits.Count.ShouldBe(1);
|
|
Array.Fill(bytes, (byte)0);
|
|
var (actualTicket, sample, _) = hub.Commits.Single();
|
|
actualTicket.ShouldBe(ticket);
|
|
sample.Value.GetBytes().ToArray().ShouldBe(new byte[] { 7, 8, 9 });
|
|
sample.StatusCode.ShouldBe(0x80740000u);
|
|
sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(ServerTime));
|
|
}
|
|
|
|
[Fact]
|
|
public void Rejected_ingress_invalidates_current_ticket_without_committing_a_value()
|
|
{
|
|
using var hub = new RecordingSourceHub { RejectReservations = true };
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "ref", "node-a", "instance-a");
|
|
var ticket = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
|
|
publisher.TryPublish(ticket, new DataValueSnapshot(new byte[64], OpcUaStatus.Good, null, null)).ShouldBeFalse();
|
|
|
|
hub.Reservations.ShouldBe(1);
|
|
hub.Invalidated.ShouldContain(ticket);
|
|
hub.Commits.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public void Stale_ticket_cannot_invalidate_or_publish_after_rebind()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "ref", "node-a", "instance-a");
|
|
var old = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
publisher.TryRemove(old).ShouldBeTrue();
|
|
var current = publisher.Bind(key, new SourceGeneration(2, 1));
|
|
publisher.TryPublish(current, new DataValueSnapshot(42, OpcUaStatus.Good, SourceTime, ServerTime)).ShouldBeTrue();
|
|
|
|
hub.RejectReservations = true;
|
|
publisher.TryPublish(old, new DataValueSnapshot(new byte[4], OpcUaStatus.Good, null, null)).ShouldBeFalse();
|
|
|
|
hub.Invalidated.ShouldNotContain(current);
|
|
hub.Commits.Count.ShouldBe(1);
|
|
publisher.TryCapture(key, out var captured).ShouldBeTrue();
|
|
captured.ShouldBe(current);
|
|
}
|
|
|
|
[Fact]
|
|
public void Driver_source_identity_uses_unambiguous_components_and_ignores_aliases()
|
|
{
|
|
var first = SourceKey.ForDriver("c", "ab", "c", "n", "i");
|
|
var collisionCandidate = SourceKey.ForDriver("c", "a", "bc", "n", "i");
|
|
first.ShouldNotBe(collisionCandidate);
|
|
first.ShouldBe(SourceKey.ForDriver("c", "ab", "c", "n", "i"));
|
|
first.ShouldNotBe(SourceKey.ForDriver("c", "ab", "c", "n", "other-instance"));
|
|
}
|
|
|
|
[Fact]
|
|
public void Source_keys_normalize_origin_cluster_case_but_preserve_opaque_identifier_case()
|
|
{
|
|
var driver = SourceKey.ForDriver("Cluster-A", "Driver", "Path/Ref", "Node", "Incarnation");
|
|
driver.ShouldBe(SourceKey.ForDriver("cLuStEr-a", "Driver", "Path/Ref", "Node", "Incarnation"));
|
|
driver.ShouldNotBe(SourceKey.ForDriver("CLUSTER-A", "driver", "Path/Ref", "Node", "Incarnation"));
|
|
driver.ShouldNotBe(SourceKey.ForDriver("CLUSTER-A", "Driver", "path/Ref", "Node", "Incarnation"));
|
|
driver.ShouldNotBe(SourceKey.ForDriver("CLUSTER-A", "Driver", "Path/Ref", "node", "Incarnation"));
|
|
var virtualTag = SourceKey.ForVirtual("Cluster-A", "VTag", "Node", "Incarnation");
|
|
virtualTag.ShouldBe(SourceKey.ForVirtual("cluster-a", "VTag", "Node", "Incarnation"));
|
|
virtualTag.ShouldNotBe(SourceKey.ForVirtual("cluster-a", "vtag", "Node", "Incarnation"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Quiet_initial_callback_is_retained_before_catalog_activation()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub,
|
|
() => new ServingIdentity("node-a", "instance-a", "Primary", 0, 0));
|
|
var key = SourceKey.ForDriver("cluster-a", "stub-driver-1", "source", "node-a", "instance-a");
|
|
publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var driver = new CallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, sourcePublisher: publisher), TestContext.Current.CancellationToken);
|
|
await Subscribe(actor, driver);
|
|
|
|
driver.Fire(new DataValueSnapshot(42, OpcUaStatus.Good, SourceTime, null));
|
|
|
|
var sample = hub.Commits.Single().Sample;
|
|
sample.Value.GetScalar().ShouldBe(42);
|
|
sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
sample.ServerTimestampUtc.ShouldBeNull();
|
|
sample.Serving.CatalogEpoch.ShouldBe(0);
|
|
sample.Serving.AuthorityEpoch.ShouldBe(0);
|
|
Should.Throw<ArgumentOutOfRangeException>(() => sample.Validate());
|
|
}
|
|
|
|
[Fact]
|
|
public void Physical_binding_change_fences_old_ticket_until_new_source_publishes()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "same-raw-path", "node-a", "instance-a");
|
|
var old = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
publisher.TryPublish(old, new DataValueSnapshot(1, OpcUaStatus.Good, SourceTime, ServerTime)).ShouldBeTrue();
|
|
|
|
publisher.TryRebind(old, out var next).ShouldBeTrue();
|
|
publisher.TryPublish(old, new DataValueSnapshot(2, OpcUaStatus.Good, SourceTime, ServerTime)).ShouldBeFalse();
|
|
publisher.TryCapture(key, out var captured).ShouldBeTrue();
|
|
captured.ShouldBe(next);
|
|
hub.Commits.Count.ShouldBe(1);
|
|
|
|
publisher.TryPublish(next, new DataValueSnapshot(3, OpcUaStatus.Good, ServerTime, ServerTime)).ShouldBeTrue();
|
|
hub.Commits.Last().Sample.Value.GetScalar().ShouldBe(3);
|
|
}
|
|
|
|
[Fact]
|
|
public void Desired_artifact_tag_config_change_restarts_and_fences_old_producer()
|
|
{
|
|
var db = NewInMemoryDbFactory();
|
|
var tags = new[] { (Driver: "drv-1", DriverName: "Modbus", Device: "dev1", Tag: "speed", DataType: "Double", Writable: false) };
|
|
var refs = Array.Empty<(string, string, string, string, string?)>();
|
|
var beforeId = SeedV3Deployment(db, RevisionHash.Parse(new string('a', 64)), tags, refs, enabled: true,
|
|
tagConfigByTag: new Dictionary<string, string> { ["speed"] = "{\"address\":\"1\"}" });
|
|
var afterId = SeedV3Deployment(db, RevisionHash.Parse(new string('b', 64)), tags, refs, enabled: true,
|
|
tagConfigByTag: new Dictionary<string, string> { ["speed"] = "{\"address\":\"2\"}" });
|
|
using var context = db.CreateDbContext();
|
|
var before = DeploymentArtifact.ParseDriverInstances(context.Deployments.Single(x => x.DeploymentId == beforeId.Value).ArtifactBlob!).Single();
|
|
var after = DeploymentArtifact.ParseDriverInstances(context.Deployments.Single(x => x.DeploymentId == afterId.Value).ArtifactBlob!).Single();
|
|
before.DriverConfig.ShouldNotBe(after.DriverConfig);
|
|
var plan = DriverSpawnPlanner.Compute(new Dictionary<string, DriverChildSnapshot>
|
|
{
|
|
[before.DriverInstanceId] = new(before.DriverType, before.DriverConfig, before.ResilienceConfig)
|
|
}, new[] { after });
|
|
plan.ToStop.ShouldContain(before.DriverInstanceId);
|
|
plan.ToSpawn.Single().DriverInstanceId.ShouldBe(before.DriverInstanceId);
|
|
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
const string reference = "Plant/Modbus/dev1/speed";
|
|
publisher.RegisterDriverShape(before.DriverInstanceId, reference, SourceValueShape.FromDriverType("Double", false)).ShouldBeTrue();
|
|
var oldProducer = publisher.RegisterDriverIncarnation(before.DriverInstanceId);
|
|
publisher.EnsureDriverBinding("cluster-a", before.DriverInstanceId, reference, oldProducer).ShouldBeTrue();
|
|
publisher.TryCaptureDriver(before.DriverInstanceId, reference, oldProducer, out var ticket).ShouldBeTrue();
|
|
publisher.RetireDriver(before.DriverInstanceId, oldProducer);
|
|
var replacement = publisher.RegisterDriverIncarnation(after.DriverInstanceId);
|
|
publisher.EnsureDriverBinding("cluster-a", after.DriverInstanceId, reference, replacement).ShouldBeTrue();
|
|
publisher.TryCaptureDriver(before.DriverInstanceId, reference, oldProducer, out _).ShouldBeFalse();
|
|
publisher.TryPublish(ticket, new DataValueSnapshot(99, OpcUaStatus.Good, null, null)).ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Replacement_binds_before_subscribe_so_its_only_initial_callback_is_retained()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, () => new ServingIdentity("node-a", "instance-a", "Primary", 0, 0), "cluster-a");
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false));
|
|
var old = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
publisher.EnsureDriverBinding("cluster-a", "stub-driver-1", "source", old).ShouldBeTrue();
|
|
publisher.RetireDriver("stub-driver-1", old);
|
|
var replacement = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new InitialCallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: replacement), TestContext.Current.CancellationToken);
|
|
|
|
await Subscribe(actor, driver);
|
|
|
|
hub.Commits.Count.ShouldBe(1);
|
|
hub.Commits.Single().Sample.Value.GetScalar().ShouldBe(73);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", old, out _).ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Quiet_initial_batch_admits_every_source_beyond_preparation_slice()
|
|
{
|
|
const int count = 130;
|
|
using var hub = HubTest.Create(partitions: 1, bytes: 1_000_000, ingress: 256, dirty: 256, maxSources: 256);
|
|
var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a");
|
|
var references = Enumerable.Range(0, count).Select(i => $"source-{i:D3}").ToArray();
|
|
foreach (var reference in references)
|
|
publisher.RegisterDriverShape("stub-driver-1", reference, SourceValueShape.FromDriverType("Int32", false)).ShouldBeTrue();
|
|
var producer = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new QuietInitialBatchDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: producer), TestContext.Current.CancellationToken);
|
|
|
|
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
|
AwaitCondition(() => driver.InitializeCount > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
|
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
|
|
new DriverInstanceActor.Subscribe(references, TimeSpan.FromMilliseconds(100)),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
var legacy = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget,
|
|
cancellationToken: TestContext.Current.CancellationToken);
|
|
legacy.Items.Count.ShouldBe(count);
|
|
driver.SubscribeCount.ShouldBe(1);
|
|
hub.ProcessPending();
|
|
|
|
for (var i = 0; i < count; i++)
|
|
{
|
|
publisher.TryCaptureDriver("stub-driver-1", references[i], producer, out var ticket)
|
|
.ShouldBeTrue($"initial source {references[i]} was never admitted");
|
|
using var sample = hub.Read(ticket);
|
|
sample.Readiness.ShouldBe(DataReadiness.Ready, $"initial source {references[i]} has no retained acquisition");
|
|
sample.Sample!.Value.GetScalar().ShouldBe(i);
|
|
sample.Sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Initial_binding_contention_preserves_legacy_subscription_and_recovers_only_on_fresh_data()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false));
|
|
var producer = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var key = SourceKey.ForDriver("cluster-a", "stub-driver-1", "source", "node-a", "instance-a");
|
|
using var entered = new ManualResetEventSlim();
|
|
using var resume = new ManualResetEventSlim();
|
|
var cancellation = TestContext.Current.CancellationToken;
|
|
var blocker = Task.Run(() => actual.WithPartitionLockForTest(key, () => { entered.Set(); resume.Wait(cancellation); }), cancellation);
|
|
var driver = new InitialCallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: producer), TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
|
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
|
AwaitCondition(() => driver.InitializeCount > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
|
var reply = await actor.Ask<object>(new DriverInstanceActor.Subscribe(new[] { "source" }, TimeSpan.FromMilliseconds(100)),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
reply.ShouldBeOfType<DriverInstanceActor.SubscriptionEstablished>();
|
|
driver.SubscribeCount.ShouldBe(1);
|
|
var legacy = parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
legacy.Items.Single().Value.ShouldBe(73);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out _).ShouldBeFalse();
|
|
}
|
|
finally { resume.Set(); }
|
|
await blocker.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
|
|
AwaitCondition(() => publisher.TryCaptureDriver("stub-driver-1", "source", producer, out _),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
actor.Tell(new Identify("binding-ready"), TestActor);
|
|
ExpectMsg<ActorIdentity>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out var ticket).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
using (var initial = actual.Read(ticket)) initial.Sample.ShouldBeNull();
|
|
driver.Fire(91);
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
using var sample = actual.Read(ticket);
|
|
sample.Sample!.Value.GetScalar().ShouldBe(91);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Full_hub_keeps_legacy_callback_live_and_never_replays_its_dropped_value()
|
|
{
|
|
using var actual = HubTest.Create(partitions: 1, maxSources: 1);
|
|
var occupying = HubTest.Ticket("other", "tag");
|
|
HubTest.BindAndPublish(actual, occupying, 1, 5);
|
|
actual.ProcessPending();
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false));
|
|
var producer = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new InitialCallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: producer), TestContext.Current.CancellationToken);
|
|
|
|
await Subscribe(actor, driver);
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
|
.Items.Single().Value.ShouldBe(73);
|
|
driver.SubscribeCount.ShouldBe(1);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out _).ShouldBeFalse();
|
|
|
|
actual.TryRemove(occupying, 2).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
AwaitCondition(() => publisher.TryCaptureDriver("stub-driver-1", "source", producer, out _),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
actor.Tell(new Identify("binding-ready"), TestActor);
|
|
ExpectMsg<ActorIdentity>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out var ticket).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
using (var noReplay = actual.Read(ticket))
|
|
{
|
|
noReplay.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
noReplay.Sample.ShouldBeNull();
|
|
}
|
|
driver.SubscribeCount.ShouldBe(1, "recovery must not tear down the legacy subscription");
|
|
driver.Fire(91);
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
|
.Items.Single().Value.ShouldBe(91);
|
|
actual.ProcessPending();
|
|
using var fresh = actual.Read(ticket);
|
|
fresh.Sample!.Value.GetScalar().ShouldBe(91);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Missing_or_unsupported_source_shape_keeps_legacy_subscription_live(bool unsupported)
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
if (unsupported)
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("VendorOpaque", false));
|
|
var producer = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new InitialCallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: producer), TestContext.Current.CancellationToken);
|
|
|
|
await Subscribe(actor, driver);
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
|
.Items.Single().Value.ShouldBe(73);
|
|
driver.SubscribeCount.ShouldBe(1);
|
|
if (publisher.TryCaptureDriver("stub-driver-1", "source", producer, out var unavailableTicket))
|
|
{
|
|
actual.ProcessPending();
|
|
using var unavailable = actual.Read(unavailableTicket);
|
|
unavailable.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
unavailable.Sample.ShouldBeNull();
|
|
}
|
|
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false)).ShouldBeTrue();
|
|
AwaitCondition(() => publisher.TryCaptureDriver("stub-driver-1", "source", producer, out _),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
actor.Tell(new Identify("binding-ready"), TestActor);
|
|
ExpectMsg<ActorIdentity>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out var current).ShouldBeTrue();
|
|
using (var noReplay = actual.Read(current)) noReplay.Sample.ShouldBeNull();
|
|
driver.SubscribeCount.ShouldBe(1);
|
|
driver.Fire(91);
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
|
.Items.Single().Value.ShouldBe(91);
|
|
actual.ProcessPending();
|
|
using var fresh = actual.Read(current);
|
|
fresh.Sample!.Value.GetScalar().ShouldBe(91);
|
|
}
|
|
|
|
[Fact]
|
|
public void Comms_loss_is_a_status_only_transition_with_no_fabricated_acquisition_time()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "ref", "node-a", "instance-a");
|
|
var ticket = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
publisher.TryPublish(ticket, new DataValueSnapshot(42, OpcUaStatus.Good, SourceTime, ServerTime)).ShouldBeTrue();
|
|
|
|
publisher.TryPublishStatus(ticket, OpcUaStatus.BadNoCommunication, out var afterLoss).ShouldBeTrue();
|
|
|
|
var status = hub.Statuses.Single();
|
|
status.Ticket.ShouldBe(afterLoss);
|
|
status.Status.ShouldBe(OpcUaStatus.BadNoCommunication);
|
|
status.Source.ShouldBeNull();
|
|
status.Server.ShouldBeNull();
|
|
hub.Commits.Count.ShouldBe(1, "a status-only transition must not publish a fabricated null value");
|
|
publisher.TryCapture(key, out var captured).ShouldBeTrue();
|
|
captured.ShouldBe(afterLoss);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Status_fences_a_callback_in_flight_and_marks_the_gap_unavailable()
|
|
{
|
|
using var entered = new ManualResetEventSlim();
|
|
using var resume = new ManualResetEventSlim();
|
|
using var hub = new RecordingSourceHub { BeforeReservation = () => { entered.Set(); resume.Wait(); } };
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "ref", "node-a", "instance-a");
|
|
var ticket = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var pending = Task.Run(() => publisher.TryPublish(ticket, new DataValueSnapshot(new byte[] { 1 }, OpcUaStatus.Good, SourceTime, ServerTime)));
|
|
try
|
|
{
|
|
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
|
publisher.TryPublishStatus(ticket, OpcUaStatus.BadNoCommunication, out var afterLoss).ShouldBeTrue();
|
|
afterLoss.ShouldNotBe(ticket);
|
|
hub.Invalidated.ShouldContain(afterLoss);
|
|
}
|
|
finally { resume.Set(); }
|
|
(await pending).ShouldBeFalse();
|
|
hub.Commits.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Blocked_status_does_not_block_callback_and_invalidates_only_that_ticket()
|
|
{
|
|
using var entered = new ManualResetEventSlim();
|
|
using var resume = new ManualResetEventSlim();
|
|
using var hub = new RecordingSourceHub { BeforeStatus = () => { entered.Set(); resume.Wait(); } };
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForDriver("cluster-a", "driver", "ref", "node-a", "instance-a");
|
|
var otherKey = SourceKey.ForDriver("cluster-a", "driver", "other", "node-a", "instance-a");
|
|
var ticket = publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var other = publisher.Bind(otherKey, new SourceGeneration(1, 1));
|
|
var status = Task.Run(() => publisher.TryPublishStatus(ticket, OpcUaStatus.BadNoCommunication, out _));
|
|
try
|
|
{
|
|
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
|
var callback = Task.Run(() => publisher.TryPublish(ticket, new DataValueSnapshot(1, OpcUaStatus.Good, null, null)));
|
|
(await callback.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeFalse();
|
|
hub.Invalidated.ShouldContain(ticket);
|
|
hub.Invalidated.ShouldNotContain(other);
|
|
// An unrelated source has its own serialization boundary.
|
|
publisher.TryPublish(other, new DataValueSnapshot(2, OpcUaStatus.Good, null, null)).ShouldBeTrue();
|
|
}
|
|
finally { resume.Set(); }
|
|
(await status).ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void Repartition_rebinds_current_source_before_a_fresh_acquisition()
|
|
{
|
|
using var hub = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("Int32", false));
|
|
var producer = publisher.RegisterDriverIncarnation("driver");
|
|
publisher.EnsureDriverBinding("cluster-a", "driver", "ref", producer).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var old).ShouldBeTrue();
|
|
publisher.TryPublish(old, new DataValueSnapshot(1, OpcUaStatus.Good, SourceTime, null)).ShouldBeTrue();
|
|
hub.ProcessPending();
|
|
hub.Repartition(3);
|
|
|
|
publisher.TryPublish(old, new DataValueSnapshot(2, OpcUaStatus.Good, ServerTime, null)).ShouldBeFalse();
|
|
AwaitCondition(() => publisher.TryCaptureDriver("driver", "ref", producer, out var current) &&
|
|
current != old && hub.IsTicketCurrentNonBlocking(current), PresenceBudget, TestContext.Current.CancellationToken);
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var rebound).ShouldBeTrue();
|
|
publisher.TryPublish(rebound, new DataValueSnapshot(3, OpcUaStatus.Good, ServerTime, null)).ShouldBeTrue();
|
|
hub.ProcessPending();
|
|
using var read = hub.Read(rebound);
|
|
read.Sample!.Value.GetScalar().ShouldBe(3);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("Byte", true, DataValueKind.Array)]
|
|
[InlineData("ByteString", false, DataValueKind.Bytes)]
|
|
public void Declared_source_shape_distinguishes_uint8_array_from_byte_string(string type, bool isArray, DataValueKind expected)
|
|
{
|
|
using var hub = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType(type, isArray));
|
|
var producer = publisher.RegisterDriverIncarnation("driver");
|
|
publisher.EnsureDriverBinding("cluster-a", "driver", "ref", producer).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var ticket).ShouldBeTrue();
|
|
var bytes = new byte[] { 1, 2, 3 };
|
|
publisher.TryPublish(ticket, new DataValueSnapshot(bytes, OpcUaStatus.Good, SourceTime, null)).ShouldBeTrue();
|
|
Array.Fill(bytes, (byte)99);
|
|
hub.ProcessPending();
|
|
using var read = hub.Read(ticket);
|
|
var value = read.Sample!.Value;
|
|
value.Kind.ShouldBe(expected);
|
|
if (isArray)
|
|
{
|
|
value.ArrayElementKind.ShouldBe(DataValueKind.UInt8);
|
|
value.GetArray().Cast<byte>().ShouldBe(new byte[] { 1, 2, 3 });
|
|
value.Dimensions.ShouldBe(new[] { 3 });
|
|
}
|
|
else value.GetBytes().ToArray().ShouldBe(new byte[] { 1, 2, 3 });
|
|
}
|
|
|
|
[Fact]
|
|
public void Declared_shape_change_rebinds_the_source_and_rejects_its_old_ticket()
|
|
{
|
|
using var hub = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("ByteString", false)).ShouldBeTrue();
|
|
var producer = publisher.RegisterDriverIncarnation("driver");
|
|
publisher.EnsureDriverBinding("cluster-a", "driver", "ref", producer).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var old).ShouldBeTrue();
|
|
publisher.TryPublish(old, new DataValueSnapshot(new byte[] { 1 }, OpcUaStatus.Good, SourceTime, null)).ShouldBeTrue();
|
|
hub.ProcessPending();
|
|
|
|
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("Byte", true)).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var current).ShouldBeTrue();
|
|
current.ShouldNotBe(old);
|
|
publisher.TryPublish(old, new DataValueSnapshot(new byte[] { 2 }, OpcUaStatus.Good, ServerTime, null)).ShouldBeFalse();
|
|
publisher.TryPublish(current, new DataValueSnapshot(new byte[] { 3 }, OpcUaStatus.Good, ServerTime, null)).ShouldBeTrue();
|
|
hub.ProcessPending();
|
|
using var sample = hub.Read(current);
|
|
sample.Sample!.Value.Kind.ShouldBe(DataValueKind.Array);
|
|
sample.Sample.Value.ArrayElementKind.ShouldBe(DataValueKind.UInt8);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Producer_retirement_fences_reads_before_the_tombstone_walk_completes()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
using var entered = new ManualResetEventSlim();
|
|
using var resume = new ManualResetEventSlim();
|
|
var hub = new BlockingRemovalHub(actual, () => { entered.Set(); resume.Wait(); });
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
publisher.RegisterDriverShape("driver", "ref", SourceValueShape.FromDriverType("Int32", false));
|
|
var producer = publisher.RegisterDriverIncarnation("driver");
|
|
publisher.EnsureDriverBinding("cluster-a", "driver", "ref", producer).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out var ticket).ShouldBeTrue();
|
|
publisher.TryPublish(ticket, new DataValueSnapshot(1, OpcUaStatus.Good, SourceTime, null)).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
var retired = Task.Run(() => publisher.RetireDriver("driver", producer), TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
entered.Wait(PresenceBudget, TestContext.Current.CancellationToken).ShouldBeTrue();
|
|
publisher.TryCaptureDriver("driver", "ref", producer, out _).ShouldBeFalse();
|
|
var callback = Task.Run(() => publisher.TryPublish(ticket, new DataValueSnapshot(2, OpcUaStatus.Good, null, null)));
|
|
(await callback.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken)).ShouldBeFalse();
|
|
using var read = actual.Read(ticket);
|
|
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
}
|
|
finally { resume.Set(); }
|
|
await retired.WaitAsync(PresenceBudget, TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
[Fact]
|
|
public void Equal_fresh_virtual_evaluation_recovers_invalidated_hub_without_sdk_duplicate()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var hub = new ObservingHub(actual);
|
|
var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a");
|
|
var incarnation = publisher.RegisterVirtualIncarnation("vt-1");
|
|
publisher.EnsureVirtualBinding("vt-1", incarnation).ShouldBeTrue();
|
|
publisher.TryCaptureVirtual("vt-1", incarnation, out var ticket).ShouldBeTrue();
|
|
var parent = CreateTestProbe();
|
|
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", new SwitchingEvaluator(),
|
|
sourcePublisher: publisher, sourceIncarnation: incarnation), TestContext.Current.CancellationToken);
|
|
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, SourceTime));
|
|
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
actual.Invalidate(ticket, "test gap");
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 2, ServerTime));
|
|
AwaitCondition(() => Volatile.Read(ref hub.CommitCount) == 2, PresenceBudget, TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
using var read = actual.Read(ticket);
|
|
read.Readiness.ShouldBe(DataReadiness.Ready);
|
|
read.Sample!.Value.GetScalar().ShouldBe(42);
|
|
read.Sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(ServerTime));
|
|
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(150), TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public void Virtual_failure_changes_quality_without_creating_or_freshening_acquisition(bool initialFailure)
|
|
{
|
|
var clock = new ManualTimeProvider();
|
|
using var actual = HubTest.Create(clock: clock);
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
var incarnation = publisher.RegisterVirtualIncarnation("vt-1");
|
|
publisher.EnsureVirtualBinding("vt-1", incarnation).ShouldBeTrue();
|
|
publisher.TryCaptureVirtual("vt-1", incarnation, out var ticket).ShouldBeTrue();
|
|
var evaluator = new SwitchingEvaluator { Fail = initialFailure };
|
|
var parent = CreateTestProbe();
|
|
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator,
|
|
sourcePublisher: publisher, sourceIncarnation: incarnation), TestContext.Current.CancellationToken);
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, SourceTime));
|
|
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
if (initialFailure)
|
|
{
|
|
using var waiting = actual.Read(ticket);
|
|
waiting.Sample.ShouldBeNull();
|
|
waiting.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
return;
|
|
}
|
|
|
|
using var before = actual.Read(ticket);
|
|
var received = before.ReceivedTimestamp;
|
|
clock.Advance(TimeSpan.FromMinutes(1));
|
|
evaluator.Fail = true;
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 2, ServerTime));
|
|
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
using var bad = actual.Read(ticket);
|
|
bad.Sample!.Value.GetScalar().ShouldBe(42);
|
|
bad.Sample.StatusCode.ShouldBe(OpcUaStatus.BadInternalError);
|
|
bad.Sample.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
bad.Sample.ServerTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
bad.ReceivedTimestamp.ShouldBe(received);
|
|
}
|
|
|
|
[Fact]
|
|
public void Stopped_virtual_actor_retires_the_cached_producer()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
var incarnation = publisher.RegisterVirtualIncarnation("vt-1");
|
|
publisher.EnsureVirtualBinding("vt-1", incarnation).ShouldBeTrue();
|
|
publisher.TryCaptureVirtual("vt-1", incarnation, out var ticket).ShouldBeTrue();
|
|
var parent = CreateTestProbe();
|
|
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", new SwitchingEvaluator(),
|
|
sourcePublisher: publisher, sourceIncarnation: incarnation), TestContext.Current.CancellationToken);
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, SourceTime));
|
|
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
Watch(actor);
|
|
Sys.Stop(actor);
|
|
ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
using var read = actual.Read(ticket);
|
|
read.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
publisher.TryCaptureVirtual("vt-1", incarnation, out _).ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public void Stopped_virtual_actors_release_source_quota_and_stale_retirement_cannot_close_replacement()
|
|
{
|
|
using var actual = HubTest.Create(partitions: 1, maxSources: 1);
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
for (var i = 0; i < 4; i++)
|
|
{
|
|
var id = $"vt-{i}";
|
|
var incarnation = publisher.RegisterVirtualIncarnation(id);
|
|
publisher.EnsureVirtualBinding(id, incarnation).ShouldBeTrue();
|
|
publisher.TryCaptureVirtual(id, incarnation, out var ticket).ShouldBeTrue();
|
|
var parent = CreateTestProbe();
|
|
var actor = parent.ChildActorOf(VirtualTagActor.Props(id, "expr", new SwitchingEvaluator(),
|
|
sourcePublisher: publisher, sourceIncarnation: incarnation), TestContext.Current.CancellationToken);
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, SourceTime));
|
|
parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
var beforeStop = actual.Resources.RetainedBytes;
|
|
Watch(actor);
|
|
Sys.Stop(actor);
|
|
ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
publisher.TryCaptureVirtual(id, incarnation, out _).ShouldBeFalse();
|
|
actual.Resources.RetainedBytes.ShouldBeLessThan(beforeStop);
|
|
}
|
|
|
|
var old = publisher.RegisterVirtualIncarnation("same-id");
|
|
publisher.EnsureVirtualBinding("same-id", old).ShouldBeTrue();
|
|
publisher.RetireVirtualIncarnation("same-id", old);
|
|
actual.ProcessPending();
|
|
var replacement = publisher.RegisterVirtualIncarnation("same-id");
|
|
publisher.EnsureVirtualBinding("same-id", replacement).ShouldBeTrue();
|
|
publisher.TryCaptureVirtual("same-id", replacement, out var current).ShouldBeTrue();
|
|
publisher.TryPublish(current, new DataValueSnapshot(7, OpcUaStatus.Good, SourceTime, null)).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
publisher.RetireVirtualIncarnation("same-id", old);
|
|
using var read = actual.Read(current);
|
|
read.Readiness.ShouldBe(DataReadiness.Ready);
|
|
read.Sample!.Value.GetScalar().ShouldBe(7);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Supervised_driver_restart_retires_old_callback_and_installs_new_producer()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var publisher = new SourceSamplePublisher(actual, () => Serving, "cluster-a");
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false));
|
|
var oldToken = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new CallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: oldToken), new OneForOneStrategy(_ => Directive.Restart),
|
|
TestContext.Current.CancellationToken);
|
|
await Subscribe(actor, driver);
|
|
var oldCallback = driver.Capture();
|
|
driver.Fire(new DataValueSnapshot(11, OpcUaStatus.Good, SourceTime, null));
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", oldToken, out var oldTicket).ShouldBeTrue();
|
|
|
|
actor.Tell(Kill.Instance);
|
|
parent.ExpectMsg<DriverInstanceActor.ReprovisionRequested>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
oldCallback(new DataValueSnapshot(99, OpcUaStatus.Good, ServerTime, null));
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", oldToken, out _).ShouldBeFalse();
|
|
using (var retired = actual.Read(oldTicket)) retired.Readiness.ShouldNotBe(DataReadiness.Ready);
|
|
|
|
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
|
AwaitCondition(() => driver.InitializeCount > 1, PresenceBudget, TestContext.Current.CancellationToken);
|
|
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
|
|
new DriverInstanceActor.Subscribe(new[] { "source" }, TimeSpan.FromMilliseconds(100)),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
var key = SourceKey.ForDriver("cluster-a", "stub-driver-1", "source", "node-a", "instance-a");
|
|
publisher.TryCapture(key, out var current).ShouldBeTrue();
|
|
current.Generation.Incarnation.ShouldNotBe(oldToken);
|
|
driver.Fire(new DataValueSnapshot(12, OpcUaStatus.Good, ServerTime, null));
|
|
parent.ExpectMsg<DriverInstanceActor.AttributeValueBatchPublished>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
actual.ProcessPending();
|
|
using var read = actual.Read(current);
|
|
read.Sample!.Value.GetScalar().ShouldBe(12);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Malformed_callback_invalidates_source_and_faults_on_actor_instead_of_driver_thread()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
publisher.RegisterDriverShape("stub-driver-1", "source", SourceValueShape.FromDriverType("Int32", false));
|
|
var producer = publisher.RegisterDriverIncarnation("stub-driver-1");
|
|
var driver = new CallbackDriver();
|
|
var parent = CreateTestProbe();
|
|
parent.IgnoreMessages(m => m is DriverInstanceActor.ConnectivityChanged);
|
|
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver, clusterId: "cluster-a",
|
|
sourcePublisher: publisher, sourceIncarnation: producer), new OneForOneStrategy(_ => Directive.Restart),
|
|
TestContext.Current.CancellationToken);
|
|
await Subscribe(actor, driver);
|
|
publisher.TryCaptureDriver("stub-driver-1", "source", producer, out var ticket).ShouldBeTrue();
|
|
|
|
Should.NotThrow(() => driver.Fire(null!));
|
|
|
|
hub.Invalidated.ShouldContain(ticket);
|
|
parent.ExpectMsg<DriverInstanceActor.ReprovisionRequested>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
[Fact]
|
|
public void Supervised_virtual_restart_drops_old_async_evaluation_while_new_one_runs()
|
|
{
|
|
using var actual = HubTest.Create();
|
|
var hub = new ObservingHub(actual);
|
|
var publisher = new SourceSamplePublisher(hub, () => Serving, "cluster-a");
|
|
var oldToken = publisher.RegisterVirtualIncarnation("vt-1");
|
|
publisher.EnsureVirtualBinding("vt-1", oldToken).ShouldBeTrue();
|
|
var evaluator = new PendingEvaluator();
|
|
var parent = CreateTestProbe();
|
|
var actor = parent.ChildActorOf(VirtualTagActor.Props("vt-1", "expr", evaluator,
|
|
sourcePublisher: publisher, sourceIncarnation: oldToken), new OneForOneStrategy(_ => Directive.Restart),
|
|
TestContext.Current.CancellationToken);
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 1, SourceTime));
|
|
AwaitCondition(() => evaluator.Calls.Count == 1, PresenceBudget, TestContext.Current.CancellationToken);
|
|
actor.Tell(Kill.Instance);
|
|
AwaitCondition(() => !publisher.IsVirtualIncarnationActive("vt-1", oldToken), PresenceBudget, TestContext.Current.CancellationToken);
|
|
AwaitCondition(() => publisher.TryCaptureVirtual("vt-1", out var current) && current.Generation.Incarnation != oldToken,
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
actor.Tell(new VirtualTagActor.DependencyValueChanged("a", 2, ServerTime));
|
|
AwaitCondition(() => evaluator.Calls.Count == 2, PresenceBudget, TestContext.Current.CancellationToken);
|
|
evaluator.Calls[0].SetResult(VirtualTagEvalResult.Ok(99));
|
|
evaluator.Calls[1].SetResult(VirtualTagEvalResult.Ok(42));
|
|
var result = parent.ExpectMsg<VirtualTagActor.EvaluationResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
result.Value.ShouldBe(42);
|
|
Volatile.Read(ref hub.CommitCount).ShouldBe(1);
|
|
publisher.TryCaptureVirtual("vt-1", out var ticket).ShouldBeTrue();
|
|
actual.ProcessPending();
|
|
using var read = actual.Read(ticket);
|
|
read.Sample!.Value.GetScalar().ShouldBe(42);
|
|
}
|
|
|
|
[Fact]
|
|
public void Virtual_reassert_repairs_the_sdk_without_a_new_authoritative_sample()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForVirtual("cluster-a", "vt-1", "node-a", "instance-a");
|
|
publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var sink = CreateTestProbe();
|
|
var host = Sys.ActorOf(VirtualTagHostActor.Props(sink.Ref, null, NullVirtualTagEvaluator.Instance, sourcePublisher: publisher));
|
|
var plan = new EquipmentVirtualTagPlan("vt-1", "eq-1", "", "computed", "Double", "1", Array.Empty<string>());
|
|
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { plan }));
|
|
host.Tell(new VirtualTagActor.EvaluationResult("vt-1", 42d, SourceTime, CorrelationId.NewId()));
|
|
sink.ExpectMsg<OpcUaPublishActor.AttributeValueUpdate>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
hub.Commits.Count.ShouldBe(1);
|
|
var original = hub.Commits.Single().Sample;
|
|
|
|
host.Tell(new VirtualTagActor.EvaluationResult("vt-1", 42d, ServerTime, CorrelationId.NewId(), IsReassert: true));
|
|
sink.ExpectMsg<OpcUaPublishActor.AttributeValueUpdate>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
|
|
hub.Commits.Count.ShouldBe(1);
|
|
original.SourceTimestampUtc.ShouldBe(new DateTimeOffset(SourceTime));
|
|
}
|
|
|
|
[Fact]
|
|
public void Disabled_virtual_source_reaches_hub_when_no_sdk_sink_exists()
|
|
{
|
|
using var hub = new RecordingSourceHub();
|
|
var publisher = new SourceSamplePublisher(hub, Serving);
|
|
var key = SourceKey.ForVirtual("cluster-a", "vt-1", "node-a", "instance-a");
|
|
publisher.Bind(key, new SourceGeneration(1, 1));
|
|
var mux = CreateTestProbe();
|
|
var host = Sys.ActorOf(VirtualTagHostActor.Props(null, mux.Ref, NullVirtualTagEvaluator.Instance, sourcePublisher: publisher));
|
|
var plan = new EquipmentVirtualTagPlan("vt-1", "eq-1", "", "computed", "Double", "1", Array.Empty<string>()) with { Enabled = false };
|
|
|
|
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { plan }));
|
|
mux.ExpectMsg<DependencyMuxActor.VirtualTagOutput>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
|
AwaitCondition(() => hub.Commits.Count + hub.Statuses.Count > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
|
var status = hub.Commits.Count > 0 ? hub.Commits.Single().Sample.StatusCode : hub.Statuses.Single().Status;
|
|
status.ShouldBe(OpcUaStatus.BadOutOfService);
|
|
}
|
|
|
|
private async Task Subscribe(IActorRef actor, StubDriver driver)
|
|
{
|
|
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
|
|
AwaitCondition(() => driver.InitializeCount > 0, PresenceBudget, TestContext.Current.CancellationToken);
|
|
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
|
|
new DriverInstanceActor.Subscribe(new[] { "source" }, TimeSpan.FromMilliseconds(100)),
|
|
PresenceBudget, TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
private sealed class CallbackDriver : StubDriver, ISubscribable
|
|
{
|
|
private readonly StubHandle _handle = new();
|
|
public event EventHandler<DataChangeEventArgs>? OnDataChange;
|
|
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct) => Task.FromResult<ISubscriptionHandle>(_handle);
|
|
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
|
public void Fire(DataValueSnapshot snapshot) => OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, "source", snapshot));
|
|
public Action<DataValueSnapshot> Capture()
|
|
{
|
|
var callback = OnDataChange;
|
|
return snapshot => callback?.Invoke(this, new DataChangeEventArgs(_handle, "source", snapshot));
|
|
}
|
|
}
|
|
|
|
private sealed class InitialCallbackDriver : StubDriver, ISubscribable
|
|
{
|
|
private readonly StubHandle _handle = new();
|
|
public int SubscribeCount;
|
|
public event EventHandler<DataChangeEventArgs>? OnDataChange;
|
|
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
|
|
{
|
|
Interlocked.Increment(ref SubscribeCount);
|
|
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, "source", new DataValueSnapshot(73, OpcUaStatus.Good, SourceTime, null)));
|
|
return Task.FromResult<ISubscriptionHandle>(_handle);
|
|
}
|
|
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
|
public void Fire(int value) => OnDataChange?.Invoke(this,
|
|
new DataChangeEventArgs(_handle, "source", new DataValueSnapshot(value, OpcUaStatus.Good, ServerTime, null)));
|
|
}
|
|
|
|
private sealed class QuietInitialBatchDriver : StubDriver, IBatchSubscribable
|
|
{
|
|
private readonly StubHandle _handle = new();
|
|
public int SubscribeCount;
|
|
public event EventHandler<DataChangeEventArgs>? OnDataChange { add { } remove { } }
|
|
public event EventHandler<DataChangeBatchEventArgs>? OnDataChangeBatch;
|
|
public Task<ISubscriptionHandle> SubscribeAsync(IReadOnlyList<string> refs, TimeSpan interval, CancellationToken ct)
|
|
{
|
|
Interlocked.Increment(ref SubscribeCount);
|
|
var items = refs.Select((reference, index) =>
|
|
new DataChangeItem(reference, new DataValueSnapshot(index, OpcUaStatus.Good, SourceTime, null))).ToArray();
|
|
OnDataChangeBatch?.Invoke(this, new DataChangeBatchEventArgs(_handle, items));
|
|
return Task.FromResult<ISubscriptionHandle>(_handle);
|
|
}
|
|
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken ct) => Task.CompletedTask;
|
|
}
|
|
|
|
private sealed class SwitchingEvaluator : IVirtualTagEvaluator
|
|
{
|
|
public volatile bool Fail;
|
|
public VirtualTagEvalResult Evaluate(string id, string expression, IReadOnlyDictionary<string, object?> dependencies) =>
|
|
Fail ? VirtualTagEvalResult.Failure("test failure") : VirtualTagEvalResult.Ok(42);
|
|
}
|
|
private sealed class PendingEvaluator : IVirtualTagEvaluator
|
|
{
|
|
public System.Collections.Concurrent.ConcurrentDictionary<int, TaskCompletionSource<VirtualTagEvalResult>> Calls { get; } = new();
|
|
private int _index;
|
|
public VirtualTagEvalResult Evaluate(string id, string expression, IReadOnlyDictionary<string, object?> dependencies) => throw new NotSupportedException();
|
|
public Task<VirtualTagEvalResult> EvaluateAsync(string id, string expression, IReadOnlyDictionary<string, DataValueSnapshot> dependencies)
|
|
{
|
|
var completion = new TaskCompletionSource<VirtualTagEvalResult>();
|
|
Calls[Interlocked.Increment(ref _index) - 1] = completion;
|
|
return completion.Task;
|
|
}
|
|
}
|
|
|
|
private sealed class RecordingSourceHub : ISourceSampleHub, IDisposable
|
|
{
|
|
private readonly Dictionary<BackingSourceKey, SourceTicket> _current = new();
|
|
public List<(SourceTicket Ticket, DataSample Sample, long Sequence)> Commits { get; } = new();
|
|
public List<SourceTicket> Invalidated { get; } = new();
|
|
public List<(SourceTicket Ticket, long Sequence, uint Status, DateTimeOffset? Source, DateTimeOffset? Server)> Statuses { get; } = new();
|
|
public int Reservations { get; private set; }
|
|
public bool RejectReservations { get; set; }
|
|
public Action? BeforeReservation { get; set; }
|
|
public Action? BeforeStatus { get; set; }
|
|
|
|
public bool TryBind(SourceTicket ticket) { _current[ticket.Key] = ticket; return true; }
|
|
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => TryBind(ticket);
|
|
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) => _current.TryGetValue(key, out ticket);
|
|
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => _current.TryGetValue(ticket.Key, out var current) && current == ticket;
|
|
public void InvalidatePartitionFor(BackingSourceKey key, string reason) { }
|
|
public bool TryReserveIngress(SourceTicket ticket, long estimatedRetainedBytes, out IIngressReservation? reservation)
|
|
{
|
|
Reservations++;
|
|
BeforeReservation?.Invoke();
|
|
reservation = RejectReservations ? null : new Reservation(this, ticket);
|
|
return reservation is not null;
|
|
}
|
|
public void Invalidate(SourceTicket ticket, string reason)
|
|
{
|
|
if (_current.TryGetValue(ticket.Key, out var current) && current == ticket) Invalidated.Add(ticket);
|
|
}
|
|
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint statusCode, DateTimeOffset? sourceTimestampUtc, DateTimeOffset? serverTimestampUtc)
|
|
{
|
|
BeforeStatus?.Invoke();
|
|
Statuses.Add((ticket, sequence, statusCode, sourceTimestampUtc, serverTimestampUtc));
|
|
return true;
|
|
}
|
|
public bool TryRemove(SourceTicket ticket, long sequence) { _current.Remove(ticket.Key); return true; }
|
|
public void Dispose() { foreach (var (_, sample, _) in Commits) sample.Dispose(); }
|
|
|
|
private sealed class Reservation(RecordingSourceHub hub, SourceTicket ticket) : IIngressReservation
|
|
{
|
|
public bool TryCommit(DataSample sample, long sequence)
|
|
{
|
|
if (!hub._current.TryGetValue(ticket.Key, out var current) || current != ticket) return false;
|
|
hub.Commits.Add((ticket, sample, sequence));
|
|
return true;
|
|
}
|
|
public void Dispose() { }
|
|
}
|
|
}
|
|
|
|
private sealed class BlockingRemovalHub(PartitionedSampleHub inner, Action beforeRemove) : ISourceSampleHub
|
|
{
|
|
public bool TryBind(SourceTicket ticket) => inner.TryBind(ticket);
|
|
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => inner.TryBind(ticket, fence);
|
|
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) => inner.TryGetCurrentTicket(key, out ticket);
|
|
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => inner.IsTicketCurrentNonBlocking(ticket);
|
|
public void InvalidatePartitionFor(BackingSourceKey key, string reason) => inner.InvalidatePartitionFor(key, reason);
|
|
public bool TryReserveIngress(SourceTicket ticket, long bytes, out IIngressReservation? reservation) => inner.TryReserveIngress(ticket, bytes, out reservation);
|
|
public void Invalidate(SourceTicket ticket, string reason) => inner.Invalidate(ticket, reason);
|
|
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server) => inner.TryPublishStatus(ticket, sequence, status, source, server);
|
|
public bool TryRemove(SourceTicket ticket, long sequence) { beforeRemove(); return inner.TryRemove(ticket, sequence); }
|
|
}
|
|
|
|
private sealed class ObservingHub(PartitionedSampleHub inner) : ISourceSampleHub
|
|
{
|
|
public int CommitCount;
|
|
public bool TryBind(SourceTicket ticket) => inner.TryBind(ticket);
|
|
public bool TryBind(SourceTicket ticket, ProducerFence? fence) => inner.TryBind(ticket, fence);
|
|
public bool TryGetCurrentTicket(BackingSourceKey key, out SourceTicket ticket) => inner.TryGetCurrentTicket(key, out ticket);
|
|
public bool IsTicketCurrentNonBlocking(SourceTicket ticket) => inner.IsTicketCurrentNonBlocking(ticket);
|
|
public void InvalidatePartitionFor(BackingSourceKey key, string reason) => inner.InvalidatePartitionFor(key, reason);
|
|
public bool TryReserveIngress(SourceTicket ticket, long bytes, out IIngressReservation? reservation)
|
|
{
|
|
if (!inner.TryReserveIngress(ticket, bytes, out var innerReservation) || innerReservation is null)
|
|
{ reservation = null; return false; }
|
|
reservation = new ObservingReservation(this, innerReservation);
|
|
return true;
|
|
}
|
|
public void Invalidate(SourceTicket ticket, string reason) => inner.Invalidate(ticket, reason);
|
|
public bool TryPublishStatus(SourceTicket ticket, long sequence, uint status, DateTimeOffset? source, DateTimeOffset? server) => inner.TryPublishStatus(ticket, sequence, status, source, server);
|
|
public bool TryRemove(SourceTicket ticket, long sequence) => inner.TryRemove(ticket, sequence);
|
|
private sealed class ObservingReservation(ObservingHub hub, IIngressReservation inner) : IIngressReservation
|
|
{
|
|
public bool TryCommit(DataSample sample, long sequence)
|
|
{ var result = inner.TryCommit(sample, sequence); if (result) Interlocked.Increment(ref hub.CommitCount); return result; }
|
|
public void Dispose() => inner.Dispose();
|
|
}
|
|
}
|
|
}
|