Files
lmxopcua/tests/ZB.MOM.WW.OtOpcUa.Configuration.Tests/StoredProceduresTests.cs
Joseph Doherty 01fd90c178 Phase 1 Streams B–E scaffold + Phase 2 Streams A–C scaffold — 8 new projects with ~70 new tests, all green alongside the 494 v1 IntegrationTests baseline (parity preserved: no v1 tests broken; legacy OtOpcUa.Host untouched). Phase 1 finish: Configuration project (16 entities + 10 enums + DbContext + DesignTimeDbContextFactory + InitialSchema/StoredProcedures/AuthorizationGrants migrations — 8 procs including sp_PublishGeneration with MERGE on ExternalIdReservation per decision #124, sp_RollbackToGeneration cloning rows into a new published generation, sp_ValidateDraft with cross-cluster-namespace + EquipmentUuid-immutability + ZTag/SAPID reservation pre-flight, sp_ComputeGenerationDiff with CHECKSUM-based row signature — plus OtOpcUaNode/OtOpcUaAdmin SQL roles with EXECUTE grants scoped to per-principal-class proc sets and DENY UPDATE/DELETE/INSERT/SELECT on dbo schema); managed DraftValidator covering UNS segment regex, path length, EquipmentUuid immutability across generations, same-cluster namespace binding (decision #122), reservation pre-flight, EquipmentId derivation (decision #125), driver↔namespace compatibility — returning every failing rule in one pass; LiteDB local cache with round-trip + ring pruning + corruption-fast-fail; GenerationApplier with per-entity Added/Removed/Modified diff and dependency-ordered callbacks (namespace → driver → device → equipment → poll-group → tag, Removed before Added); Core project with GenericDriverNodeManager (scaffold for the Phase 2 Galaxy port) and DriverHost lifecycle registry; Server project using Microsoft.Extensions.Hosting BackgroundService replacing TopShelf, with NodeBootstrap that falls back to LiteDB cache when the central DB is unreachable (decision #79); Admin project scaffolded as Blazor Server with Bootstrap 5 sidebar layout, cookie auth, three admin roles (ConfigViewer/ConfigEditor/FleetAdmin), Cluster + Generation services fronting the stored procs. Phase 2 scaffold: Driver.Galaxy.Shared (netstandard2.0) with full MessagePack IPC contract surface — Hello version negotiation, Open/CloseSession, Heartbeat, DiscoverHierarchy + GalaxyObjectInfo/GalaxyAttributeInfo, Read/WriteValues, Subscribe/Unsubscribe/OnDataChange, AlarmSubscribe/Event/Ack, HistoryRead, HostConnectivityStatus, Recycle — plus length-prefixed framing (decision #28) with a 16 MiB cap and thread-safe FrameWriter/FrameReader; Driver.Galaxy.Host (net48) implementing the Tier C cross-cutting protections from driver-stability.md — strict PipeAcl (allow configured server SID only, explicit deny on LocalSystem + Administrators), PipeServer with caller-SID verification via pipe.RunAsClient + WindowsIdentity.GetCurrent and per-process shared-secret Hello, Galaxy-specific MemoryWatchdog (warn at max(1.5×baseline, +200 MB), soft-recycle at max(2×baseline, +200 MB), hard ceiling 1.5 GB, slope ≥5 MB/min over 30-min rolling window), RecyclePolicy (1 soft recycle per hour cap + 03:00 local daily scheduled), PostMortemMmf (1000-entry ring buffer in %ProgramData%\OtOpcUa\driver-postmortem\galaxy.mmf, survives hard crash, readable cross-process), MxAccessHandle : SafeHandle (ReleaseHandle loops Marshal.ReleaseComObject until refcount=0 then calls optional unregister callback), StaPump with responsiveness probe (BlockingCollection dispatcher for Phase 1 — real Win32 GetMessage/DispatchMessage pump slots in with the same semantics when the Galaxy code lift happens), IsExternalInit shim for init setters on .NET 4.8; Driver.Galaxy.Proxy (net10) implementing IDriver + ITagDiscovery forwarding over the IPC channel with MX data-type and security-classification mapping, plus Supervisor pieces — Backoff (5s → 15s → 60s capped, reset-on-stable-run), CircuitBreaker (3 crashes per 5 min opens; 1h → 4h → manual cooldown escalation; sticky alert doesn't auto-clear), HeartbeatMonitor (2s cadence, 3 consecutive misses = host dead per driver-stability.md). Infrastructure: docker SQL Server remapped to host port 14330 to coexist with the native MSSQL14 Galaxy ZB DB instance on 1433; NuGetAuditSuppress applied per-project for two System.Security.Cryptography.Xml advisories that only reach via EF Core Design with PrivateAssets=all (fix ships in 11.0.0-preview); .slnx gains 14 project registrations. Deferred with explicit TODOs in docs/v2/implementation/phase-2-partial-exit-evidence.md: Phase 1 Stream E Admin UI pages (Generations listing + draft-diff-publish, Equipment CRUD with OPC 40010 fields, UNS Areas/Lines tabs, ACLs + permission simulator, Generic JSON config editor, SignalR real-time, Release-Reservation + Merge-Equipment workflows, LDAP login page, AppServer smoke test per decision #142), Phase 2 Stream D (Galaxy MXAccess code lift out of legacy OtOpcUa.Host, dual-service installer, appsettings → DriverConfig migration script, legacy Host deletion — blocked by parity), Phase 2 Stream E (v1 IntegrationTests against v2 topology, Client.CLI walkthrough diff, four 2026-04-13 stability findings regression tests, adversarial review — requires live MXAccess runtime).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 21:35:25 -04:00

223 lines
10 KiB
C#

using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// Happy-path + representative error-path coverage per Task B.2 acceptance. Each test seeds its
/// own cluster + node + credential, creates a draft, exercises one proc, then cleans up at the
/// fixture level (the fixture drops the DB in Dispose).
/// </summary>
[Trait("Category", "StoredProcedures")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class StoredProceduresTests
{
private readonly SchemaComplianceFixture _fixture;
public StoredProceduresTests(SchemaComplianceFixture fixture) => _fixture = fixture;
[Fact]
public void Publish_then_GetCurrent_returns_the_published_generation()
{
using var conn = _fixture.OpenConnection();
var (clusterId, nodeId, _, draftId) = SeedClusterWithDraft(conn, suffix: "pub1");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draftId));
using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_GetCurrentGenerationForCluster @NodeId=@n, @ClusterId=@c";
cmd.Parameters.AddWithValue("n", nodeId);
cmd.Parameters.AddWithValue("c", clusterId);
using var r = cmd.ExecuteReader();
r.Read().ShouldBeTrue("proc should return exactly one row");
r.GetInt64(0).ShouldBe(draftId);
r.GetString(2).ShouldBe("Published");
}
[Fact]
public void GetCurrent_rejects_caller_not_bound_to_node()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, _) = SeedClusterWithDraft(conn, suffix: "unauth");
var ex = Should.Throw<SqlException>(() =>
Exec(conn, "EXEC dbo.sp_GetCurrentGenerationForCluster @NodeId=@n, @ClusterId=@c",
("n", "ghost-node"), ("c", clusterId)));
ex.Message.ShouldContain("Unauthorized");
}
[Fact]
public void Publish_second_draft_supersedes_first()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, draft1) = SeedClusterWithDraft(conn, suffix: "sup");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draft1));
var draft2 = CreateDraft(conn, clusterId);
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draft2));
var status1 = Scalar<string>(conn,
"SELECT Status FROM dbo.ConfigGeneration WHERE GenerationId = @g", ("g", draft1));
var status2 = Scalar<string>(conn,
"SELECT Status FROM dbo.ConfigGeneration WHERE GenerationId = @g", ("g", draft2));
status1.ShouldBe("Superseded");
status2.ShouldBe("Published");
}
[Fact]
public void Publish_rejects_non_draft_generation()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, draftId) = SeedClusterWithDraft(conn, suffix: "twice");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draftId));
var ex = Should.Throw<SqlException>(() =>
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draftId)));
ex.Message.ShouldContain("not in Draft");
}
[Fact]
public void ValidateDraft_rejects_orphan_tag()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, draftId) = SeedClusterWithDraft(conn, suffix: "orphan");
Exec(conn, @"INSERT dbo.Tag (GenerationId, TagId, DriverInstanceId, Name, DataType, AccessLevel, WriteIdempotent, TagConfig)
VALUES (@g, 'tag-1', 'missing-driver', 'X', 'Int32', 'Read', 0, '{}')",
("g", draftId));
var ex = Should.Throw<SqlException>(() =>
Exec(conn, "EXEC dbo.sp_ValidateDraft @DraftGenerationId=@g", ("g", draftId)));
ex.Message.ShouldContain("unresolved DriverInstanceId");
}
[Fact]
public void Rollback_creates_new_published_generation_and_clones_rows()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, draftId) = SeedClusterWithDraft(conn, suffix: "rb");
SeedMinimalDriverRow(conn, draftId, clusterId, driverInstanceId: "drv-a");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draftId));
Exec(conn, "EXEC dbo.sp_RollbackToGeneration @ClusterId=@c, @TargetGenerationId=@g, @Notes='test'",
("c", clusterId), ("g", draftId));
var newlyPublishedCount = Scalar<int>(conn,
@"SELECT COUNT(*) FROM dbo.ConfigGeneration
WHERE ClusterId = @c AND Status = 'Published' AND GenerationId <> @g",
("c", clusterId), ("g", draftId));
newlyPublishedCount.ShouldBe(1);
var driverClonedCount = Scalar<int>(conn,
@"SELECT COUNT(*) FROM dbo.DriverInstance di
JOIN dbo.ConfigGeneration cg ON cg.GenerationId = di.GenerationId
WHERE cg.ClusterId = @c AND cg.Status = 'Published' AND di.DriverInstanceId = 'drv-a'",
("c", clusterId));
driverClonedCount.ShouldBe(1);
}
[Fact]
public void ComputeDiff_returns_Added_for_driver_present_only_in_target()
{
using var conn = _fixture.OpenConnection();
var (clusterId, _, _, draft1) = SeedClusterWithDraft(conn, suffix: "diff");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draft1));
var draft2 = CreateDraft(conn, clusterId);
SeedMinimalDriverRow(conn, draft2, clusterId, driverInstanceId: "drv-added");
Exec(conn, "EXEC dbo.sp_PublishGeneration @ClusterId=@c, @DraftGenerationId=@g",
("c", clusterId), ("g", draft2));
using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_ComputeGenerationDiff @FromGenerationId=@f, @ToGenerationId=@t";
cmd.Parameters.AddWithValue("f", draft1);
cmd.Parameters.AddWithValue("t", draft2);
using var r = cmd.ExecuteReader();
var diffs = new List<(string Table, string Id, string Kind)>();
while (r.Read())
diffs.Add((r.GetString(0), r.GetString(1), r.GetString(2)));
diffs.ShouldContain(d => d.Table == "DriverInstance" && d.Id == "drv-added" && d.Kind == "Added");
}
[Fact]
public void ReleaseReservation_requires_nonempty_reason()
{
using var conn = _fixture.OpenConnection();
var ex = Should.Throw<SqlException>(() =>
Exec(conn, "EXEC dbo.sp_ReleaseExternalIdReservation @Kind='ZTag', @Value='X', @ReleaseReason=''"));
ex.Message.ShouldContain("ReleaseReason is required");
}
// ---- helpers ----
/// <summary>Creates a cluster, one node, one credential bound to the current SUSER_SNAME(), and an empty Draft.</summary>
private static (string ClusterId, string NodeId, string Credential, long DraftId)
SeedClusterWithDraft(SqlConnection conn, string suffix)
{
var clusterId = $"cluster-{suffix}";
var nodeId = $"node-{suffix}-a";
// Every test uses the same SUSER_SNAME() ('sa' by default), and the credential unique index
// is filtered on Enabled=1 across (Kind, Value) globally. To avoid collisions across tests
// sharing one DB, we disable old credentials first.
Exec(conn, "UPDATE dbo.ClusterNodeCredential SET Enabled = 0 WHERE Value = SUSER_SNAME();");
Exec(conn,
@"INSERT dbo.ServerCluster (ClusterId, Name, Enterprise, Site, RedundancyMode, NodeCount, Enabled, CreatedBy)
VALUES (@c, @c, 'zb', @s, 'None', 1, 1, SUSER_SNAME());
INSERT dbo.ClusterNode (NodeId, ClusterId, RedundancyRole, Host, OpcUaPort, DashboardPort, ApplicationUri, ServiceLevelBase, Enabled, CreatedBy)
VALUES (@n, @c, 'Primary', 'localhost', 4840, 5001, CONCAT('urn:localhost:', @s), 200, 1, SUSER_SNAME());
INSERT dbo.ClusterNodeCredential (NodeId, Kind, Value, Enabled, CreatedBy)
VALUES (@n, 'SqlLogin', SUSER_SNAME(), 1, SUSER_SNAME());",
("c", clusterId), ("n", nodeId), ("s", suffix));
var draftId = CreateDraft(conn, clusterId);
return (clusterId, nodeId, "sa", draftId);
}
private static long CreateDraft(SqlConnection conn, string clusterId)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = @"
INSERT dbo.ConfigGeneration (ClusterId, Status, CreatedAt, CreatedBy)
VALUES (@c, 'Draft', SYSUTCDATETIME(), SUSER_SNAME());
SELECT CAST(SCOPE_IDENTITY() AS bigint);";
cmd.Parameters.AddWithValue("c", clusterId);
return (long)cmd.ExecuteScalar()!;
}
private static void SeedMinimalDriverRow(SqlConnection conn, long genId, string clusterId, string driverInstanceId)
{
Exec(conn,
@"INSERT dbo.Namespace (GenerationId, NamespaceId, ClusterId, Kind, NamespaceUri, Enabled)
VALUES (@g, @ns, @c, 'Equipment', 'urn:ns', 1);
INSERT dbo.DriverInstance (GenerationId, DriverInstanceId, ClusterId, NamespaceId, Name, DriverType, Enabled, DriverConfig)
VALUES (@g, @drv, @c, @ns, 'drv', 'ModbusTcp', 1, '{}');",
("g", genId), ("c", clusterId), ("ns", $"ns-{driverInstanceId}"), ("drv", driverInstanceId));
}
private static void Exec(SqlConnection conn, string sql, params (string Name, object Value)[] parameters)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
foreach (var (name, value) in parameters) cmd.Parameters.AddWithValue(name, value);
cmd.ExecuteNonQuery();
}
private static T Scalar<T>(SqlConnection conn, string sql, params (string Name, object Value)[] parameters)
{
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
foreach (var (name, value) in parameters) cmd.Parameters.AddWithValue(name, value);
return (T)cmd.ExecuteScalar()!;
}
}