f2efeb37b7
Tasks 5 and 6 of the Phase 2 plan, committed together because their test
fallout is entangled — several fixtures construct both stores.
StoreAndForwardStorage and SiteStorageService now take ILocalDb. Connections
come from ILocalDb.CreateConnection(), which hands out an already-open,
pragma-configured connection carrying the zb_hlc_next() UDF the capture triggers
call; a raw connection would lack the UDF and every write to a replicated table
would fail closed. Deleted with the connection strings: S&F's
EnsureDatabaseDirectoryExists and its per-open busy_timeout pragma, and the site
service's BusyTimeoutFloorSeconds normalization — LocalDb owns all of it now.
DI: AddSiteRuntime's string overload is gone (nothing left to supply), so the
Host calls the no-arg form. ScadaBridge:Database:SiteDbPath and
StoreAndForwardOptions.SqliteDbPath survive only as the migrator's source
locations in Tasks 8/9.
Two things the plan did not anticipate, both worth reading:
1. FOUND A REAL LATENT DEFECT, from Phase 1, now fixed. The plan assumed
directory creation simply moved to LocalDb along with file ownership. It did
not: the LocalDb library never creates the parent directory, and
SqliteLocalDb opens the file eagerly in its constructor — so a missing
directory is a hard boot failure ("SQLite Error 14: unable to open database
file"), not a degraded start. The default site config points at the RELATIVE
path ./data/site-localdb.db, so any site node without a pre-existing data/
directory fails to boot. The docker rig escapes only because its volume mount
happens to create /app/data — a coincidence that would have hidden this until
a bare-metal or fresh deployment. This has been latent since Phase 1 made
LocalDb:Path required; deleting S&F's EnsureDatabaseDirectoryExists here
would have widened it. Re-established the guarantee at the layer that now
owns the path (SiteLocalDbDirectory.Ensure, called before AddZbLocalDb) and
pinned it with SiteLocalDbDirectoryTests. Non-vacuity is not assumed: two
tests written against the wrong assumption failed with exactly this
SQLite Error 14 before the fix existed.
2. Test fallout was ~7x the plan's estimate. The plan named "fixtures" in one
project; the constructor change actually reaches 40 files across 7 test
projects, and most used Mode=Memory;Cache=Shared — which LocalDb has no
equivalent for, so every one had to move to a real temp file. Rather than
copy the Phase 1 TestLocalDb fixture into 7 projects, added a shared
tests/ZB.MOM.WW.ScadaBridge.TestSupport library (not a test project) so the
WAL-sidecar cleanup and the "real, not stubbed" rationale live in one place.
Retargeted rather than deleted, in both directions: the S&F WAL test now asserts
against the LocalDb-backed store (WAL genuinely is LocalDb's job), while the
directory-creation test moved to Host.Tests (that guarantee is NOT LocalDb's).
SiteStorageServiceTests.Initialize_EnablesWalJournalMode got the same treatment.
DeploymentManagerMediumFindingsTests induced a persistence failure via an
unopenable path, which no longer reaches the assertion since the fixture now
throws first; it induces the same failure shape via an uninitialized store.
Verified: full solution build 0 warnings; SiteRuntime 532, Host 318,
AuditLog 355, ExternalSystemGateway 142, HealthMonitoring 97,
StoreAndForward 153 — 1597 passed, 0 failed.
Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
219 lines
9.1 KiB
C#
219 lines
9.1 KiB
C#
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.TestSupport;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Repositories;
|
|
|
|
/// <summary>
|
|
/// SiteRuntime-006 / SiteRuntime-007 regression tests for the site-local repositories.
|
|
///
|
|
/// SiteRuntime-006: the repositories must obtain a SQLite connection through
|
|
/// <see cref="SiteStorageService.CreateConnection"/>, not by reading a private field
|
|
/// via reflection.
|
|
///
|
|
/// SiteRuntime-007: the synthetic integer IDs derived from entity names must be stable
|
|
/// across process restarts (a freshly-constructed service/repository), so an ID handed
|
|
/// to a caller still resolves the same entity later.
|
|
/// </summary>
|
|
public class SiteRepositoryTests : IDisposable
|
|
{
|
|
private readonly TestLocalDb _localDb;
|
|
|
|
public SiteRepositoryTests()
|
|
{
|
|
_localDb = TestLocalDb.CreateTemp("site-repo-test");
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
// Dispose first — the master connection anchors the WAL, so the sidecars
|
|
// cannot be removed while it is open.
|
|
var path = _localDb.Path;
|
|
_localDb.Dispose();
|
|
TestLocalDb.DeleteFiles(path);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A brand-new <see cref="SiteStorageService"/> instance over the same site database.
|
|
/// The service now takes an <c>ILocalDb</c> instead of a connection string, so the
|
|
/// single fixture database is shared while each call still yields a fresh service
|
|
/// object — which is what the restart tests below actually vary (the synthetic IDs are
|
|
/// derived per service/repository instance, not per connection).
|
|
/// </summary>
|
|
private SiteStorageService NewStorage()
|
|
=> new(_localDb.Db, NullLogger<SiteStorageService>.Instance);
|
|
|
|
/// <summary>
|
|
/// SiteRuntime-006: an external system stored via <see cref="SiteStorageService"/>
|
|
/// can be read back through the repository — proving the repository's connection
|
|
/// (now obtained from <see cref="SiteStorageService.CreateConnection"/>) is valid.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ExternalSystemRepository_RoundTripsStoredDefinition()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
await storage.StoreExternalSystemAsync(
|
|
"WeatherApi", "https://api.example.com", "ApiKey", "{\"key\":\"x\"}", null);
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
var all = await repo.GetAllExternalSystemsAsync();
|
|
|
|
Assert.Single(all);
|
|
Assert.Equal("WeatherApi", all[0].Name);
|
|
Assert.Equal("https://api.example.com", all[0].EndpointUrl);
|
|
}
|
|
|
|
/// <summary>
|
|
/// ExternalSystemGateway (Timeout): the per-system <c>TimeoutSeconds</c> stored via
|
|
/// <see cref="SiteStorageService.StoreExternalSystemAsync"/> must round-trip through the
|
|
/// site SQLite store and back out via the repository, so site-side calls honor it.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task SiteStorage_ExternalSystem_TimeoutSeconds_RoundTrips()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
await storage.StoreExternalSystemAsync(
|
|
"WeatherApi", "https://api.example.com", "ApiKey", "{\"key\":\"x\"}", null, 7);
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
var found = await repo.GetExternalSystemByNameAsync("WeatherApi");
|
|
|
|
Assert.NotNull(found);
|
|
Assert.Equal(7, found!.TimeoutSeconds);
|
|
}
|
|
|
|
/// <summary>
|
|
/// SiteRuntime-007: the synthetic ID for an external system must be identical when
|
|
/// the storage service and repository are re-created (simulating a process restart).
|
|
/// With the old <see cref="string.GetHashCode()"/> the ID was randomized per process
|
|
/// and a by-ID lookup after a restart would fail.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ExternalSystemRepository_SyntheticId_IsStableAcrossRestart()
|
|
{
|
|
var storage1 = NewStorage();
|
|
await storage1.InitializeAsync();
|
|
await storage1.StoreExternalSystemAsync(
|
|
"StableSystem", "https://x", "None", null, null);
|
|
|
|
var repo1 = new SiteExternalSystemRepository(storage1);
|
|
var idBeforeRestart = (await repo1.GetAllExternalSystemsAsync())[0].Id;
|
|
|
|
// Simulate a process restart — brand-new service + repository instances.
|
|
var storage2 = NewStorage();
|
|
var repo2 = new SiteExternalSystemRepository(storage2);
|
|
var idAfterRestart = (await repo2.GetAllExternalSystemsAsync())[0].Id;
|
|
|
|
Assert.Equal(idBeforeRestart, idAfterRestart);
|
|
|
|
// And the by-ID lookup must succeed using the pre-restart ID.
|
|
var found = await repo2.GetExternalSystemByIdAsync(idBeforeRestart);
|
|
Assert.NotNull(found);
|
|
Assert.Equal("StableSystem", found.Name);
|
|
}
|
|
|
|
// ── ExternalSystemGateway-011: name-keyed repository lookups ──
|
|
|
|
/// <summary>
|
|
/// ExternalSystemGateway-011: the site repository's name-keyed external-system
|
|
/// lookup returns the matching row, and the same synthetic ID as the by-ID path.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ExternalSystemRepository_GetByName_ReturnsMatchingDefinition()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
await storage.StoreExternalSystemAsync(
|
|
"Alpha", "https://alpha.test", "ApiKey", "{\"key\":\"x\"}", null);
|
|
await storage.StoreExternalSystemAsync(
|
|
"Beta", "https://beta.test", "Basic", null, null);
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
|
|
var found = await repo.GetExternalSystemByNameAsync("Beta");
|
|
Assert.NotNull(found);
|
|
Assert.Equal("Beta", found!.Name);
|
|
Assert.Equal("https://beta.test", found.EndpointUrl);
|
|
|
|
// The by-name path must produce the same synthetic ID as the by-id path.
|
|
var byId = await repo.GetExternalSystemByIdAsync(found.Id);
|
|
Assert.NotNull(byId);
|
|
Assert.Equal("Beta", byId!.Name);
|
|
}
|
|
|
|
/// <summary>
|
|
/// ExternalSystemGateway-011: a missing name resolves to <c>null</c>.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ExternalSystemRepository_GetByName_MissingName_ReturnsNull()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
await storage.StoreExternalSystemAsync(
|
|
"Alpha", "https://alpha.test", "ApiKey", null, null);
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
|
|
Assert.Null(await repo.GetExternalSystemByNameAsync("DoesNotExist"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// ExternalSystemGateway-011: the site repository's name-keyed method lookup
|
|
/// returns the method scoped to its parent system, or <c>null</c> for a miss.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task ExternalSystemRepository_GetMethodByName_ResolvesScopedToSystem()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
var methodDefs = "[{\"Name\":\"getData\",\"HttpMethod\":\"GET\",\"Path\":\"/data\"}]";
|
|
await storage.StoreExternalSystemAsync(
|
|
"WeatherApi", "https://api.example.com", "ApiKey", null, methodDefs);
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
var system = await repo.GetExternalSystemByNameAsync("WeatherApi");
|
|
Assert.NotNull(system);
|
|
|
|
var method = await repo.GetMethodByNameAsync(system!.Id, "getData");
|
|
Assert.NotNull(method);
|
|
Assert.Equal("getData", method!.Name);
|
|
Assert.Equal("GET", method.HttpMethod);
|
|
|
|
Assert.Null(await repo.GetMethodByNameAsync(system.Id, "noSuchMethod"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// ExternalSystemGateway-011: the site repository's name-keyed database-connection
|
|
/// lookup returns the matching row, or <c>null</c> for a miss.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task DatabaseConnectionRepository_GetByName_ReturnsMatchingDefinition()
|
|
{
|
|
var storage = NewStorage();
|
|
await storage.InitializeAsync();
|
|
await storage.StoreDatabaseConnectionAsync(
|
|
"Plant", "Server=plant;Database=p;", maxRetries: 3, retryDelay: TimeSpan.FromSeconds(2));
|
|
await storage.StoreDatabaseConnectionAsync(
|
|
"Historian", "Server=hist;Database=h;", maxRetries: 0, retryDelay: TimeSpan.FromSeconds(5));
|
|
|
|
var repo = new SiteExternalSystemRepository(storage);
|
|
|
|
var found = await repo.GetDatabaseConnectionByNameAsync("Historian");
|
|
Assert.NotNull(found);
|
|
Assert.Equal("Historian", found!.Name);
|
|
Assert.Equal("Server=hist;Database=h;", found.ConnectionString);
|
|
Assert.Equal(0, found.MaxRetries);
|
|
|
|
Assert.Null(await repo.GetDatabaseConnectionByNameAsync("DoesNotExist"));
|
|
}
|
|
|
|
// NotificationRepository_SyntheticId_IsStableAcrossRestart was removed 2026-07-10
|
|
// (arch-review 08 §1.3/#23) along with the vestigial SiteNotificationRepository —
|
|
// notification config is central-only and never lives on a site. The synthetic-ID
|
|
// stability guarantee is still exercised by ExternalSystemRepository_SyntheticId_IsStableAcrossRestart.
|
|
}
|