Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.SiteRuntime/ServiceCollectionExtensions.cs
T
Joseph Doherty 0b5e9b44f6 feat(localdb): rewire OperationTrackingStore onto the consolidated site database
Task 4 of the LocalDb Phase 1 adoption plan.

OperationTrackingStore took IOptions<OperationTrackingOptions> and opened its own
SqliteConnection from ConnectionString. It now takes ILocalDb and gets every
connection - writer and the two ad-hoc reader paths - from CreateConnection().

This is not cosmetic. OperationTracking is a RegisterReplicated table, so its
capture triggers call zb_hlc_next(). That UDF is registered per connection by
ILocalDb and by nothing else, so a raw SqliteConnection would fail closed on
every write. Connections from CreateConnection() also arrive already open -
calling Open()/OpenAsync() on one throws - hence the removed OpenAsync calls on
the reader paths.

OperationTrackingOptions.ConnectionString is now vestigial for this store; the
database location is LocalDb:Path. The options class stays (retention settings)
and the config key stays bound for the site config DB.

InitializeSchema is kept but is now always a no-op in the host: onReady runs
while ILocalDb is being constructed, strictly before this constructor can
receive it. It remains so a directly-constructed store (tests, tooling) is
self-sufficient.

Tests: the store fixture moves off mode=memory&cache=shared onto a real ILocalDb
over a temp file. There is no in-memory mode - LocalDbOptions.Path is a
filesystem path - and testing through a raw in-memory connection would no longer
resemble the host. Verifier connections stay raw on purpose: this fixture never
registers the table, so no trigger fires and the UDF is never reached.

Three DI fixtures needed LocalDb:Path added, because resolving
IOperationTrackingStore now forces ILocalDb construction:
SiteCompositionRootTests, SiteAuditWiringTests, and the AuditLog
CombinedTelemetryHarness.

Verified: build 0 warnings; Host 294/294, SiteRuntime 530/530, AuditLog 354/354.

Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
2026-07-19 08:59:38 -04:00

111 lines
6.0 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
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 for SQLite persistence.
/// The caller must register an <see cref="ISiteStorageConnectionProvider"/> or call the
/// overload with an explicit connection string.
/// </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 is registered by the Host using AddSiteRuntime(connectionString)
// This overload is for backward compatibility / skeleton placeholder
return services;
}
/// <summary>
/// Registers Site Runtime services with an explicit SQLite connection string.
/// </summary>
/// <param name="services">The DI service collection to register services into.</param>
/// <param name="siteDbConnectionString">The SQLite connection string for the site local storage database.</param>
/// <returns>The same <see cref="IServiceCollection"/> to allow chaining.</returns>
public static IServiceCollection AddSiteRuntime(this IServiceCollection services, string siteDbConnectionString)
{
services.AddSingleton(sp =>
{
var logger = sp.GetRequiredService<ILogger<SiteStorageService>>();
return new SiteStorageService(siteDbConnectionString, logger);
});
services.AddHostedService<SiteStorageInitializer>();
// Script compilation service
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
services.AddScoped<IExternalSystemRepository, SiteExternalSystemRepository>();
// 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>>()));
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;
}
}