84b405ff5f
The compile cache was a `static` class, so its entry table and its Hits/Count
counters were one process-global blob every test class in the SiteRuntime
assembly wrote into. Row 91 last wave neutered the resulting flakes (per-test
GUID keys + one-sided counter bounds), but the shared mutable state itself
remained: any test calling Clear() evicted entries other parallel classes had
just inserted, and a Clear() from a class outside the serialized collection
would degrade the others to recompiles and re-open the row-91 flake class.
PREMISE CORRECTION: the register speculated production clears "per-instance or
per-deployment script entries" and offered ClearKeys(prefix) as the natural fit.
There are NO production callers of Clear() at all — grep of src/ finds only
GetOrAdd (ScriptCompilationService.CompileCore). Clear() existed solely so
tests could reset the global. A key-scoped API would therefore have been new
production surface built for nobody, so the instance-scoped seam is the fix and
Clear() is deleted outright rather than migrated.
- SiteScriptCompileCache: `internal static class` -> `internal sealed class`;
Cache/EvictionLock/_hits/_accessSequence become instance fields. LRU batch
eviction, the double-checked sweep and the ConcurrentDictionary.ToArray()
snapshot are byte-for-byte the same policy. Clear() removed.
- ScriptCompilationService owns one cache. Public ctor (the DI path) builds its
own; a new internal ctor takes one for tests. Production N4 sharing is
unchanged and now rests on the DI SINGLETON registration — the one service
instance is threaded to DeployCompileValidator and to every Instance Actor —
so that lifetime is load-bearing and is pinned by a new registration test.
- Tests: all three Clear() callers migrated off it. Each test now owns its cache,
which lets the assertions get STRONGER — the row-91 workarounds are retired:
Hits/Count are exact again (no >= baseline bounds), the per-test GUID key
token is gone, and ForeignEntrySlack (512 entries of allowance on the bound)
drops to the racing-thread count in the concurrency test. New test
SeparateCaches_DoNotShareEntriesOrCounters pins the scoping directly: filling
one cache past MaxEntries leaves another's entry, hit count and identity
intact. DeploymentWarmThenGateTests additionally asserts Count == 1 now that
its counter is private.
- The [Collection("SiteScriptCompileCache")] serialization from row 91 is
RELAXED (removed from all three classes) — they no longer touch any shared
state, so there is nothing left to serialize.
- Docs: Component-SiteRuntime.md gains the ownership/singleton note and drops
the Clear() reference; DeploymentManagerActor / DeployCompileValidator /
ServiceCollectionExtensions comments corrected to say where the cache lives.
Build: 0 warnings. SiteRuntime.Tests 643/643, three consecutive full-parallel
runs. AuditLog.Tests correlation classes (other ScriptCompilationService
consumers) green.
134 lines
7.8 KiB
C#
134 lines
7.8 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.LocalDb;
|
|
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.SiteEventLogging;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Deployment;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Streaming;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime;
|
|
|
|
public static class ServiceCollectionExtensions
|
|
{
|
|
/// <summary>
|
|
/// Registers Site Runtime services including SiteStorageService, which persists to the
|
|
/// consolidated site database resolved from <c>ILocalDb</c> (<c>LocalDb:Path</c>).
|
|
/// </summary>
|
|
/// <param name="services">The DI service collection to register services into.</param>
|
|
/// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
|
|
public static IServiceCollection AddSiteRuntime(this IServiceCollection services)
|
|
{
|
|
// SiteStorageService takes ILocalDb (the consolidated site database at
|
|
// LocalDb:Path) rather than a connection string, so there is nothing left for a
|
|
// caller to supply — the string overload is gone and this is the only entry point.
|
|
services.AddSingleton(sp => new SiteStorageService(
|
|
sp.GetRequiredService<ILocalDb>(),
|
|
sp.GetRequiredService<ILogger<SiteStorageService>>()));
|
|
|
|
services.AddHostedService<SiteStorageInitializer>();
|
|
|
|
// Script compilation service.
|
|
//
|
|
// SINGLETON IS LOAD-BEARING (register row 100): this service owns the
|
|
// SiteScriptCompileCache, so "one Roslyn compile per script body per process"
|
|
// (N4) is exactly the statement that there is one of these per host. Downgrading
|
|
// it to Scoped/Transient would silently give every consumer its own cache and
|
|
// reintroduce the recompile storms WP3.1 removed — no test would fail on
|
|
// behaviour, only the registration pin in SiteRuntimeServiceRegistrationTests.
|
|
services.AddSingleton<ScriptCompilationService>();
|
|
|
|
// Shared script library
|
|
services.AddSingleton<SharedScriptLibrary>();
|
|
|
|
// Site stream manager — registered as singleton and exposed as ISiteStreamSubscriber
|
|
// so the gRPC server can subscribe relay actors to instance events.
|
|
// ActorSystem is injected later via Initialize() after AkkaHostedService starts.
|
|
services.AddSingleton(sp =>
|
|
{
|
|
var options = sp.GetRequiredService<IOptions<SiteRuntimeOptions>>().Value;
|
|
var logger = sp.GetRequiredService<ILogger<SiteStreamManager>>();
|
|
return new SiteStreamManager(options, logger);
|
|
});
|
|
services.AddSingleton<ISiteStreamSubscriber>(sp => sp.GetRequiredService<SiteStreamManager>());
|
|
|
|
// Site-local cached-operation tracking store — the SQLite source of truth
|
|
// that Tracking.Status(TrackedOperationId) reads and the cached-call telemetry
|
|
// forwarder writes. Registered HERE (site-only) so the two comments that claim
|
|
// "the operational tracking store is registered by AddSiteRuntime" are true
|
|
// again (AuditLog SCE + AkkaHostedService). Before this (arch-review 08 round 2
|
|
// NF4/T8) it had no DI registration anywhere in src/, so every consumer resolved
|
|
// it as null and silently ran degraded (no cached-drain, no PullSiteCalls
|
|
// reconciliation, Tracking.Status audit-only). Central roots never call
|
|
// AddSiteRuntime, so this stays absent on central — matching the SITE-ONLY
|
|
// contract. OperationTrackingOptions is bound + validated by the Host's
|
|
// SiteServiceRegistration site-options block — but it no longer supplies the
|
|
// store's database: the store takes ILocalDb (the consolidated site database
|
|
// at LocalDb:Path), so OperationTrackingOptions.ConnectionString is now only
|
|
// read by the site config DB. Resolving this store therefore forces ILocalDb
|
|
// construction, which is what runs SiteLocalDbSetup.OnReady.
|
|
services.AddSingleton<Commons.Interfaces.IOperationTrackingStore, Tracking.OperationTrackingStore>();
|
|
|
|
// Site-local repository implementations backed by SQLite.
|
|
// WP2.6a: ExternalSystemDefinitionCache is a singleton shared by every scoped
|
|
// SiteExternalSystemRepository instance (one per script-execution DI scope), so
|
|
// resolving the repository repeatedly does not each pay a fresh SQLite
|
|
// fetch-all — DeploymentManagerActor invalidates the shared cache after an
|
|
// artifact deploy applies external-system changes.
|
|
services.AddSingleton<ExternalSystemDefinitionCache>();
|
|
services.AddScoped<IExternalSystemRepository>(sp => new SiteExternalSystemRepository(
|
|
sp.GetRequiredService<SiteStorageService>(),
|
|
sp.GetRequiredService<ExternalSystemDefinitionCache>()));
|
|
|
|
// Notify-and-fetch: typed HttpClient for fetching deployment configs from central.
|
|
services.AddHttpClient<IDeploymentConfigFetcher, HttpDeploymentConfigFetcher>()
|
|
.ConfigureHttpClient((sp, c) =>
|
|
c.Timeout = TimeSpan.FromSeconds(
|
|
sp.GetRequiredService<IOptions<SiteRuntimeOptions>>().Value.ConfigFetchTimeoutSeconds));
|
|
|
|
// S2/UA5: periodically lift the shared script-execution scheduler gauges
|
|
// (queue depth, busy threads, oldest-busy age) onto the site health report.
|
|
// Registered via factory-lambda so ISiteHealthCollector (registered by the
|
|
// Host's AddSiteHealthMonitoring) is resolved lazily at host start.
|
|
services.AddHostedService(sp => new ScriptSchedulerStatsReporter(
|
|
sp.GetRequiredService<HealthMonitoring.ISiteHealthCollector>(),
|
|
sp.GetRequiredService<IOptions<SiteRuntimeOptions>>().Value,
|
|
sp.GetRequiredService<ILogger<ScriptSchedulerStatsReporter>>()));
|
|
|
|
// WP2.6d: periodically lift SiteStreamManager's alarm-publish-queue drop count
|
|
// onto the site health report.
|
|
services.AddHostedService(sp => new Streaming.SiteStreamAlarmDropReporter(
|
|
sp.GetRequiredService<HealthMonitoring.ISiteHealthCollector>(),
|
|
sp.GetRequiredService<SiteStreamManager>(),
|
|
sp.GetRequiredService<ILogger<Streaming.SiteStreamAlarmDropReporter>>()));
|
|
|
|
// WP3.2 (site_events volume policy): the recorder is a singleton so ScriptRunLauncher
|
|
// can resolve it from the root service provider on every run, the same way it already
|
|
// resolves ISiteEventLogger. The flush service is registered ONLY here — central
|
|
// composition roots never call AddSiteRuntime(), which is what makes the periodic
|
|
// "script" summary event site-only, matching the design memo.
|
|
services.AddSingleton<ScriptRunSummaryRecorder>();
|
|
services.AddHostedService(sp => new ScriptRunSummaryFlushService(
|
|
sp.GetRequiredService<ScriptRunSummaryRecorder>(),
|
|
sp.GetRequiredService<ISiteEventLogger>(),
|
|
sp.GetRequiredService<IOptionsMonitor<SiteRuntimeOptions>>(),
|
|
sp.GetRequiredService<ILogger<ScriptRunSummaryFlushService>>()));
|
|
|
|
return services;
|
|
}
|
|
|
|
/// <summary>Registers any additional DI services needed by the Site Runtime Akka actors.</summary>
|
|
/// <param name="services">The DI service collection to register services into.</param>
|
|
/// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
|
|
public static IServiceCollection AddSiteRuntimeActors(this IServiceCollection services)
|
|
{
|
|
// Actor registration is handled by AkkaHostedService.RegisterSiteActors()
|
|
// which creates the DeploymentManager singleton and proxy
|
|
return services;
|
|
}
|
|
}
|