using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
///
/// lmxopcua#1053 (review 01 R-25): ConfiguredProjectedInterestOwner.SweepAsync re-queued every desired entry
/// every second, so a configured reference that cannot be resolved (origin down, mapping gone) re-ran discovery once a
/// second for as long as the interest lasted. A failed resolve now backs off exponentially (1 s doubling, 30 s cap).
///
[Trait("Category", "Unit"), Trait("Feature", "GrpcData")]
public sealed class GrpcDataConfiguredInterestBackoffTests
{
private static readonly string Reference = ProjectedDataIds.DependencyReference(DataRealm.Raw,
ProjectedDataIds.Identifier("mapping", new DataAddress("origin", "urn:raw", "string", "plant/unresolvable")));
///
/// Sixty one-second sweeps against a reference that never resolves: one discovery per sweep before the fix (~61),
/// at most the backoff schedule's handful after it (t = 0, 1, 3, 7, 15, 31 s). Positive control: the retries do not
/// stop — once discovery succeeds, a later sweep within the 30 s cap acquires the lease.
///
[Fact(Timeout = 60000)]
public async Task An_unresolvable_configured_reference_backs_off_instead_of_rediscovering_every_second()
{
var ct = TestContext.Current.CancellationToken;
var clock = new ManualTimeProvider();
var discovery = new FlakyDiscovery();
await using var owner = new ConfiguredProjectedInterestOwner(discovery, 4, clock: clock);
await clock.WaitForTimerDueAtAsync(clock.Start + TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
owner.SetInterest(Reference, true);
await WaitUntilAsync(() => Volatile.Read(ref discovery.Calls) >= 1, ct);
for (var second = 0; second < 60; second++)
{
clock.Advance(TimeSpan.FromSeconds(1));
await Task.Delay(30, ct); // let the sweep + a worker act on the tick (an upper bound is what is asserted)
}
var failedCalls = Volatile.Read(ref discovery.Calls);
failedCalls.ShouldBeLessThanOrEqualTo(8,
$"an unresolvable reference must back off; it was rediscovered {failedCalls} times in 60 s");
failedCalls.ShouldBeGreaterThanOrEqualTo(3, "it is still retried, just less often");
// Positive control: the origin comes back; a sweep within the 30 s cap resolves it.
discovery.Succeed = true;
for (var second = 0; second < 31 && discovery.Acquired == 0; second++)
{
clock.Advance(TimeSpan.FromSeconds(1));
await Task.Delay(30, ct);
}
await WaitUntilAsync(() => Volatile.Read(ref discovery.Acquired) == 1, ct);
}
private static async Task WaitUntilAsync(Func condition, CancellationToken ct)
{
var giveUp = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (!condition())
{
if (DateTime.UtcNow > giveUp) throw new TimeoutException("condition not reached");
await Task.Delay(5, ct);
}
}
private sealed class FlakyDiscovery : IConfiguredProjectionDiscovery
{
public int Calls, Acquired;
public volatile bool Succeed;
public Task ResolveAsync(string reference, CancellationToken cancellationToken)
{
Interlocked.Increment(ref Calls);
if (!Succeed) return Task.FromResult(null);
Interlocked.Increment(ref Acquired);
return Task.FromResult(new Lease());
}
}
private sealed class Lease : IConfiguredProjectionLease
{
public bool IsValid => true;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}