using System.Diagnostics.Metrics;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;
///
/// #926 live gate against opc-plc --alm: an alarm event item whose queue is far smaller than one
/// ConditionRefresh replay overflows on the REAL server. The server's EventQueueOverflowEventType must reach
/// the driver (it comes from the Server object, past the source filter), the RefreshEnd must NOT signal, and the
/// driver's re-refresh is bounded. The positive control is the same driver with the production queue, which signals.
/// Read-only against the fixture.
///
[Collection(OpcPlcCollection.Name)]
[Trait("Category", "LiveIntegration")]
[Trait("Feature", "GrpcData")]
[Trait("Issue", "926")]
public sealed class OpcUaClientRefreshOverflowLiveTests(OpcPlcFixture sim, ITestOutputHelper output)
{
///
/// discardOldest: false (production): the overflowing replay loses its RefreshEnd too (the newest events
/// are dropped), so nothing can signal. true: the RefreshEnd survives but the RefreshStart and the head of
/// the replay do not — the case a naive RefreshEnd signal gets wrong. (Observed on the fixture's opc-plc, 2026-11-28:
/// with discardOldest false a queue of 1 yields overflow notices; a queue of 2 yielded none at all — and no
/// RefreshEnd either, so it still never signalled.)
///
[Theory]
[InlineData(false, 1u)]
[InlineData(true, 2u)]
public async Task Overflowing_refresh_never_signals_and_re_refresh_is_bounded(bool discardOldest, uint queueSize)
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
var id = $"opcua-926-live-{Guid.NewGuid():N}";
using var counts = new EventCounts(id);
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id)
{
AlarmEventItemQueueSize = queueSize, // one replay = RefreshStart + every retained condition + RefreshEnd
AlarmEventItemDiscardOldest = discardOldest,
AlarmRefreshRetryBaseDelay = TimeSpan.FromMilliseconds(250),
};
var signals = 0;
drv.InitialAlarmStateDelivered += (_, _) => Interlocked.Increment(ref signals);
drv.OnAlarmEvent += (_, _) => { };
await drv.InitializeAsync("{}", ct);
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
// 1 + 3 retries, back-off 0.25 + 0.5 + 1 s; allow the replays to arrive.
var until = DateTime.UtcNow.AddSeconds(20);
while (counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy) < 1 + OpcUaClientDriver.MaxAlarmRefreshRetries
&& DateTime.UtcNow < until)
await Task.Delay(100, ct);
await Task.Delay(3000, ct); // quiet window: nothing further may arrive
output.WriteLine($"discardOldest={discardOldest} overflows={counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow)} " +
$"lossyRefreshEnds={counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy)} signals={signals}");
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBeGreaterThan(0,
"the server's EventQueueOverflowEventType reached the driver past the source filter");
Volatile.Read(ref signals).ShouldBe(0, "a lossy replay must never declare its conditions known");
if (discardOldest)
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeGreaterThan(0,
"the RefreshEnd arrived and was refused as lossy (its RefreshStart was discarded)");
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBeLessThanOrEqualTo(
1 + OpcUaClientDriver.MaxAlarmRefreshRetries, "re-refresh is bounded — no refresh storm");
await drv.ShutdownAsync(ct);
}
[Fact]
public async Task Production_queue_refresh_signals()
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
var id = $"opcua-926-live-ctl-{Guid.NewGuid():N}";
using var counts = new EventCounts(id);
await using var drv = new OpcUaClientDriver(OpcPlcProfile.BuildOptions(sim.EndpointUrl), id);
var signalled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
drv.InitialAlarmStateDelivered += (_, e) => signalled.TrySetResult(e);
drv.OnAlarmEvent += (_, _) => { };
await drv.InitializeAsync("{}", ct);
await drv.SubscribeAlarmsAsync(["Plant/opc/plc/926"], ct);
(await signalled.Task.WaitAsync(TimeSpan.FromSeconds(30), ct)).Unsignalable.ShouldBeFalse();
counts.Get(OpcUaClientDiagnostics.AlarmEventQueueOverflow).ShouldBe(0);
counts.Get(OpcUaClientDiagnostics.AlarmRefreshLossy).ShouldBe(0);
await drv.ShutdownAsync(ct);
}
/// Counts otopcua.driver.opcuaclient.events for ONE driver instance (the instance tag filters out
/// parallel tests' measurements).
private sealed class EventCounts : IDisposable
{
private readonly MeterListener _listener = new();
private readonly Dictionary _counts = new();
public EventCounts(string driverInstanceId)
{
// Run the telemetry type's static initializer FIRST: if the counter is created while this listener is
// live, InstrumentPublished runs inside that initializer, where the field still reads null — the counter
// would never be enabled and every count would read 0 (seen when this class ran alone).
var counter = OtOpcUaTelemetry.OpcUaClientEvents;
_listener.InstrumentPublished = (inst, l) =>
{
if (ReferenceEquals(inst, counter)) l.EnableMeasurementEvents(inst);
};
_listener.SetMeasurementEventCallback((_, value, tags, _) =>
{
string? instance = null, evt = null;
foreach (var t in tags)
{
if (t.Key == OtOpcUaTelemetry.PollOverrunDriverInstanceTag) instance = t.Value as string;
else if (t.Key == "event") evt = t.Value as string;
}
if (instance != driverInstanceId || evt is null) return;
lock (_counts) _counts[evt] = _counts.GetValueOrDefault(evt) + value;
});
_listener.Start();
}
public long Get(string evt) { lock (_counts) return _counts.GetValueOrDefault(evt); }
public void Dispose() => _listener.Dispose();
}
}