From 2ef2d751cba966391764ffc0e26b21b6c9f41cfb Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:23:50 -0500 Subject: [PATCH] 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) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- docs/requirements/Component-InboundAPI.md | 2 +- .../EndpointExtensions.cs | 4 +- .../InboundScriptExecutor.cs | 4 +- .../Middleware/AuditWriteMiddleware.cs | 24 +++++- .../RelayProvenance.cs | 32 +++++++- .../SchemaRefResolver.cs | 22 +++++- .../ServiceCollectionExtensions.cs | 5 ++ .../SharedSchemaLibraryCache.cs | 57 +++++++++++++++ .../Wp6InboundPerfTests.cs | 73 +++++++++++++++++++ 9 files changed, 212 insertions(+), 11 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/Wp6InboundPerfTests.cs diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index e2bc85b8..a76de6c3 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -175,7 +175,7 @@ The `sbk__` design already supports zero-downtime rotation — a ## 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 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 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 diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs index 171532db..dc5fce98 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/EndpointExtensions.cs @@ -260,7 +260,9 @@ public static class EndpointExtensions var sharedSchemaRepo = httpContext.RequestServices.GetService(); var resolveRef = await SchemaRefResolver.BuildAsync( - sharedSchemaRepo, [method.ParameterDefinitions], httpContext.RequestAborted); + sharedSchemaRepo, [method.ParameterDefinitions], + httpContext.RequestServices.GetService(), // INB-2 + httpContext.RequestAborted); var paramResult = ParameterValidator.Validate(body, method.ParameterDefinitions, resolveRef); if (!paramResult.IsValid) diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs index 17a2e45a..caf87e49 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs @@ -643,7 +643,9 @@ public class InboundScriptExecutor var sharedSchemaRepo = scope?.ServiceProvider.GetService(); var resolveRef = await SchemaRefResolver.BuildAsync( - sharedSchemaRepo, [method.ReturnDefinition], cts.Token); + sharedSchemaRepo, [method.ReturnDefinition], + scope?.ServiceProvider.GetService(), // INB-2 + cts.Token); // Validate the script's return value against the // method's declared ReturnDefinition. A method whose script returns a diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs index e1017d58..d06f66aa 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/Middleware/AuditWriteMiddleware.cs @@ -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. /// + /// + /// INB-3: how many body bytes the audit copy expects to read — the declared + /// Content-Length when it is under the cap, else the cap. The scratch buffer is + /// rented at this plus one byte. + /// + /// The request's declared Content-Length, if any. + /// The audit capture cap. + /// The expected capture length in bytes. + 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.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); } diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs index ebdfe318..9dd46b5c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/RelayProvenance.cs @@ -83,13 +83,39 @@ internal static class RelayProvenance context.Items[AuditWriteMiddleware.InboundExecutionIdItemKey] = proof.ExecutionId; } + /// INB-4: the full replay-cache scan runs at most once per this many seconds. + private const int ReplayPruneIntervalSeconds = 5; + + /// Unix second before which no further prune scan runs (INB-4). + private static long _nextPruneAt; + + /// Number of prune scans performed — a test hook for INB-4. + internal static int PruneScans; + private static bool TryRecordProof(Proof proof) + => TryRecordProof(proof.ExecutionId, proof.Nonce!, proof.Time); + + /// Records a proof as seen; for a replay or a full cache. + /// The proof's execution id. + /// The proof's nonce. + /// The proof's own unix-second timestamp. + /// Whether the proof was new and recorded. + 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); } /// Reads a stream fully, failing if it exceeds the given byte limit. diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs index 07b9e596..a1460548 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SchemaRefResolver.cs @@ -44,9 +44,26 @@ public static class SchemaRefResolver /// A synchronous name → schema JSON? resolver, or null when no definition /// uses a $ref (so the validators take their unchanged no-resolver path). /// + public static Task?> BuildAsync( + ISharedSchemaRepository? repository, + IEnumerable definitions, + CancellationToken ct = default) + => BuildAsync(repository, definitions, cache: null, ct); + + /// + /// As , + /// serving the library from when one is supplied (INB-2) instead of + /// reading it from the database on every call. + /// + /// The shared-schema repository, or null when none is registered. + /// The schema definition JSON strings to be validated (parameter and/or return). + /// The process-wide library snapshot cache, or null to read the repository directly. + /// Cancellation token for the library load. + /// A synchronous resolver, or null when no definition uses a $ref. public static async Task?> BuildAsync( ISharedSchemaRepository? repository, IEnumerable 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 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); } } diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs index 3b9d4087..f77b46e9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs @@ -29,6 +29,11 @@ public static class ServiceCollectionExtensions services.AddSingleton(sp => new ApiMethodCache( sp.GetRequiredService>().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>().Value.ApiMethodCacheTtl)); + // Routed calls go through the IInstanceRouter seam; the // production implementation delegates to CommunicationService. services.AddScoped(); diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs new file mode 100644 index 00000000..02f81e6e --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/SharedSchemaLibraryCache.cs @@ -0,0 +1,57 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; + +namespace ZB.MOM.WW.ScadaBridge.InboundAPI; + +/// +/// INB-2: a short-TTL, process-wide snapshot of the shared-schema library (name → schema +/// JSON) for runtime $ref resolution. +/// +/// +/// A method whose parameter or return definition used a $ref 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 — the same bound +/// the resolved ApiMethod 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. +/// +public sealed class SharedSchemaLibraryCache +{ + private sealed record Snapshot(IReadOnlyDictionary Library, DateTimeOffset ExpiresAtUtc); + + private readonly TimeSpan _ttl; + private readonly TimeProvider _timeProvider; + private Snapshot? _snapshot; + + /// Initializes the cache. + /// How long a loaded library snapshot is served. + /// Clock; defaults to the system clock. + 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; + } + + /// Returns the cached library snapshot, loading it through when stale. + /// The shared-schema repository used on a miss. + /// Cancellation token. + /// The library as name → schema JSON. + public async Task> 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; + } + + /// Drops the snapshot so the next lookup reloads the library. + public void Invalidate() => Volatile.Write(ref _snapshot, null); +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/Wp6InboundPerfTests.cs b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/Wp6InboundPerfTests.cs new file mode 100644 index 00000000..a75f4057 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/Wp6InboundPerfTests.cs @@ -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; + +/// 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; + } +}