using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Schemas;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.InboundAPI.Middleware;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI.Tests;
/// WP6 task 6.9: INB-2 (library snapshot), INB-3 (scratch sizing), INB-4 (time-based replay prune).
public class Wp6InboundPerfTests
{
private const string RefDefinition = """[{"name":"p","type":"Object","$ref":"lib:Shape"}]""";
/// INB-2: repeated $ref resolution within the TTL reads the library once; after the TTL it reloads.
/// A task that represents the asynchronous operation.
[Fact]
public async Task SchemaLibrary_IsReadOncePerTtl_NotPerResolution()
{
var repo = Substitute.For();
repo.ListAsync(Arg.Any()).Returns(new List { new() { Name = "Shape", SchemaJson = "{\"type\":\"object\"}" } });
var clock = new ManualClock(DateTimeOffset.UtcNow);
var cache = new SharedSchemaLibraryCache(TimeSpan.FromSeconds(5), clock);
for (var i = 0; i < 100; i++)
{
var resolve = await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
Assert.NotNull(resolve!("Shape"));
}
await repo.Received(1).ListAsync(Arg.Any());
clock.Advance(TimeSpan.FromSeconds(6));
await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
await repo.Received(2).ListAsync(Arg.Any());
}
/// INB-3: the audit scratch buffer is sized to the declared body, not the 1 MiB cap.
[Theory]
[InlineData(200L, 1_048_576, 200)]
[InlineData(null, 1_048_576, 1_048_576)]
[InlineData(5_000_000L, 1_048_576, 1_048_576)]
[InlineData(-1L, 1_048_576, 1_048_576)]
public void AuditScratch_IsSizedToContentLength(long? contentLength, int cap, int expected)
=> Assert.Equal(expected, AuditWriteMiddleware.ExpectedCaptureBytes(contentLength, cap));
/// INB-4: past the prune threshold, a burst of relayed proofs triggers at most one full scan per interval.
[Fact]
public void ReplayCache_PrunesOnATimeBasis_NotPerRequest()
{
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
for (var i = 0; i < 5000; i++)
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
var before = Volatile.Read(ref RelayProvenance.PruneScans);
for (var i = 0; i < 2000; i++)
Assert.True(RelayProvenance.TryRecordProof(Guid.NewGuid(), "n", now));
Assert.True(Volatile.Read(ref RelayProvenance.PruneScans) - before <= 1,
"the replay cache was scanned more than once inside one prune interval");
// ...and a replay is still refused.
var id = Guid.NewGuid();
Assert.True(RelayProvenance.TryRecordProof(id, "x", now));
Assert.False(RelayProvenance.TryRecordProof(id, "x", now));
}
private sealed class ManualClock(DateTimeOffset start) : TimeProvider
{
private DateTimeOffset _now = start;
/// Advances the clock.
/// The amount to advance.
public void Advance(TimeSpan by) => _now += by;
///
public override DateTimeOffset GetUtcNow() => _now;
}
}