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
@@ -260,7 +260,9 @@ public static class EndpointExtensions
var sharedSchemaRepo =
httpContext.RequestServices.GetService<ISharedSchemaRepository>();
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);
if (!paramResult.IsValid)
@@ -643,7 +643,9 @@ public class InboundScriptExecutor
var sharedSchemaRepo =
scope?.ServiceProvider.GetService<ISharedSchemaRepository>();
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
// 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
/// JSON parser) sees the full body.
/// </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(
HttpRequest request,
int capBytes)
@@ -543,7 +554,14 @@ public sealed class AuditWriteMiddleware
// (and immediately discard) `cap + 1` bytes per request — the pool
// may hand back a buffer LARGER than `limit`, so we treat `limit`
// (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);
try
{
@@ -567,8 +585,8 @@ public sealed class AuditWriteMiddleware
return (null, false);
}
var truncated = total > capBytes;
var bytesForString = truncated ? capBytes : total;
var truncated = total > expected;
var bytesForString = truncated ? expected : total;
var content = DecodeUtf8Bounded(buffer, bytesForString, cutAtValidBytes: truncated);
return (string.IsNullOrEmpty(content) ? null : content, truncated);
}
@@ -83,13 +83,39 @@ internal static class RelayProvenance
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)
=> 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();
// 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)
{
foreach (var kv in SeenProofs)
if (kv.Value <= now) SeenProofs.TryRemove(kv);
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)
if (kv.Value <= now) SeenProofs.TryRemove(kv);
}
}
// Still full after pruning live entries: fail closed rather than grow without bound.
@@ -97,7 +123,7 @@ internal static class RelayProvenance
// The proof is valid for +/- the window around its own timestamp, so keep the record
// 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>
@@ -44,9 +44,26 @@ public static class SchemaRefResolver
/// 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).
/// </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(
ISharedSchemaRepository? repository,
IEnumerable<string?> definitions,
SharedSchemaLibraryCache? cache,
CancellationToken ct = default)
{
// Skip the library round-trip entirely unless some definition uses a $ref.
@@ -55,8 +72,9 @@ public static class SchemaRefResolver
return null;
}
var library = await repository.ListAsync(ct);
var map = library.ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
IReadOnlyDictionary<string, string> map = cache is not null
? await cache.GetAsync(repository, ct)
: (await repository.ListAsync(ct)).ToDictionary(s => s.Name, s => s.SchemaJson, StringComparer.Ordinal);
return name => map.GetValueOrDefault(name);
}
}
@@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions
services.AddSingleton(sp => new ApiMethodCache(
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
// production implementation delegates to CommunicationService.
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);
}