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:
Joseph Doherty
2026-12-03 10:23:50 -05:00
parent c5cd280739
commit 2ef2d751cb
9 changed files with 212 additions and 11 deletions
+1 -1
View File
@@ -175,7 +175,7 @@ The `sbk_<keyId>_<secret>` design already supports zero-downtime rotation — a
## Script Compilation & Hot-Reload ## Script Compilation & Hot-Reload
API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList<string> errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`. API method scripts are pre-compiled in the **background after startup** by `InboundMethodWarmupService` (a hosted service registered after `AkkaHostedService`, so it never delays the cluster join or `/health/*`): it waits for `ApplicationStarted`, then — only once this node is the active central node (`IActiveNodeGate`; a standby pays nothing until a failover promotes it) — loads all method definitions and compiles them into in-memory delegates. Lazy compile + the per-request revision check guarantee correctness regardless. Compiles are **single-flight per method name + script revision**: N concurrent first callers share one compile (and one non-collectible loaded assembly). `InboundScriptExecutor.CompileAndRegister(ApiMethod, out IReadOnlyList<string> errors)` compiles once and returns the diagnostics, so a save needs no separate validate pass; the management Create/Update path uses its sibling `CompileForPublish(method, out errors, out publish)`, which compiles once for the `compileWarning` and hands back a `publish` action queued as the post-commit registration — one compile (one pinned assembly) per save even inside a configuration transaction (review 2026-10-21 05/M1). `ApiMethodCache` prunes expired entries on a miss once large (scopes are exact method names — pinned by test — so growth is bounded). A Management API/UI create, update or delete drops that method's `ApiMethodCache` entry post-commit on the node that made the change; the peer central node converges within `ApiMethodCacheTtl` (default 5 s) — Gitea #85, audit `docs/plans/2026-11-09-central-cache-staleness-audit.md`. Runtime `$ref` resolution reads the shared-schema library from a process-wide `SharedSchemaLibraryCache` snapshot on the same `ApiMethodCacheTtl`, so a schema-library edit reaches running methods within that bound instead of costing two full library reads per request (INB-2, 2026-12-03).
### Update Workflow ### Update Workflow
@@ -260,7 +260,9 @@ public static class EndpointExtensions
var sharedSchemaRepo = var sharedSchemaRepo =
httpContext.RequestServices.GetService<ISharedSchemaRepository>(); httpContext.RequestServices.GetService<ISharedSchemaRepository>();
var resolveRef = await SchemaRefResolver.BuildAsync( var resolveRef = await SchemaRefResolver.BuildAsync(
sharedSchemaRepo, [method.ParameterDefinitions], httpContext.RequestAborted); sharedSchemaRepo, [method.ParameterDefinitions],
httpContext.RequestServices.GetService<SharedSchemaLibraryCache>(), // INB-2
httpContext.RequestAborted);
var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef); var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef);
if (!paramResult.IsValid) if (!paramResult.IsValid)
@@ -643,7 +643,9 @@ public class InboundScriptExecutor
var sharedSchemaRepo = var sharedSchemaRepo =
scope?.ServiceProvider.GetService<ISharedSchemaRepository>(); scope?.ServiceProvider.GetService<ISharedSchemaRepository>();
var resolveRef = await SchemaRefResolver.BuildAsync( var resolveRef = await SchemaRefResolver.BuildAsync(
sharedSchemaRepo, [method.ReturnDefinition], cts.Token); sharedSchemaRepo, [method.ReturnDefinition],
scope?.ServiceProvider.GetService<SharedSchemaLibraryCache>(), // INB-2
cts.Token);
// Validate the script's return value against the // Validate the script's return value against the
// method's declared ReturnDefinition. A method whose script returns a // method's declared ReturnDefinition. A method whose script returns a
@@ -528,6 +528,17 @@ public sealed class AuditWriteMiddleware
/// afterwards so the framework's next reader (the endpoint handler's /// afterwards so the framework's next reader (the endpoint handler's
/// JSON parser) sees the full body. /// JSON parser) sees the full body.
/// </remarks> /// </remarks>
/// <summary>
/// INB-3: how many body bytes the audit copy expects to read — the declared
/// <c>Content-Length</c> when it is under the cap, else the cap. The scratch buffer is
/// rented at this plus one byte.
/// </summary>
/// <param name="contentLength">The request's declared Content-Length, if any.</param>
/// <param name="capBytes">The audit capture cap.</param>
/// <returns>The expected capture length in bytes.</returns>
internal static int ExpectedCaptureBytes(long? contentLength, int capBytes) =>
contentLength is long declared && declared >= 0 && declared < capBytes ? (int)declared : capBytes;
private static async Task<(string? body, bool truncated)> ReadBufferedRequestBodyAsync( private static async Task<(string? body, bool truncated)> ReadBufferedRequestBodyAsync(
HttpRequest request, HttpRequest request,
int capBytes) int capBytes)
@@ -543,7 +554,14 @@ public sealed class AuditWriteMiddleware
// (and immediately discard) `cap + 1` bytes per request — the pool // (and immediately discard) `cap + 1` bytes per request — the pool
// may hand back a buffer LARGER than `limit`, so we treat `limit` // may hand back a buffer LARGER than `limit`, so we treat `limit`
// (not `buffer.Length`) as the read ceiling. // (not `buffer.Length`) as the read ceiling.
var limit = capBytes + 1; //
// INB-3: size the rent to the declared Content-Length when it is under the cap. A
// 200-byte body used to rent cap + 1 (1 MiB + 1 → the 2 MiB pool bucket, LOH) per
// request; a burst beyond the pool's per-core retention allocated fresh LOH arrays.
// Kestrel enforces that the body matches Content-Length, and anything read past the
// declared length is still reported as truncated below.
var expected = ExpectedCaptureBytes(request.ContentLength, capBytes);
var limit = expected + 1;
var buffer = ArrayPool<byte>.Shared.Rent(limit); var buffer = ArrayPool<byte>.Shared.Rent(limit);
try try
{ {
@@ -567,8 +585,8 @@ public sealed class AuditWriteMiddleware
return (null, false); return (null, false);
} }
var truncated = total > capBytes; var truncated = total > expected;
var bytesForString = truncated ? capBytes : total; var bytesForString = truncated ? expected : total;
var content = DecodeUtf8Bounded(buffer, bytesForString, cutAtValidBytes: truncated); var content = DecodeUtf8Bounded(buffer, bytesForString, cutAtValidBytes: truncated);
return (string.IsNullOrEmpty(content) ? null : content, truncated); return (string.IsNullOrEmpty(content) ? null : content, truncated);
} }
@@ -83,21 +83,47 @@ internal static class RelayProvenance
context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId; context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId;
} }
/// <summary>INB-4: the full replay-cache scan runs at most once per this many seconds.</summary>
private const int ReplayPruneIntervalSeconds = 5;
/// <summary>Unix second before which no further prune scan runs (INB-4).</summary>
private static long _nextPruneAt;
/// <summary>Number of prune scans performed — a test hook for INB-4.</summary>
internal static int PruneScans;
private static bool TryRecordProof(Proof proof) private static bool TryRecordProof(Proof proof)
=> TryRecordProof(proof.ExecutionId, proof.Nonce!, proof.Time);
/// <summary>Records a proof as seen; <see langword="false"/> for a replay or a full cache.</summary>
/// <param name="executionId">The proof's execution id.</param>
/// <param name="nonce">The proof's nonce.</param>
/// <param name="proofTime">The proof's own unix-second timestamp.</param>
/// <returns>Whether the proof was new and recorded.</returns>
internal static bool TryRecordProof(Guid executionId, string nonce, long proofTime)
{ {
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// INB-4: prune on a time basis. Each entry lives ~301 s past its proof time, so above
// ~14 relayed req/s the count stays over the threshold with nothing expired, and the
// old every-call scan walked up to the whole dictionary per relayed request. One
// thread per interval wins the CAS and scans; everyone else skips straight to the add.
if (SeenProofs.Count >= ReplayPruneThreshold) if (SeenProofs.Count >= ReplayPruneThreshold)
{ {
var due = Interlocked.Read(ref _nextPruneAt);
if (now >= due && Interlocked.CompareExchange(ref _nextPruneAt, now + ReplayPruneIntervalSeconds, due) == due)
{
Interlocked.Increment(ref PruneScans);
foreach (var kv in SeenProofs) foreach (var kv in SeenProofs)
if (kv.Value <= now) SeenProofs.TryRemove(kv); if (kv.Value <= now) SeenProofs.TryRemove(kv);
} }
}
// Still full after pruning live entries: fail closed rather than grow without bound. // Still full after pruning live entries: fail closed rather than grow without bound.
if (SeenProofs.Count >= ReplayHardCap) return false; if (SeenProofs.Count >= ReplayHardCap) return false;
// The proof is valid for +/- the window around its own timestamp, so keep the record // The proof is valid for +/- the window around its own timestamp, so keep the record
// until the far edge of that window. // until the far edge of that window.
return SeenProofs.TryAdd(proof.ExecutionId.ToString("N") + ":" + proof.Nonce, proof.Time + ProofWindowSeconds + 1); return SeenProofs.TryAdd(executionId.ToString("N") + ":" + nonce, proofTime + ProofWindowSeconds + 1);
} }
/// <summary>Reads a stream fully, failing if it exceeds the given byte limit.</summary> /// <summary>Reads a stream fully, failing if it exceeds the given byte limit.</summary>
@@ -44,9 +44,26 @@ public static class SchemaRefResolver
/// A synchronous <c>name → schema JSON?</c> resolver, or <c>null</c> when no definition /// A synchronous <c>name → schema JSON?</c> resolver, or <c>null</c> when no definition
/// uses a <c>$ref</c> (so the validators take their unchanged no-resolver path). /// uses a <c>$ref</c> (so the validators take their unchanged no-resolver path).
/// </returns> /// </returns>
public static Task<Func<string, string?>?> BuildAsync(
ISharedSchemaRepository? repository,
IEnumerable<string?> definitions,
CancellationToken ct = default)
=> BuildAsync(repository, definitions, cache: null, ct);
/// <summary>
/// As <see cref="BuildAsync(ISharedSchemaRepository?, IEnumerable{string?}, CancellationToken)"/>,
/// serving the library from <paramref name="cache"/> when one is supplied (INB-2) instead of
/// reading it from the database on every call.
/// </summary>
/// <param name="repository">The shared-schema repository, or <c>null</c> when none is registered.</param>
/// <param name="definitions">The schema definition JSON strings to be validated (parameter and/or return).</param>
/// <param name="cache">The process-wide library snapshot cache, or <c>null</c> to read the repository directly.</param>
/// <param name="ct">Cancellation token for the library load.</param>
/// <returns>A synchronous resolver, or <c>null</c> when no definition uses a <c>$ref</c>.</returns>
public static async Task<Func<string, string?>?> BuildAsync( public static async Task<Func<string, string?>?> BuildAsync(
ISharedSchemaRepository? repository, ISharedSchemaRepository? repository,
IEnumerable<string?> definitions, IEnumerable<string?> definitions,
SharedSchemaLibraryCache? cache,
CancellationToken ct = default) CancellationToken ct = default)
{ {
// Skip the library round-trip entirely unless some definition uses a $ref. // Skip the library round-trip entirely unless some definition uses a $ref.
@@ -55,8 +72,9 @@ public static class SchemaRefResolver
return null; return null;
} }
var library = await repository.ListAsync(ct); IReadOnlyDictionary<string, string> map = cache is not null
var map = library.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal); ? await cache.GetAsync(repository, ct)
: (await repository.ListAsync(ct)).ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
return name => map.GetValueOrDefault(name); return name => map.GetValueOrDefault(name);
} }
} }
@@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions
services.AddSingleton(sp => new ApiMethodCache( services.AddSingleton(sp => new ApiMethodCache(
sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl)); sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));
// INB-2: the shared-schema library snapshot runtime $ref resolution reads, on the same
// TTL as the ApiMethod row it is resolved for.
services.AddSingleton(sp => new SharedSchemaLibraryCache(
sp.GetRequiredService<IOptions<InboundApiOptions>>().Value.ApiMethodCacheTtl));
// Routed calls go through the IInstanceRouter seam; the // Routed calls go through the IInstanceRouter seam; the
// production implementation delegates to CommunicationService. // production implementation delegates to CommunicationService.
services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>(); services.AddScoped<IInstanceRouter, CommunicationServiceInstanceRouter>();
@@ -0,0 +1,57 @@
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
/// <summary>
/// INB-2: a short-TTL, process-wide snapshot of the shared-schema library (name → schema
/// JSON) for runtime <c>$ref</c> resolution.
/// </summary>
/// <remarks>
/// A method whose parameter or return definition used a <c>$ref</c> read the whole library
/// from the database twice per request (once for parameter validation, once for return
/// validation, on different scopes). The library changes only on a designer edit, so one
/// snapshot is shared for <see cref="InboundApiOptions.ApiMethodCacheTtl"/> — the same bound
/// the resolved <c>ApiMethod</c> row is already cached for, so a schema edit becomes visible
/// to callers on the same cadence as a method edit. Concurrent misses may both load; the
/// last write wins, which is harmless for a read-only snapshot.
/// </remarks>
public sealed class SharedSchemaLibraryCache
{
private sealed record Snapshot(IReadOnlyDictionary<string, string> Library, DateTimeOffset ExpiresAtUtc);
private readonly TimeSpan _ttl;
private readonly TimeProvider _timeProvider;
private Snapshot? _snapshot;
/// <summary>Initializes the cache.</summary>
/// <param name="ttl">How long a loaded library snapshot is served.</param>
/// <param name="timeProvider">Clock; defaults to the system clock.</param>
public SharedSchemaLibraryCache(TimeSpan ttl, TimeProvider? timeProvider = null)
{
if (ttl <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "SharedSchemaLibraryCache TTL must be positive.");
_ttl = ttl;
_timeProvider = timeProvider ?? TimeProvider.System;
}
/// <summary>Returns the cached library snapshot, loading it through <paramref name="repository"/> when stale.</summary>
/// <param name="repository">The shared-schema repository used on a miss.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The library as name → schema JSON.</returns>
public async Task<IReadOnlyDictionary<string, string>> GetAsync(ISharedSchemaRepository repository, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(repository);
var now = _timeProvider.GetUtcNow();
var current = Volatile.Read(ref _snapshot);
if (current is not null && current.ExpiresAtUtc > now)
return current.Library;
var library = (await repository.ListAsync(ct).ConfigureAwait(false))
.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
Volatile.Write(ref _snapshot, new Snapshot(library, now + _ttl));
return library;
}
/// <summary>Drops the snapshot so the next lookup reloads the library.</summary>
public void Invalidate() => Volatile.Write(ref _snapshot, null);
}
@@ -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;
}
}