99f2b9d8b7
Track RefreshStart..RefreshEnd per alarm subscription. EventQueueOverflow (matched by EventType before the source filter - it comes from the Server object), RefreshRequired, a publish-sequence gap the SDK skipped (EventFieldList.Message.SequenceNumber; SDK 2.0.1's Republish publish-state never fires for a gap that blocks delivery) or a missing RefreshStart suppress the A1 signal and re-run ConditionRefresh, bounded (3, 2/4/8 s); exhausted = conditions stay unknown (Uncertain), never Unsignalable. Alarm event queue 1000 -> 10000; new counters alarm_event_queue_overflow / alarm_refresh_lossy. Unit + real-SDK gap tests, live overflow gate on opc-plc --alm; plan G2 text corrected.
362 lines
18 KiB
C#
362 lines
18 KiB
C#
using Opc.Ua;
|
|
using Opc.Ua.Client;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using static ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests.OpcUaClientInitialAlarmStateSignalTests;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
|
|
|
/// <summary>
|
|
/// #926 — a RefreshEnd declares the conditions it covers state-known (grpc-data A1), so it may signal only for a
|
|
/// LOSSLESS RefreshStart…RefreshEnd bracket. A loss inside the bracket (the server's EventQueueOverflowEventType, a
|
|
/// RefreshRequired, a publish-sequence gap the SDK skipped) or a missing RefreshStart suppresses the signal
|
|
/// and re-runs ConditionRefresh, bounded; a never-signal outcome leaves the conditions unknown (Uncertain).
|
|
/// </summary>
|
|
[Trait("Category", "Unit")]
|
|
[Trait("Feature", "GrpcData")]
|
|
[Trait("Issue", "926")]
|
|
public sealed class OpcUaClientRefreshBracketLossTests
|
|
{
|
|
private const string Trip1 = "Plant/opc/plc/Trip1";
|
|
|
|
/// <summary>The authored source index: the overflow notice (SourceNode = Server) is NOT in it, so this also proves
|
|
/// the notice is seen before the source filter.</summary>
|
|
private static readonly Dictionary<string, string> Index = new() { ["ns=3;s=Alarms.Trip1"] = Trip1 };
|
|
|
|
private static (OpcUaClientDriver Drv, List<string> Trace, IAlarmSubscriptionHandle Handle, RetryProbe Retries) NewDriver(string id)
|
|
{
|
|
var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), id)
|
|
{
|
|
// Long enough that a replay's own (lossy) RefreshEnd is routed before its re-refresh starts, as in production
|
|
// (2 s back-off vs. a 500 ms publishing interval); short enough to keep the suite fast.
|
|
AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(100),
|
|
};
|
|
var trace = Record(drv);
|
|
var handle = drv.AddAlarmSubscriptionForTest([Trip1]);
|
|
var retries = new RetryProbe();
|
|
drv.AlarmRefreshRetryInvokerForTest = (_, _) => { retries.Hit(); return Task.CompletedTask; };
|
|
return (drv, trace, handle, retries);
|
|
}
|
|
|
|
private static void Route(OpcUaClientDriver drv, IAlarmSubscriptionHandle h, NodeId type) =>
|
|
drv.RouteAlarmEvent(Marker(type), Index, h);
|
|
|
|
/// <summary>The issue's scenario: refreshed events overflowed the upstream queue, RefreshEnd still arrived. No signal
|
|
/// (the condition stays unknown), a re-refresh is run, and ITS clean bracket signals.</summary>
|
|
[Fact]
|
|
public async Task Overflow_inside_the_bracket_suppresses_the_signal_and_re_refreshes()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-overflow");
|
|
using var _ = drv;
|
|
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
drv.RouteAlarmEvent(Condition(active: false, acked: true), Index, h); // what survived; the active one was lost
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
|
|
trace.ShouldNotContain(t => t.StartsWith("signal:"), "a lossy replay must never declare its conditions known");
|
|
await retries.WaitForAsync(1);
|
|
|
|
// The re-refresh's replay is lossless ⇒ signalled (positive control: the bracket CAN signal).
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
drv.RouteAlarmEvent(Condition(active: true, acked: false), Index, h);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.Last().ShouldBe("signal:" + Trip1);
|
|
trace.Count(t => t.StartsWith("signal:")).ShouldBe(1);
|
|
retries.Count.ShouldBe(1, "one loss ⇒ one re-refresh (the lossy RefreshEnd does not request a second)");
|
|
}
|
|
|
|
/// <summary>A bracket whose RefreshStart never arrived (lost with the head of the replay) does not signal.</summary>
|
|
[Fact]
|
|
public async Task RefreshEnd_without_its_RefreshStart_does_not_signal()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-nostart");
|
|
using var _ = drv;
|
|
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBeEmpty();
|
|
await retries.WaitForAsync(1);
|
|
}
|
|
|
|
/// <summary>A RefreshRequired inside the bracket is a loss; its own sweep is the re-refresh, so the driver adds none.</summary>
|
|
[Fact]
|
|
public async Task RefreshRequired_inside_the_bracket_suppresses_the_signal()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-required");
|
|
using var _ = drv;
|
|
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshRequiredEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBeEmpty();
|
|
await Task.Delay(200, TestContext.Current.CancellationToken);
|
|
retries.Count.ShouldBe(0);
|
|
|
|
// Positive control: the next clean bracket signals.
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBe(["signal:" + Trip1]);
|
|
}
|
|
|
|
/// <summary>An overflow OUTSIDE a bracket lost live events: a re-refresh repairs them (and its bracket signals).</summary>
|
|
[Fact]
|
|
public async Task Overflow_outside_a_bracket_requests_a_re_refresh()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-live-overflow");
|
|
using var _ = drv;
|
|
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
await retries.WaitForAsync(1);
|
|
trace.ShouldBeEmpty("the overflow notice is never projected as an alarm");
|
|
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBe(["signal:" + Trip1]);
|
|
}
|
|
|
|
/// <summary>Liveness: a re-refresh whose own RefreshStart is lost (the queue is still full, so only overflow notices
|
|
/// arrive and no bracket ever opens) can still request the next one, up to the bound.</summary>
|
|
[Fact]
|
|
public async Task A_re_refresh_whose_RefreshStart_is_lost_can_request_the_next()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-start-lost");
|
|
using var _ = drv;
|
|
|
|
for (var n = 1; n <= OpcUaClientDriver.MaxAlarmRefreshRetries; n++)
|
|
{
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType); // coalesced into the same request
|
|
await retries.WaitForAsync(n);
|
|
}
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
await Task.Delay(500, TestContext.Current.CancellationToken);
|
|
retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries);
|
|
trace.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary>A structurally lossy upstream (every replay overflows) costs at most <see cref="OpcUaClientDriver.MaxAlarmRefreshRetries"/>
|
|
/// re-refreshes, then never signals — the conditions stay unknown. A later clean bracket signals and resets the budget.</summary>
|
|
[Fact]
|
|
public async Task Re_refresh_is_bounded_and_the_budget_resets_on_a_clean_bracket()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-bounded");
|
|
using var _ = drv;
|
|
|
|
for (var i = 0; i < OpcUaClientDriver.MaxAlarmRefreshRetries + 3; i++)
|
|
{
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
await retries.WaitForAsync(Math.Min(i + 1, OpcUaClientDriver.MaxAlarmRefreshRetries));
|
|
}
|
|
await Task.Delay(200, TestContext.Current.CancellationToken);
|
|
retries.Count.ShouldBe(OpcUaClientDriver.MaxAlarmRefreshRetries, "no refresh storm");
|
|
trace.ShouldBeEmpty("never-signal is the safe outcome: Uncertain, not known-inactive");
|
|
|
|
// A lossless bracket (a RefreshRequired sweep, a reconnect) signals and gives the budget back.
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBe(["signal:" + Trip1]);
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
Route(drv, h, ObjectTypeIds.EventQueueOverflowEventType);
|
|
await retries.WaitForAsync(OpcUaClientDriver.MaxAlarmRefreshRetries + 1);
|
|
}
|
|
|
|
/// <summary>A publish-sequence gap inside a bracket (a message the SDK gave up on) suppresses its signal; contiguous
|
|
/// numbers, a repeat (several events in one message), the wrap and a gap outside a bracket are no loss.</summary>
|
|
[Fact]
|
|
public async Task Sequence_gap_inside_the_bracket_suppresses_outside_is_ignored()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-seqgap");
|
|
using var _ = drv;
|
|
|
|
drv.NoteAlarmMessageSequence(h, 5);
|
|
drv.NoteAlarmMessageSequence(h, 9); // gap outside a bracket: the next bracket replays everything
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
drv.NoteAlarmMessageSequence(h, 10);
|
|
drv.NoteAlarmMessageSequence(h, 10); // a second event of the same message
|
|
drv.NoteAlarmMessageSequence(h, 0); // unknown (no message): ignored
|
|
drv.NoteAlarmMessageSequence(h, 11);
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.ShouldBe(["signal:" + Trip1], "no loss inside that bracket");
|
|
|
|
drv.NoteAlarmMessageSequence(h, uint.MaxValue);
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
drv.NoteAlarmMessageSequence(h, 1); // the wrap is contiguous
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2);
|
|
retries.Count.ShouldBe(0);
|
|
|
|
Route(drv, h, ObjectTypeIds.RefreshStartEventType);
|
|
drv.NoteAlarmMessageSequence(h, 3); // message 2 lost
|
|
Route(drv, h, ObjectTypeIds.RefreshEndEventType);
|
|
trace.Count(t => t.StartsWith("signal:")).ShouldBe(2, "the replay with a lost message did not signal");
|
|
await retries.WaitForAsync(1);
|
|
}
|
|
|
|
/// <summary>The overflow notice is never an alarm, even pass-through (no authored refs).</summary>
|
|
[Fact]
|
|
public void Overflow_notice_is_never_projected()
|
|
{
|
|
OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.EventQueueOverflowEventType), new Dictionary<string, string>(),
|
|
new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldBeNull();
|
|
// Positive control: a non-marker event from the same source projects pass-through.
|
|
OpcUaClientDriver.ProjectEvent(Marker(ObjectTypeIds.BaseEventType), new Dictionary<string, string>(),
|
|
new StrayHandle(), n => n.ToString(), (_, _) => { }).ShouldNotBeNull();
|
|
}
|
|
|
|
/// <summary>The alarm event item asks for the deeper queue.</summary>
|
|
[Fact]
|
|
public void Alarm_event_queue_is_deep() => OpcUaClientDriver.AlarmEventQueueSize.ShouldBeGreaterThanOrEqualTo(10_000u);
|
|
|
|
/// <summary>
|
|
/// Through a REAL SDK subscription with the driver's alarm options: the publish message carrying a refreshed
|
|
/// event (seq 3) is lost and its republish fails (not available). The SDK skips the gap and delivers the
|
|
/// RefreshEnd (seq 4) — reporting the skip to nothing observable: its <c>Republish</c> publish-state is raised
|
|
/// only in a worker pass that also delivers a message, which the gap prevents. The driver's own sequence check
|
|
/// (<see cref="OpcUaClientDriver.RouteAlarmEventFieldList"/>) suppresses that RefreshEnd.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Abandoned_publish_gap_suppresses_the_RefreshEnd_through_the_real_SDK()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-gap");
|
|
using var _ = drv;
|
|
|
|
var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: 3);
|
|
|
|
order.ShouldBe(["live:1", "start:2", "end:4"], "the SDK skipped the lost message and delivered the RefreshEnd");
|
|
trace.ShouldNotContain(t => t.StartsWith("signal:"), "a replay with a lost message must not declare its conditions known");
|
|
await retries.WaitForAsync(1);
|
|
}
|
|
|
|
/// <summary>Positive control for the real-SDK test: the same replay with nothing lost signals.</summary>
|
|
[Fact]
|
|
public async Task Lossless_publish_sequence_signals_through_the_real_SDK()
|
|
{
|
|
var (drv, trace, h, retries) = NewDriver("opcua-926-sdk-nogap");
|
|
using var _ = drv;
|
|
|
|
var order = await GapReplay.DeliverAsync(drv.BuildAlarmSubscriptionOptions(1), drv, h, Index, skip: null);
|
|
|
|
order.ShouldBe(["live:1", "start:2", "refreshed:3", "end:4"]);
|
|
trace.ShouldBe(["event:" + Trip1 + ":Retrigger", "signal:" + Trip1]);
|
|
retries.Count.ShouldBe(0);
|
|
}
|
|
|
|
private sealed class StrayHandle : IAlarmSubscriptionHandle
|
|
{
|
|
public string DiagnosticId => "stray";
|
|
}
|
|
|
|
private sealed class RetryProbe
|
|
{
|
|
private int _count;
|
|
public int Count => Volatile.Read(ref _count);
|
|
public void Hit() => Interlocked.Increment(ref _count);
|
|
|
|
public async Task WaitForAsync(int n)
|
|
{
|
|
var until = DateTime.UtcNow.AddSeconds(10);
|
|
while (Count < n && DateTime.UtcNow < until) await Task.Delay(10);
|
|
Count.ShouldBeGreaterThanOrEqualTo(n);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Feeds publish responses 1 (a live event), 2 (RefreshStart), 3 (a refreshed Active event), 4 (RefreshEnd) and
|
|
/// 5..8 (unrelated events) into a real SDK <see cref="Subscription"/>, routing every delivered event through the
|
|
/// driver's production entry. <c>skip</c>: a sequence number that never arrives and is not available for
|
|
/// republish. Returns the order of what was delivered (kind:sequence) up to the RefreshEnd.
|
|
/// </summary>
|
|
private static class GapReplay
|
|
{
|
|
public static async Task<List<string>> DeliverAsync(SubscriptionOptions options, OpcUaClientDriver drv,
|
|
IAlarmSubscriptionHandle handle, Dictionary<string, string> index, uint? skip)
|
|
{
|
|
var order = new List<string>();
|
|
var ended = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var subscription = new Subscription(telemetry: null!, options);
|
|
var item = new MonitoredItem(telemetry: null!, new MonitoredItemOptions
|
|
{
|
|
DisplayName = "Server/Events",
|
|
StartNodeId = ObjectIds.Server,
|
|
AttributeId = Attributes.EventNotifier,
|
|
Filter = new EventFilter(),
|
|
});
|
|
item.Notification += (_, args) =>
|
|
{
|
|
if (args.NotificationValue is not EventFieldList efl) return;
|
|
lock (order)
|
|
{
|
|
if (ended.Task.IsCompleted) return;
|
|
var seq = efl.Message?.SequenceNumber ?? 0;
|
|
var kind = UpstreamValueMapping.ToClr(efl.EventFields[1]) is NodeId t
|
|
? t == ObjectTypeIds.RefreshStartEventType ? "start"
|
|
: t == ObjectTypeIds.RefreshEndEventType ? "end"
|
|
: seq == 3 ? "refreshed" : "live"
|
|
: "?";
|
|
order.Add($"{kind}:{seq}");
|
|
drv.RouteAlarmEventFieldList(efl, index, handle);
|
|
if (kind == "end") ended.TrySetResult();
|
|
}
|
|
};
|
|
subscription.AddItem(item);
|
|
subscription.AddItem(item);
|
|
|
|
const System.Reflection.BindingFlags all = System.Reflection.BindingFlags.Instance
|
|
| System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic;
|
|
var save = typeof(Subscription).GetMethods(all)
|
|
.First(m => m.Name == "SaveMessageInCache" && m.GetParameters().Length == 2);
|
|
typeof(Subscription).GetMethod("StartKeepAliveTimer", all)!.Invoke(subscription, null);
|
|
|
|
var available = new uint[] { 1, 2, 3, 4, 5, 6, 7, 8 }.Where(n => n != skip).ToArray();
|
|
async Task Send(uint seq, List<Variant> fields, int pauseMs)
|
|
{
|
|
var message = new NotificationMessage
|
|
{
|
|
SequenceNumber = seq,
|
|
PublishTime = DateTime.UtcNow,
|
|
NotificationData =
|
|
[
|
|
new ExtensionObject(new EventNotificationList
|
|
{
|
|
Events = [new EventFieldList { ClientHandle = item.ClientHandle, EventFields = fields.ToArray() }],
|
|
}),
|
|
],
|
|
};
|
|
save.Invoke(subscription, [SdkReplay.ToParam(save, available), message]);
|
|
await Task.Delay(pauseMs);
|
|
}
|
|
|
|
try
|
|
{
|
|
// seq 1 is a live event before the refresh: the SDK's first message only re-syncs its sequence.
|
|
await Send(1, Unrelated(), 300);
|
|
await Send(2, Marker(ObjectTypeIds.RefreshStartEventType), 300);
|
|
if (skip != 3) await Send(3, Condition(active: true, acked: false), 300);
|
|
await Send(4, Marker(ObjectTypeIds.RefreshEndEventType), 300);
|
|
await Send(5, Unrelated(), 300);
|
|
// The SDK republishes a gap once it is > 2.5 s old with later messages behind it, then skips it once
|
|
// the republish has failed; each step runs on a later arrival.
|
|
for (uint seq = 6; seq <= 8 && !ended.Task.IsCompleted; seq++)
|
|
await Send(seq, Unrelated(), 2700);
|
|
await ended.Task.WaitAsync(TimeSpan.FromSeconds(15));
|
|
}
|
|
finally
|
|
{
|
|
subscription.Dispose();
|
|
}
|
|
|
|
lock (order) return order.ToList();
|
|
}
|
|
|
|
private static List<Variant> Unrelated()
|
|
{
|
|
var f = Marker(ObjectTypeIds.BaseEventType);
|
|
f[2] = new Variant(NodeId.Parse("ns=9;s=Elsewhere")); // not an authored source ⇒ dropped by the filter
|
|
return f;
|
|
}
|
|
}
|
|
}
|