644 lines
44 KiB
C#
644 lines
44 KiB
C#
using System.Threading.Channels;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
|
{
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Failed_first_sdk_item_construction_removes_new_fanout_and_component_reference()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock; origin.Publish(7);
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Both,
|
|
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value }], ct);
|
|
await NextPublished(published.Reader, x => Equals(x.Snapshot.Value, 7), ct);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var samples = (System.Collections.IDictionary)manager.GetType().GetField("_projectedSamples", flags)!.GetValue(manager)!;
|
|
var original = (ProjectedValueWrite)samples[anchor].ShouldNotBeNull();
|
|
var count = manager.GetType().GetProperty("MonitoredNodeCount", flags).ShouldNotBeNull();
|
|
var beforeNodes = (int)count.GetValue(manager)!;
|
|
var cacheField = typeof(Opc.Ua.Server.CustomNodeManager2).GetField("m_componentCache", flags).ShouldNotBeNull();
|
|
int References()
|
|
{
|
|
if (cacheField.GetValue(manager) is not System.Collections.IDictionary cache || !cache.Contains(anchor)) return 0;
|
|
var entry = cache[anchor].ShouldNotBeNull();
|
|
return (int)entry.GetType().GetField("RefCount")!.GetValue(entry)!;
|
|
}
|
|
var beforeReferences = References();
|
|
samples[anchor] = original with { Proof = new ThrowingSourceProof(original.Proof) };
|
|
try
|
|
{
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
var result = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct);
|
|
StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue("the injected check must fail after creating the first fanout");
|
|
}
|
|
catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); }
|
|
finally { samples[anchor] = original; }
|
|
((int)count.GetValue(manager)!).ShouldBe(beforeNodes, "failed first construction cannot retain an empty monitored node");
|
|
References().ShouldBe(beforeReferences, "failed first construction must return its component-cache reference");
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Failed_sdk_item_construction_releases_candidate_and_fanout_ownership()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var samples = (System.Collections.IDictionary)manager.GetType().GetField("_projectedSamples", flags)!.GetValue(manager)!;
|
|
var original = (ProjectedValueWrite)samples[anchor].ShouldNotBeNull();
|
|
var budget = manager.GetType().GetField("_projectedCandidateBudget", flags)!.GetValue(manager)!;
|
|
var entries = budget.GetType().GetProperty("RetainedEntries").ShouldNotBeNull();
|
|
var before = (int)entries.GetValue(budget)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var existing = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var handle = (Opc.Ua.Server.NodeHandle)existing.ManagerHandle;
|
|
var node = handle.MonitoredNode;
|
|
var fanoutBefore = node.DataChangeMonitoredItems.Count;
|
|
var componentCache = (System.Collections.IDictionary)typeof(Opc.Ua.Server.CustomNodeManager2)
|
|
.GetField("m_componentCache", flags)!.GetValue(manager)!;
|
|
var cacheKey = string.IsNullOrEmpty(handle.ComponentPath) ? handle.NodeId : handle.RootId;
|
|
var cacheEntry = componentCache[cacheKey].ShouldNotBeNull();
|
|
var references = cacheEntry.GetType().GetField("RefCount").ShouldNotBeNull();
|
|
var referencesBefore = (int)references.GetValue(cacheEntry)!;
|
|
samples[anchor] = original with { Proof = new ThrowingSourceProof(original.Proof) };
|
|
try
|
|
{
|
|
var result = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 2, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct);
|
|
StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue("the injected source check must fail after the item is constructed");
|
|
}
|
|
catch (ServiceResultException error) { StatusCode.IsBad(error.StatusCode).ShouldBeTrue(); }
|
|
finally { samples[anchor] = original; }
|
|
((int)entries.GetValue(budget)!).ShouldBe(before, "failed construction cannot retain the initial sample candidate charge");
|
|
node.DataChangeMonitoredItems.Count.ShouldBe(fanoutBefore, "failed construction cannot remain registered in node fanout");
|
|
((int)references.GetValue(cacheEntry)!).ShouldBe(referencesBefore, "failed construction must return its component-cache reference");
|
|
});
|
|
}
|
|
|
|
private sealed class ThrowingSourceProof(IProjectedSamplePublicationProof inner) : IProjectedSamplePublicationProof
|
|
{
|
|
public bool IsValid => inner.IsValid;
|
|
public object SourceIdentity => inner.SourceIdentity;
|
|
public bool IsSourceValid => throw new IOException("test source validity failure");
|
|
public TimeProvider Clock => inner.Clock;
|
|
public void Invalidate() => inner.Invalidate();
|
|
}
|
|
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task Disabled_sdk_item_does_not_keep_a_ghost_loss_control(bool disableBeforeLoss)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 1, DiscardOldest = true } }], ct);
|
|
created.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
var itemId = created.Results[0].MonitoredItemId;
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull();
|
|
async Task SetMode(MonitoringMode mode)
|
|
{
|
|
var changed = await client.SetMonitoringModeAsync(new RequestHeader(), sub, mode, [itemId], ct);
|
|
changed.Results[0].ShouldBe(StatusCodes.Good);
|
|
}
|
|
if (disableBeforeLoss) await SetMode(MonitoringMode.Disabled);
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
if (!disableBeforeLoss)
|
|
{
|
|
queuedLoss.GetValue(item).ShouldNotBeNull("the loss must first be queued while reporting");
|
|
await SetMode(MonitoringMode.Disabled);
|
|
}
|
|
queuedLoss.GetValue(item).ShouldBeNull("disabled items cannot retain a control the SDK silently dropped");
|
|
await SetMode(MonitoringMode.Reporting);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var unavailable = await PublishComposedValue(client, 1, ct);
|
|
StatusCode.IsGood(unavailable.StatusCode).ShouldBeFalse();
|
|
unavailable.WrappedValue.IsNull.ShouldBeTrue();
|
|
});
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Theory(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task Retiring_an_sdk_item_removes_its_health_entry_before_timer_or_demand_reuse(bool directDispose)
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var health = (System.Collections.IDictionary)manager.GetType().GetField("_projectedHealthIndex", flags)!.GetValue(manager)!;
|
|
health.Count.ShouldBe(1);
|
|
var demandField = item.GetType().GetField("_demand", flags).ShouldNotBeNull();
|
|
var originalDemand = (IProjectedDemandLease)demandField.GetValue(item).ShouldNotBeNull();
|
|
var slotsAtDisposal = -1;
|
|
demandField.SetValue(item, new ObserveDemandDisposal(originalDemand, () => slotsAtDisposal = health.Count));
|
|
var before = origin.Clock.GetTimestamp();
|
|
if (directDispose) ((IDisposable)item).Dispose();
|
|
else item.GetType().GetMethod("Retire", flags).ShouldNotBeNull().Invoke(item, null);
|
|
origin.Clock.GetTimestamp().ShouldBe(before, "unregistration cannot wait for a health timer sweep");
|
|
slotsAtDisposal.ShouldBe(0, "the health slot must be released before its demand capacity can be reused");
|
|
health.Count.ShouldBe(0, "retirement must release the bounded health slot before the demand can be reused");
|
|
var stillLive = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
stillLive.Cast<object>().ShouldContain(item, "retirement can precede SDK item deletion");
|
|
});
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Partial_sdk_queue_drain_retains_a_pending_loss_control_once()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 1, true, 0, ct)).SubscriptionId;
|
|
var created = await client.CreateMonitoredItemsAsync(new RequestHeader(), sub, TimestampsToReturn.Both,
|
|
[new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = anchor, AttributeId = Attributes.Value },
|
|
MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters
|
|
{ ClientHandle = 1, SamplingInterval = 100, QueueSize = 3, DiscardOldest = true,
|
|
Filter = new ExtensionObject(new DataChangeFilter { Trigger = Opc.Ua.DataChangeTrigger.StatusValueTimestamp }) } }], ct);
|
|
created.Results[0].StatusCode.ShouldBe(StatusCodes.Good);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), false, [sub], ct);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
// Zero SDK sampling delay makes the queued ordering deterministic; source cadence is unchanged.
|
|
item.ModifyAttributes(item.DiagnosticsMasks, TimestampsToReturn.Both, item.ClientHandle,
|
|
item.Filter, item.Filter, null, 0, 3, true).ShouldBeNull();
|
|
item.QueueSize.ShouldBe(3u);
|
|
stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
|
await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull();
|
|
queuedLoss.GetValue(item).ShouldNotBeNull();
|
|
Convert.ToInt32(item.ItemsInQueue).ShouldBeGreaterThanOrEqualTo(2, "the SDK must actually retain a value before the loss");
|
|
// The client subscription can buffer several item callbacks before one
|
|
// response. Call the actual SDK item with maximum one to exercise a
|
|
// demonstrable partial item dequeue rather than assuming response boundaries.
|
|
var context = new Opc.Ua.Server.OperationContext(item);
|
|
var first = new Queue<MonitoredItemNotification>();
|
|
var firstDiagnostics = new Queue<DiagnosticInfo>();
|
|
item.Publish(context, first, firstDiagnostics, 1, NullLogger.Instance).ShouldBeTrue();
|
|
first.Count.ShouldBe(1);
|
|
first.Single().Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8,
|
|
"the first partial dequeue must contain the earlier sample, not the loss control");
|
|
queuedLoss.GetValue(item).ShouldNotBeNull("a partial drain must keep the later loss control");
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(300));
|
|
var second = new Queue<MonitoredItemNotification>();
|
|
var secondDiagnostics = new Queue<DiagnosticInfo>();
|
|
item.Publish(context, second, secondDiagnostics, 1, NullLogger.Instance).ShouldBeFalse();
|
|
var loss = second.ShouldHaveSingleItem().Value;
|
|
StatusCode.IsGood(loss.StatusCode).ShouldBeFalse();
|
|
loss.WrappedValue.IsNull.ShouldBeTrue();
|
|
queuedLoss.GetValue(item).ShouldBeNull();
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(1));
|
|
queuedLoss.GetValue(item).ShouldBeNull("a reported loss must not be requeued");
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Throwing_current_authority_sanitizes_a_loss_notification()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var demandField = item.GetType().GetField("_demand", flags).ShouldNotBeNull();
|
|
var demand = (IProjectedDemandLease)demandField.GetValue(item).ShouldNotBeNull();
|
|
demandField.SetValue(item, new ThrowingStatusDemand(demand));
|
|
try
|
|
{
|
|
var result = await PublishComposedValue(client, 1, ct);
|
|
result.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
|
result.WrappedValue.IsNull.ShouldBeTrue();
|
|
}
|
|
finally { demandField.SetValue(item, demand); }
|
|
});
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
private sealed class ThrowingStatusDemand(IProjectedDemandLease inner) : IProjectedDemandLease
|
|
{
|
|
public DataView OriginView => inner.OriginView;
|
|
public DataRealm Realm => inner.Realm;
|
|
public string LocalIdentifier => inner.LocalIdentifier;
|
|
public long ProjectionGeneration => inner.ProjectionGeneration;
|
|
public TimeSpan MaximumSampleAge => inner.MaximumSampleAge;
|
|
public ServingIdentity Serving => inner.Serving;
|
|
public CancellationToken CancellationToken => inner.CancellationToken;
|
|
public bool IsValid => throw new IOException("test authority callback failed");
|
|
public void Dispose() { }
|
|
}
|
|
|
|
private sealed class ObserveDemandDisposal(IProjectedDemandLease inner, Action beforeDispose) : IProjectedDemandLease
|
|
{
|
|
public DataView OriginView => inner.OriginView;
|
|
public DataRealm Realm => inner.Realm;
|
|
public string LocalIdentifier => inner.LocalIdentifier;
|
|
public long ProjectionGeneration => inner.ProjectionGeneration;
|
|
public TimeSpan MaximumSampleAge => inner.MaximumSampleAge;
|
|
public ServingIdentity Serving => inner.Serving;
|
|
public CancellationToken CancellationToken => inner.CancellationToken;
|
|
public bool IsValid => inner.IsValid;
|
|
public void Dispose() { beforeDispose(); inner.Dispose(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Dequeued_old_loss_is_suppressed_when_a_new_baseline_wins_before_delivery()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
var dequeued = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
using var releaseDequeue = new ManualResetEventSlim();
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var hook = item.GetType().GetField("AfterLossDequeueForTests", flags).ShouldNotBeNull();
|
|
hook.SetValue(item, (Action)(() => { dequeued.TrySetResult(); releaseDequeue.Wait(ct); }));
|
|
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var pending = client.PublishAsync(new RequestHeader(), default, timeout.Token);
|
|
await dequeued.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
held.Release.TrySetResult();
|
|
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
|
|
releaseDequeue.Set();
|
|
var old = await pending;
|
|
ComposedChanges(old.NotificationMessage).ShouldNotContain(x => x.ClientHandle == 1,
|
|
"a dequeued old-era loss must be suppressed after a new baseline");
|
|
var recovered = await PublishComposedValue(client, 1, ct);
|
|
recovered.StatusCode.ShouldBe(StatusCodes.Good);
|
|
recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
finally { releaseDequeue.Set(); held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Queued_sdk_loss_status_cannot_override_a_recovered_baseline()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), false, [sub], ct);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
|
var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull();
|
|
while (queuedLoss.GetValue(item) is null) await Task.Delay(10, timeout.Token);
|
|
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
|
held.Release.TrySetResult();
|
|
await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
|
|
await client.SetPublishingModeAsync(new RequestHeader(), true, [sub], ct);
|
|
var recovered = await PublishComposedValue(client, 1, ct);
|
|
recovered.StatusCode.ShouldBe(StatusCodes.Good, "a queued old-era loss must not follow a newer proven baseline");
|
|
recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Replayed_sdk_loss_status_never_reveals_data_after_authority_is_suspended()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
LocalCatalogCoordinator? coordinator = null;
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, placements, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 1, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var unavailable = await PublishComposedNotification(client, 1, ct);
|
|
StatusCode.IsGood(unavailable.Value.StatusCode).ShouldBeFalse();
|
|
unavailable.Value.WrappedValue.IsNull.ShouldBeTrue();
|
|
var replacement = Prepare(coordinator!);
|
|
try
|
|
{
|
|
var replay = await client.RepublishAsync(new RequestHeader(), sub, unavailable.Sequence, ct);
|
|
var value = ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value;
|
|
StatusCode.IsGood(value.StatusCode).ShouldBeFalse();
|
|
value.WrappedValue.IsNull.ShouldBeTrue();
|
|
}
|
|
catch (ServiceResultException error) { error.StatusCode.ShouldBe(StatusCodes.BadMessageNotAvailable); }
|
|
finally
|
|
{
|
|
var mapping = Mapping(origin.Raw);
|
|
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
|
|
placements.Stage(replacement, [mapping], [Connection()]);
|
|
coordinator!.Complete(replacement, true).ShouldBeTrue();
|
|
}
|
|
}, onCoordinator: value => coordinator = value);
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Sdk_item_does_not_report_source_loss_while_an_exact_proven_peer_remains()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new GateLaterSubscriptions(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var slow = (await client.CreateSubscriptionAsync(new RequestHeader(), 200, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, slow, anchor, 1, 200, ct);
|
|
var slowStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var first = await PublishComposedNotification(client, 1, ct);
|
|
first.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
var fast = (await client.CreateSubscriptionAsync(new RequestHeader(), 50, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, fast, anchor, 2, 50, ct);
|
|
var fastStream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
(await PublishComposedValue(client, 2, ct)).StatusCode.ShouldBe(StatusCodes.Good);
|
|
await slowStream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var replay = await client.RepublishAsync(new RequestHeader(), slow, first.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode)
|
|
.ShouldBeTrue("continuous exact-source coverage preserves the original still-fresh evidence");
|
|
await client.SetPublishingModeAsync(new RequestHeader(), false, [fast], ct);
|
|
fastStream.EmitValue(2, 42, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
|
await NextPublished(published.Reader, x => !x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 42), ct);
|
|
var next = await PublishComposedValue(client, 1, ct);
|
|
next.StatusCode.ShouldBe(StatusCodes.Good, "a covered peer loss must not enqueue a false outage status");
|
|
next.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(42);
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Sdk_item_reports_source_loss_then_recovers_on_a_new_complete_baseline()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
var held = new HoldSourceLossRetries(subscriptions);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => held);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
var published = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
|
try
|
|
{
|
|
await WithComposedServer(origin, origin.Raw, async (session, sink, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var initial = await PublishComposedNotification(client, 1, ct);
|
|
initial.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
initial.Value.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(7);
|
|
subscriptions.SnapshotVersion = 2; subscriptions.SnapshotValue = 8;
|
|
await stream.DisposeAsync();
|
|
await held.RetryBlocked.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
origin.Clock.Advance(TimeSpan.FromMilliseconds(100));
|
|
var unavailable = await PublishComposedNotification(client, 1, ct);
|
|
StatusCode.IsGood(unavailable.Value.StatusCode).ShouldBeFalse("a stopped source must actively change the SDK item's quality");
|
|
unavailable.Value.WrappedValue.IsNull.ShouldBeTrue();
|
|
unavailable.Value.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue);
|
|
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
|
|
var manager = sink.GetType().GetField("_nodeManager", flags)!.GetValue(sink)!;
|
|
var live = manager.GetType().GetField("_liveItems", flags)!.GetValue(manager)!;
|
|
var keys = (System.Collections.IEnumerable)live.GetType().GetProperty("Keys")!.GetValue(live)!;
|
|
var item = keys.Cast<object>().OfType<Opc.Ua.Server.MonitoredItem>().Single(x => x.ClientHandle == 1);
|
|
var queuedLoss = item.GetType().GetField("_queuedLoss", flags).ShouldNotBeNull();
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(1));
|
|
queuedLoss.GetValue(item).ShouldBeNull("one reported loss must not enqueue another status on each sweep");
|
|
var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
|
|
held.Release.TrySetResult();
|
|
var baseline = await NextPublished(published.Reader, x => x.IsCompleteSnapshot && Equals(x.Snapshot.Value, 8), ct);
|
|
baseline.SourceProof.IsValid.ShouldBeTrue();
|
|
var recovered = await PublishComposedValue(client, 1, ct);
|
|
recovered.StatusCode.ShouldBe(StatusCodes.Good);
|
|
recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
var obsolete = await client.RepublishAsync(new RequestHeader(), sub, unavailable.Sequence, ct);
|
|
ComposedChanges(obsolete.NotificationMessage).ShouldNotContain(x => x.ClientHandle == 1,
|
|
"an old loss status must not overwrite the new complete baseline");
|
|
}, onPublished: update => published.Writer.TryWrite(update));
|
|
}
|
|
finally { held.Release.TrySetResult(); }
|
|
}
|
|
|
|
[Fact(Timeout = 90000), Trait("Phase", "P11Wire")]
|
|
public async Task Sdk_item_reports_stale_silent_source_without_closing_a_live_stream()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
LocalDataFixture? peer = null;
|
|
var subscriptions = new FakeSubscriptions(() => peer!.Serving);
|
|
using var origin = new LocalDataFixture(servingGeneration: 1, targetSubscriptions: (_, _) => subscriptions);
|
|
peer = origin; subscriptions.SampleClock = origin.Clock;
|
|
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
|
{
|
|
var client = (SessionClient)session;
|
|
await BrowseAll(client, anchor, 1);
|
|
var sub = (await client.CreateSubscriptionAsync(new RequestHeader(), 100, 300, 1, 0, true, 0, ct)).SubscriptionId;
|
|
await AddComposedItem(client, sub, anchor, 1, 100, ct);
|
|
var stream = await subscriptions.ItemsAdded.Reader.ReadAsync(ct).AsTask().WaitAsync(TimeSpan.FromSeconds(10), ct);
|
|
var initial = await PublishComposedNotification(client, 1, ct);
|
|
initial.Value.StatusCode.ShouldBe(StatusCodes.Good);
|
|
origin.Clock.Advance(TimeSpan.FromSeconds(5)); // The 2-second age bound expired; the maintenance timer fired.
|
|
var stale = await PublishComposedValue(client, 1, ct);
|
|
StatusCode.IsGood(stale.StatusCode).ShouldBeFalse("an open but silent stream cannot leave its last value indefinitely Good");
|
|
stale.WrappedValue.IsNull.ShouldBeTrue();
|
|
stale.SourceTimestamp.ShouldBe(DateTimeUtc.MinValue);
|
|
subscriptions.Closed.Reader.TryRead(out _).ShouldBeFalse("a stale sample alone need not close a still-live stream");
|
|
stream.EmitValue(2, 8, origin.Clock.GetUtcNow(), TimeSpan.Zero);
|
|
var recovered = await PublishComposedValue(client, 1, ct);
|
|
recovered.StatusCode.ShouldBe(StatusCodes.Good);
|
|
recovered.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy).ShouldBe(8);
|
|
var replay = await client.RepublishAsync(new RequestHeader(), sub, initial.Sequence, ct);
|
|
StatusCode.IsGood(ComposedChanges(replay.NotificationMessage).Single(x => x.ClientHandle == 1).Value.StatusCode).ShouldBeFalse();
|
|
}, staleTimeoutMilliseconds: 2000);
|
|
}
|
|
|
|
private sealed class HoldSourceLossRetries(IDataSubscriptionService inner) : IDataSubscriptionService
|
|
{
|
|
private int _opens;
|
|
internal readonly TaskCompletionSource RetryBlocked = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public async Task<IDataSubscription> SubscribeAsync(CancellationToken ct)
|
|
{
|
|
if (Interlocked.Increment(ref _opens) > 1)
|
|
{
|
|
RetryBlocked.TrySetResult();
|
|
await Release.Task.WaitAsync(ct);
|
|
}
|
|
return await inner.SubscribeAsync(ct);
|
|
}
|
|
}
|
|
}
|