Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.InboundAPI/ServiceCollectionExtensions.cs
T
Joseph Doherty 2ef2d751cb 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).
2026-12-03 10:23:50 -05:00

67 lines
3.7 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
namespace ZB.MOM.WW.ScadaBridge.InboundAPI;
public static class ServiceCollectionExtensions
{
/// <summary>
/// Registers all inbound API services (script executor, route helper, and endpoint filter).
/// </summary>
/// <param name="services">The service collection to register into.</param>
/// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
public static IServiceCollection AddInboundAPI(this IServiceCollection services)
{
// Inbound authentication is handled by the shared
// ZB.MOM.WW.Auth.ApiKeys verifier (Bearer sbk_<keyId>_<secret>), registered by
// AddZbApiKeyAuth in the Host composition root. The legacy ApiKeyValidator +
// peppered IApiKeyHasher and the SQL Server ApiKey store were retired, so this
// extension no longer registers them.
services.AddSingleton<InboundScriptExecutor>();
services.AddScoped<RouteHelper>();
// Short-TTL cache of resolved ApiMethod rows, sitting in front of the
// per-request repository fetch in EndpointExtensions. Invalidated by name via
// ScriptArtifactChangeSubscriber (below) and self-heals via TTL expiry for
// changes the bus does not cover.
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>();
// Endpoint filter enforcing the request
// body size cap and active-node gating for POST /api/{methodName}.
services.AddSingleton<InboundApiEndpointFilter>();
// Standby-node forwarding (2026-08-28): a standby relays POST /api/{methodName}
// to the active peer over HTTP instead of answering 503 STANDBY_NODE. The
// named client has no HttpClient.Timeout of its own — the forwarder's per-attempt
// CTS (InboundApiOptions.StandbyForwardTimeout) is the single deadline, so a
// long-running method on the active node is not cut off by a second, hidden cap.
services.AddHttpClient(HttpStandbyRequestForwarder.HttpClientName)
.ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan);
services.AddSingleton<IStandbyRequestForwarder, HttpStandbyRequestForwarder>();
// N1: the ApiMethod consumer of the script-artifact invalidation bus.
// The bus parameter is optional — hosts without a registered
// IScriptArtifactChangeBus (site roles, plain test hosts) start it as a no-op
// and the executor's per-request revision check alone keeps handlers fresh.
services.AddHostedService<ScriptArtifactChangeSubscriber>();
// ScadaBridge#103: a create / update / delete / recompile made through the other central
// node drops this node's handler, known-bad record and cached row for the method.
services.TryAddEnumerable(ServiceDescriptor.Singleton<ICentralCacheInvalidationHandler, InboundApiCacheInvalidationHandler>());
return services;
}
}