Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Actors/InstanceActorSetAttributeTests.cs
Joseph Doherty f2efeb37b7 refactor(sf,site): both stores take ILocalDb instead of a connection string
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
2026-07-20 03:05:45 -04:00

222 lines
8.9 KiB
C#

using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.Logging.Abstractions;
using Akka.TestKit;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
using ZB.MOM.WW.ScadaBridge.TestSupport;
using System.Text.Json;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors;
/// <summary>
/// Regression tests for SiteRuntime-001: Instance.SetAttribute must route writes
/// to the Data Connection Layer for data-sourced attributes instead of persisting
/// a local static override.
/// </summary>
public class InstanceActorSetAttributeTests : TestKit, IDisposable
{
private readonly SiteStorageService _storage;
private readonly ScriptCompilationService _compilationService;
private readonly SharedScriptLibrary _sharedScriptLibrary;
private readonly SiteRuntimeOptions _options;
private readonly TestLocalDb _localDb;
public InstanceActorSetAttributeTests()
{
_localDb = TestLocalDb.CreateTemp("instance-setattr-test");
_storage = new SiteStorageService(
_localDb.Db,
NullLogger<SiteStorageService>.Instance);
_storage.InitializeAsync().GetAwaiter().GetResult();
_compilationService = new ScriptCompilationService(
NullLogger<ScriptCompilationService>.Instance);
_sharedScriptLibrary = new SharedScriptLibrary(
_compilationService, NullLogger<SharedScriptLibrary>.Instance);
_options = new SiteRuntimeOptions();
}
void IDisposable.Dispose()
{
// TestKit teardown first, so no in-flight actor can reach a disposed ILocalDb;
// then dispose the database before deleting — the master connection anchors the WAL.
Shutdown();
var path = _localDb.Path;
_localDb.Dispose();
TestLocalDb.DeleteFiles(path);
}
private IActorRef CreateInstanceActor(string instanceName, FlattenedConfiguration config, IActorRef? dclManager)
{
return ActorOf(Props.Create(() => new InstanceActor(
instanceName,
JsonSerializer.Serialize(config),
_storage,
_compilationService,
_sharedScriptLibrary,
null,
_options,
NullLogger<InstanceActor>.Instance,
dclManager)));
}
/// <summary>
/// Drains the startup <see cref="SubscribeTagsRequest"/> the Instance Actor emits
/// to the DCL in PreStart, then returns the next <see cref="WriteTagRequest"/>.
/// </summary>
private static WriteTagRequest ExpectWriteTag(TestProbe dclProbe)
=> dclProbe.FishForMessage<WriteTagRequest>(_ => true, TimeSpan.FromSeconds(5));
private static FlattenedConfiguration DataSourcedConfig(string instanceName) => new()
{
InstanceUniqueName = instanceName,
Attributes =
[
new ResolvedAttribute
{
CanonicalName = "Setpoint",
Value = "10",
DataType = "Double",
DataSourceReference = "/Motor/Setpoint",
BoundDataConnectionName = "OpcServer1"
}
]
};
[Fact]
public async Task SetAttribute_DataSourcedAttribute_IssuesDclWriteAndDoesNotPersistOverride()
{
var config = DataSourcedConfig("PumpDcl1");
var dclProbe = CreateTestProbe();
var actor = CreateInstanceActor("PumpDcl1", config, dclProbe.Ref);
actor.Tell(new SetStaticAttributeCommand(
"corr-dcl", "PumpDcl1", "Setpoint", "55", DateTimeOffset.UtcNow));
// The Instance Actor must forward a WriteTagRequest to the DCL manager.
var write = ExpectWriteTag(dclProbe);
Assert.Equal("OpcServer1", write.ConnectionName);
Assert.Equal("/Motor/Setpoint", write.TagPath);
Assert.Equal("55", write.Value);
// DCL confirms the write.
dclProbe.Reply(new WriteTagResponse(write.CorrelationId, true, null, DateTimeOffset.UtcNow));
var response = ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
Assert.True(response.Success);
// No static override should be persisted for a data-sourced attribute.
await Task.Delay(300);
var overrides = await _storage.GetStaticOverridesAsync("PumpDcl1");
Assert.Empty(overrides);
}
[Fact]
public void SetAttribute_DataSourcedAttribute_DoesNotOptimisticallyUpdateMemory()
{
var config = DataSourcedConfig("PumpDcl2");
var dclProbe = CreateTestProbe();
var actor = CreateInstanceActor("PumpDcl2", config, dclProbe.Ref);
actor.Tell(new SetStaticAttributeCommand(
"corr-dcl2", "PumpDcl2", "Setpoint", "999", DateTimeOffset.UtcNow));
var write = ExpectWriteTag(dclProbe);
dclProbe.Reply(new WriteTagResponse(write.CorrelationId, true, null, DateTimeOffset.UtcNow));
ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
// In-memory value must still be the original config value — it is only
// updated when the subscription delivers the confirmed device value.
actor.Tell(new GetAttributeRequest("corr-get", "PumpDcl2", "Setpoint", DateTimeOffset.UtcNow));
var get = ExpectMsg<GetAttributeResponse>(TimeSpan.FromSeconds(5));
Assert.Equal("10", get.Value?.ToString());
}
[Fact]
public void SetAttribute_DataSourcedAttribute_DclWriteFailure_ReturnedToCaller()
{
var config = DataSourcedConfig("PumpDcl3");
var dclProbe = CreateTestProbe();
var actor = CreateInstanceActor("PumpDcl3", config, dclProbe.Ref);
actor.Tell(new SetStaticAttributeCommand(
"corr-dcl3", "PumpDcl3", "Setpoint", "42", DateTimeOffset.UtcNow));
var write = ExpectWriteTag(dclProbe);
dclProbe.Reply(new WriteTagResponse(write.CorrelationId, false, "device rejected write", DateTimeOffset.UtcNow));
var response = ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
Assert.False(response.Success);
Assert.Contains("device rejected write", response.ErrorMessage);
}
[Fact]
public async Task SetAttribute_StaticAttribute_StillPersistsOverrideAndDoesNotCallDcl()
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "PumpStatic1",
Attributes =
[
new ResolvedAttribute { CanonicalName = "Label", Value = "Main", DataType = "String" }
]
};
var dclProbe = CreateTestProbe();
var actor = CreateInstanceActor("PumpStatic1", config, dclProbe.Ref);
actor.Tell(new SetStaticAttributeCommand(
"corr-static", "PumpStatic1", "Label", "Backup", DateTimeOffset.UtcNow));
var response = ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
Assert.True(response.Success);
// DCL must NOT receive a write for a static attribute.
dclProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
await Task.Delay(300);
var overrides = await _storage.GetStaticOverridesAsync("PumpStatic1");
Assert.Single(overrides);
Assert.Equal("Backup", overrides["Label"]);
}
// SiteRuntime-025: SetAttribute on an unknown attribute name must NOT
// pollute the in-memory dictionary, NOT publish a synthetic
// AttributeValueChanged, and NOT persist a durable override row.
[Fact]
public async Task SetAttribute_UnknownAttribute_ReturnsFailureAndDoesNotPersistOverride()
{
var config = new FlattenedConfiguration
{
InstanceUniqueName = "PumpUnknown",
Attributes =
[
new ResolvedAttribute { CanonicalName = "Label", Value = "Main", DataType = "String" }
]
};
var dclProbe = CreateTestProbe();
var actor = CreateInstanceActor("PumpUnknown", config, dclProbe.Ref);
actor.Tell(new SetStaticAttributeCommand(
"corr-unknown", "PumpUnknown", "notARealAttr", "x", DateTimeOffset.UtcNow));
var response = ExpectMsg<SetStaticAttributeResponse>(TimeSpan.FromSeconds(5));
Assert.False(response.Success);
Assert.Contains("Unknown attribute", response.ErrorMessage);
Assert.Contains("notARealAttr", response.ErrorMessage);
// The DCL must NOT receive any write — the attribute does not exist.
dclProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
// No durable override row should be persisted for an unknown attribute —
// otherwise the polluting key resurrects on every restart via
// HandleOverridesLoaded.
await Task.Delay(300);
var overrides = await _storage.GetStaticOverridesAsync("PumpUnknown");
Assert.DoesNotContain("notARealAttr", overrides.Keys);
}
}