a117f79ad1
OtOpcUa now emits RefreshRequiredEventType (SourceNode = Server, no condition fields) on an incomplete condition snapshot, a removed imported condition, or a resync that leaves pre-failover EventIds answering BadEventIdUnknown. RealOpcUaClient had no branch for it: the event fell through HandleAlarmEvent as a phantom condition keyed "Server" and no refresh was issued, so the mirror could hold stale / un-ackable state. - HandleAlarmEvent recognises RefreshRequiredEventType, emits nothing, and hands the item's handle to the new ConditionRefreshCoalescer. - The coalescer runs off the SDK publish thread, debounces 500 ms so a burst (one event per affected item) costs one refresh, never overlaps refreshes (a request during an in-flight refresh is served by the next), logs and swallows failures, and is cleared on disconnect. - Execution: targeted ConditionRefresh2(eventSubscription, item) per asking item; one subscription-wide ConditionRefresh when every live alarm item asked, an item has no server id, or ConditionRefresh2 fails. The replay is the usual RefreshStart/End frame, so NativeAlarmActor's snapshot swap clears conditions the refreshed snapshot no longer lists. - The server-side OfType WhereClause built from a condition filter now ORs in OfType(RefreshRequiredEventType): the server queues RefreshRequired through the item's filter, so a bare condition-type clause dropped it. Tests: RealOpcUaRefreshRequiredTests (branch, no-session tolerance, burst coalescing, no overlap, failure tolerance, Clear, framing intact); RealOpcUaClientAlarmFilterTests updated for the added operand. Component-DataConnectionLayer.md documents the behaviour.
199 lines
8.7 KiB
C#
199 lines
8.7 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Reflection;
|
|
using Opc.Ua;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
|
|
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
|
|
|
|
/// <summary>
|
|
/// Gitea #148: OtOpcUa emits <c>RefreshRequiredEventType</c> (SourceNode = Server, no condition
|
|
/// fields) on an incomplete condition snapshot, a removed imported condition, or a resync that
|
|
/// invalidates EventIds. Per OPC UA Part 9 the client must call ConditionRefresh and must NOT treat
|
|
/// the event as an alarm. These tests pin the event branch in <c>HandleAlarmEvent</c> and the
|
|
/// debounce/coalesce behaviour of <see cref="ConditionRefreshCoalescer"/>.
|
|
/// </summary>
|
|
public class RealOpcUaRefreshRequiredTests
|
|
{
|
|
private static readonly MethodInfo Handler =
|
|
typeof(RealOpcUaClient).GetMethod("HandleAlarmEvent", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
|
|
|
/// <summary>OtOpcUa's RefreshRequired shape: SourceNode = Server, SourceName "Server", Message "RefreshRequired".</summary>
|
|
private static EventFieldList RefreshRequiredEvent() => new()
|
|
{
|
|
EventFields = new Variant[]
|
|
{
|
|
Variant.From(ObjectTypeIds.RefreshRequiredEventType), // 0 EventType
|
|
Variant.From(ObjectIds.Server), // 1 SourceNode
|
|
Variant.From("Server"), // 2 SourceName
|
|
Variant.From(DateTime.UtcNow), // 3 Time
|
|
Variant.From(new LocalizedText("RefreshRequired")), // 4 Message
|
|
Variant.From((ushort)100), // 5 Severity
|
|
Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null,
|
|
}
|
|
};
|
|
|
|
private static void Seed(RealOpcUaClient client, string handle)
|
|
{
|
|
var field = typeof(RealOpcUaClient).GetField("_alarmLastState", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
|
var map = (ConcurrentDictionary<string, Dictionary<string, (bool Active, bool Acked)>>)field.GetValue(client)!;
|
|
map[handle] = new Dictionary<string, (bool Active, bool Acked)>(StringComparer.Ordinal);
|
|
}
|
|
|
|
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout)
|
|
{
|
|
var deadline = DateTime.UtcNow + timeout;
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline)
|
|
throw new TimeoutException("condition not reached");
|
|
await Task.Delay(10);
|
|
}
|
|
}
|
|
|
|
/// <summary>A RefreshRequired event is never surfaced as a native alarm transition.</summary>
|
|
[Fact]
|
|
public async Task RefreshRequired_IsNotMappedAsAnAlarm_AndRequestsARefresh()
|
|
{
|
|
var client = new RealOpcUaClient();
|
|
Seed(client, "h1");
|
|
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
|
|
client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer(
|
|
(handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; },
|
|
TimeSpan.FromMilliseconds(20));
|
|
var sink = new List<NativeAlarmTransition>();
|
|
|
|
Handler.Invoke(client, ["h1", "ns=2;s=Area", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
|
|
|
|
Assert.Empty(sink); // no phantom condition keyed "Server"
|
|
await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5));
|
|
Assert.Equal(["h1"], batches.Single());
|
|
}
|
|
|
|
/// <summary>
|
|
/// The production executor tolerates a client with no live session: a RefreshRequired that
|
|
/// lands after a disconnect is logged and dropped, never thrown on the publish thread.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task RefreshRequired_WithNoSession_IsSwallowed()
|
|
{
|
|
var client = new RealOpcUaClient();
|
|
Seed(client, "h1");
|
|
var sink = new List<NativeAlarmTransition>();
|
|
|
|
Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
|
|
|
|
await WaitUntilAsync(() => client.RefreshRequiredCoalescer.ExecutedBatches == 1, TimeSpan.FromSeconds(5));
|
|
Assert.Empty(sink);
|
|
}
|
|
|
|
/// <summary>A burst of RefreshRequired across several items costs ONE refresh carrying every handle.</summary>
|
|
[Fact]
|
|
public async Task Burst_CoalescesIntoOneRefresh()
|
|
{
|
|
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
|
|
var coalescer = new ConditionRefreshCoalescer(
|
|
(handles, _) => { batches.Enqueue(handles.ToList()); return Task.CompletedTask; },
|
|
TimeSpan.FromMilliseconds(100));
|
|
|
|
for (var i = 0; i < 50; i++)
|
|
coalescer.Request(i % 2 == 0 ? "a" : "b");
|
|
|
|
await WaitUntilAsync(() => batches.Count >= 1, TimeSpan.FromSeconds(5));
|
|
await Task.Delay(300); // no trailing second refresh
|
|
Assert.Single(batches);
|
|
Assert.Equal(["a", "b"], batches.Single().OrderBy(h => h));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A request arriving WHILE a refresh runs is not lost and does not overlap it: it is served by
|
|
/// a second, sequential refresh.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task RequestDuringRefresh_RunsASecondSequentialRefresh()
|
|
{
|
|
var release = new TaskCompletionSource();
|
|
var concurrent = 0;
|
|
var maxConcurrent = 0;
|
|
var batches = new ConcurrentQueue<IReadOnlyCollection<string>>();
|
|
var coalescer = new ConditionRefreshCoalescer(async (handles, _) =>
|
|
{
|
|
var now = Interlocked.Increment(ref concurrent);
|
|
maxConcurrent = Math.Max(maxConcurrent, now);
|
|
batches.Enqueue(handles.ToList());
|
|
if (batches.Count == 1)
|
|
await release.Task;
|
|
Interlocked.Decrement(ref concurrent);
|
|
}, TimeSpan.FromMilliseconds(20));
|
|
|
|
coalescer.Request("a");
|
|
await WaitUntilAsync(() => batches.Count == 1, TimeSpan.FromSeconds(5));
|
|
coalescer.Request("b"); // while the first refresh is still in flight
|
|
await Task.Delay(100);
|
|
Assert.Single(batches);
|
|
release.SetResult();
|
|
|
|
await WaitUntilAsync(() => batches.Count == 2, TimeSpan.FromSeconds(5));
|
|
Assert.Equal(1, maxConcurrent);
|
|
Assert.Equal(["b"], batches.ToArray()[1]);
|
|
}
|
|
|
|
/// <summary>An executor fault is logged, not thrown, and does not stop later refreshes.</summary>
|
|
[Fact]
|
|
public async Task ExecutorFailure_IsSwallowed_AndLaterRequestsStillRefresh()
|
|
{
|
|
var calls = 0;
|
|
var coalescer = new ConditionRefreshCoalescer((_, _) =>
|
|
{
|
|
if (Interlocked.Increment(ref calls) == 1)
|
|
throw new ServiceResultException(StatusCodes.BadRefreshInProgress);
|
|
return Task.CompletedTask;
|
|
}, TimeSpan.FromMilliseconds(20));
|
|
|
|
coalescer.Request("a");
|
|
await WaitUntilAsync(() => Volatile.Read(ref calls) == 1, TimeSpan.FromSeconds(5));
|
|
await Task.Delay(50);
|
|
coalescer.Request("a");
|
|
await WaitUntilAsync(() => Volatile.Read(ref calls) == 2, TimeSpan.FromSeconds(5));
|
|
}
|
|
|
|
/// <summary>Clear() (disconnect) drops requests still debouncing — they belong to a dead session.</summary>
|
|
[Fact]
|
|
public async Task Clear_DropsPendingRequests()
|
|
{
|
|
var calls = 0;
|
|
var coalescer = new ConditionRefreshCoalescer(
|
|
(_, _) => { Interlocked.Increment(ref calls); return Task.CompletedTask; },
|
|
TimeSpan.FromMilliseconds(100));
|
|
|
|
coalescer.Request("a");
|
|
coalescer.Clear();
|
|
await Task.Delay(300);
|
|
Assert.Equal(0, Volatile.Read(ref calls));
|
|
}
|
|
|
|
/// <summary>
|
|
/// RefreshStart/RefreshEnd stay framing sentinels, never alarms, and RefreshRequired arriving
|
|
/// between them neither breaks the frame nor emits a condition.
|
|
/// </summary>
|
|
[Fact]
|
|
public void RefreshRequiredInsideARefreshFrame_LeavesTheFrameIntact()
|
|
{
|
|
var client = new RealOpcUaClient();
|
|
Seed(client, "h1");
|
|
client.RefreshRequiredCoalescer = new ConditionRefreshCoalescer(
|
|
(_, _) => Task.CompletedTask, TimeSpan.FromMilliseconds(10));
|
|
var sink = new List<NativeAlarmTransition>();
|
|
EventFieldList Boundary(NodeId type) => new()
|
|
{
|
|
EventFields = new Variant[] { Variant.From(type), Variant.Null, Variant.Null, Variant.Null, Variant.Null, Variant.Null }
|
|
};
|
|
|
|
Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshStartEventType), (Action<NativeAlarmTransition>)sink.Add]);
|
|
Handler.Invoke(client, ["h1", "", RefreshRequiredEvent(), (Action<NativeAlarmTransition>)sink.Add]);
|
|
Handler.Invoke(client, ["h1", "", Boundary(ObjectTypeIds.RefreshEndEventType), (Action<NativeAlarmTransition>)sink.Add]);
|
|
|
|
Assert.Equal(["SnapshotStart", "SnapshotComplete"], sink.Select(t => t.Kind.ToString()));
|
|
}
|
|
}
|