perf(inbound-api): cached schema library snapshot, Content-Length-sized audit buffer, time-based replay prune (INB-2, INB-3, INB-4, WP6 task 6.9)
INB-2: new SharedSchemaLibraryCache (singleton, ApiMethodCacheTtl) serves the shared-schema library to SchemaRefResolver for both the parameter and the return validation; previously each $ref-using request read the whole library twice (two scopes/DbContexts). No shared-schema invalidation bus exists, so the snapshot self-heals on the TTL — the same bound the ApiMethod row itself is already cached for (documented in Component-InboundAPI). Parsed-schema caching was not added (parse is cheap next to the DB reads). 50 req/s on a $ref method: 100 library reads/s -> <=1 per 5 s per node (test: 100 resolutions -> 1 ListAsync; reload after TTL). INB-3: the audit body copy rents ExpectedCaptureBytes(Content-Length, cap)+1 instead of cap+1, and anything read past the declared length still reports truncated. 200-byte body: 1 MiB+1 rent (2 MiB LOH pool bucket) -> 201 bytes (256 B bucket). INB-4: the replay cache's full prune scan runs at most once per 5 s (one CAS winner) instead of on every relayed request once over 4,096 entries. Throwaway Stopwatch, ~15k live entries, 2,000 relayed requests: old per-request scan 214 us -> new 31 us (one amortised scan).
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
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;
|
||||
|
||||
/// <summary>WP6 task 6.9: INB-2 (library snapshot), INB-3 (scratch sizing), INB-4 (time-based replay prune).</summary>
|
||||
public class Wp6InboundPerfTests
|
||||
{
|
||||
private const string RefDefinition = """[{"name":"p","type":"Object","$ref":"lib:Shape"}]""";
|
||||
|
||||
/// <summary>INB-2: repeated $ref resolution within the TTL reads the library once; after the TTL it reloads.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SchemaLibrary_IsReadOncePerTtl_NotPerResolution()
|
||||
{
|
||||
var repo = Substitute.For<ISharedSchemaRepository>();
|
||||
repo.ListAsync(Arg.Any<CancellationToken>()).Returns(new List<SharedSchema> { 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<CancellationToken>());
|
||||
|
||||
clock.Advance(TimeSpan.FromSeconds(6));
|
||||
await SchemaRefResolver.BuildAsync(repo, [RefDefinition], cache);
|
||||
await repo.Received(2).ListAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>INB-3: the audit scratch buffer is sized to the declared body, not the 1 MiB cap.</summary>
|
||||
[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));
|
||||
|
||||
/// <summary>INB-4: past the prune threshold, a burst of relayed proofs triggers at most one full scan per interval.</summary>
|
||||
[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;
|
||||
/// <summary>Advances the clock.</summary>
|
||||
/// <param name="by">The amount to advance.</param>
|
||||
public void Advance(TimeSpan by) => _now += by;
|
||||
/// <inheritdoc />
|
||||
public override DateTimeOffset GetUtcNow() => _now;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user