diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DanglingReferenceSqlServerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DanglingReferenceSqlServerTests.cs new file mode 100644 index 000000000..c617d7618 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DanglingReferenceSqlServerTests.cs @@ -0,0 +1,165 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; + +/// +/// lmxopcua#1049 (#998 C-10 follow-up) on the real provider. The raw-tree parent links are LOGICAL foreign keys, +/// so the race the review described — user A's "is the device empty?" check passes, user B adds a tag under it, +/// A deletes the device — really commits both on SQL Server, and the deploy gate's DanglingReference rule is +/// what names the orphan. And because the deploy reads its whole snapshot under SNAPSHOT isolation, a +/// concurrent, perfectly consistent commit landing MID-read cannot make the gate report a dangling row that never +/// existed in any committed state (a parent read before the commit, its child read after it). +/// +[Trait("Category", "SchemaCompliance")] +[Collection(nameof(SchemaComplianceCollection))] +public sealed class DanglingReferenceSqlServerTests +{ + private readonly SchemaComplianceFixture _fixture; + + /// Initializes a new instance of the class. + /// The migrated test database. + public DanglingReferenceSqlServerTests(SchemaComplianceFixture fixture) => _fixture = fixture; + + private OtOpcUaConfigDbContext NewContext(params IInterceptor[] interceptors) => new( + new DbContextOptionsBuilder().UseSqlServer(_fixture.ConnectionString) + .AddInterceptors(interceptors).Options); + + private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"; + + private static Tag NewTag(string tagId, string deviceId) => new() + { + TagId = tagId, DeviceId = deviceId, Name = tagId, DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}", + }; + + /// Seeds cluster → driver → device; returns (driverId, deviceId). + private (string DriverId, string DeviceId) SeedDevice() + { + var clusterId = Id("cl")[..30]; + var driverId = Id("di"); + var deviceId = Id("dev"); + using var db = NewContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "dev", NodeCount = 1, + RedundancyMode = RedundancyMode.None, CreatedBy = "t1049", + }); + db.DriverInstances.Add(new DriverInstance + { + DriverInstanceId = driverId, ClusterId = clusterId, Name = Id("drv"), DriverType = "Modbus", DriverConfig = "{}", + }); + db.Devices.Add(new Device { DeviceId = deviceId, DriverInstanceId = driverId, Name = Id("plc"), DeviceConfig = "{}" }); + db.SaveChanges(); + return (driverId, deviceId); + } + + private static IEnumerable DanglingFor(DraftSnapshot draft, string tagId) => + DraftValidator.Validate(draft).Where(e => e.Code == DraftValidator.DanglingReferenceCode && e.Context == tagId); + + /// + /// The review's race, interleaved on two real connections: A's emptiness check, B's tag add, A's device delete. + /// Both commit (no FK); the deploy snapshot then names the orphaned tag. + /// + [Fact] + public async Task A_device_deleted_while_a_tag_is_added_under_it_is_reported_by_the_deploy_gate() + { + var ct = TestContext.Current.CancellationToken; + var (_, deviceId) = SeedDevice(); + var tagId = Id("tag"); + + await using (var userA = NewContext()) + { + await using var tx = await userA.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + (await userA.Tags.AnyAsync(t => t.DeviceId == deviceId, ct)).ShouldBeFalse(); // "the device is empty" + + await using (var userB = NewContext()) + { + userB.Tags.Add(NewTag(tagId, deviceId)); + await userB.SaveChangesAsync(ct); // commits while A's check result is already stale + } + + userA.Devices.Remove(await userA.Devices.SingleAsync(d => d.DeviceId == deviceId, ct)); + await userA.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } + + await using var deploy = NewContext(); + var draft = await DraftSnapshotFactory.FromConfigDbAsync(deploy, ct); + + draft.Tags.ShouldContain(t => t.TagId == tagId); + draft.Devices.ShouldNotContain(d => d.DeviceId == deviceId); + DanglingFor(draft, tagId).ShouldHaveSingleItem().Message.ShouldContain($"Device '{deviceId}'"); + } + + /// + /// A device and its tag added together in ONE commit that lands after the snapshot read has passed the Devices + /// table but before it reads Tags: under the factory's SNAPSHOT transaction neither is seen, so no false + /// DanglingReference. Positive control: the same interleave inside a READ COMMITTED transaction (the + /// factory then reads in the caller's transaction) DOES report the tag as dangling — so the isolation, not the + /// timing, is what keeps the gate honest; and a read after the commit sees both rows and no error. + /// + [Fact] + public async Task A_consistent_commit_landing_mid_read_is_never_reported_as_dangling_under_snapshot_isolation() + { + var ct = TestContext.Current.CancellationToken; + var (driverId, deviceId) = SeedDevice(); + + // Snapshot read (the deploy path): the concurrent commit is invisible. + var (lateDevice, lateTag) = (Id("dev"), Id("tag")); + await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice, lateTag))) + { + var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); + draft.Tags.ShouldNotContain(t => t.TagId == lateTag); + DanglingFor(draft, lateTag).ShouldBeEmpty(); + } + + // Positive control 1: the same interleave read unisolated produces exactly the false positive. + var (lateDevice2, lateTag2) = (Id("dev"), Id("tag")); + await using (var db = NewContext(new CommitDeviceAndTagWhenDeviceMaterialises(_fixture.ConnectionString, deviceId, driverId, lateDevice2, lateTag2))) + { + await using var tx = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); + draft.Tags.ShouldContain(t => t.TagId == lateTag2); + DanglingFor(draft, lateTag2).ShouldHaveSingleItem(); + } + + // Positive control 2: both commits really landed, and a read started afterwards sees them whole. + await using var after = NewContext(); + var later = await DraftSnapshotFactory.FromConfigDbAsync(after, ct); + later.Tags.ShouldContain(t => t.TagId == lateTag); + later.Devices.ShouldContain(d => d.DeviceId == lateDevice); + DanglingFor(later, lateTag).ShouldBeEmpty(); + DanglingFor(later, lateTag2).ShouldBeEmpty(); + } + + /// + /// When the snapshot read materialises the seeded device (Devices is read before Tags), commits a NEW device and a + /// tag under it — one consistent transaction — on a separate connection. + /// + private sealed class CommitDeviceAndTagWhenDeviceMaterialises( + string connectionString, string triggerDeviceId, string driverId, string newDeviceId, string newTagId) + : IMaterializationInterceptor + { + private int _fired; + + public object InitializedInstance(MaterializationInterceptionData materializationData, object entity) + { + if (entity is Device d && d.DeviceId == triggerDeviceId && Interlocked.Exchange(ref _fired, 1) == 0) + { + using var other = new OtOpcUaConfigDbContext( + new DbContextOptionsBuilder().UseSqlServer(connectionString).Options); + other.Devices.Add(new Device { DeviceId = newDeviceId, DriverInstanceId = driverId, Name = newDeviceId, DeviceConfig = "{}" }); + other.Tags.Add(NewTag(newTagId, newDeviceId)); + other.SaveChanges(); + } + + return entity; + } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ClusterNodeEditConcurrencySqlServerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ClusterNodeEditConcurrencySqlServerTests.cs new file mode 100644 index 000000000..d93e9bab5 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ClusterNodeEditConcurrencySqlServerTests.cs @@ -0,0 +1,202 @@ +using Bunit; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages; + +/// +/// lmxopcua#1049 (#998 C-9 follow-up): the NodeEdit / ClusterEdit pages against a REAL SQL Server, where +/// rowversion is generated and the Restrict FKs exist (the InMemory provider has neither). A save carrying +/// the token the page loaded is refused once another user has changed the row — the other user's edit survives — +/// and a save with a current token succeeds; a node that was deployed to deletes together with its +/// NodeDeploymentState rows; a cluster that still has nodes is not deleted and the page says why. +/// +[Collection(nameof(AdminUiSqlServerCollection))] +public sealed class ClusterNodeEditConcurrencySqlServerTests : BunitContext +{ + private const string ModalSelector = ".modal-dialog"; + private readonly AdminUiSqlServerFixture _sql; + + /// Registers the fixture's SQL-backed context factory (when the server is available). + /// The AdminUI SQL Server fixture. + public ClusterNodeEditConcurrencySqlServerTests(AdminUiSqlServerFixture sql) + { + _sql = sql; + JSInterop.Setup("otDialog.activate", _ => true).SetResult(true); + JSInterop.SetupVoid("otDialog.update", _ => true).SetVoidResult(); + JSInterop.SetupVoid("otDialog.deactivate", _ => true).SetVoidResult(); + if (sql.SkipReason is null) Services.AddSingleton(sql.Factory); + Services.AddSingleton(new FakeAuth()); + } + + private static string Id(string prefix) => $"{prefix}-{Guid.NewGuid():N}"[..(prefix.Length + 21)]; + + private string SeedCluster() + { + var clusterId = Id("C"); + using var db = _sql.Factory.CreateDbContext(); + db.ServerClusters.Add(new ServerCluster + { + ClusterId = clusterId, Name = Id("Cluster"), Enterprise = "zb", Site = "s1", NodeCount = 1, + RedundancyMode = RedundancyMode.None, CreatedBy = "t1049", + }); + db.SaveChanges(); + return clusterId; + } + + private string SeedNode(string clusterId) + { + var nodeId = Id("n"); + using var db = _sql.Factory.CreateDbContext(); + db.ClusterNodes.Add(new ClusterNode + { + NodeId = nodeId, ClusterId = clusterId, Host = "h-original", ApplicationUri = "urn:" + nodeId, CreatedBy = "t1049", + }); + db.SaveChanges(); + return nodeId; + } + + /// Another user's committed edit, on its own context. + private void ConcurrentEdit(Action edit) + { + using var db = _sql.Factory.CreateDbContext(); + edit(db); + db.SaveChanges(); + } + + /// NodeEdit: a stale token is refused with the concurrency message; the other user's edit survives. + [SqlServerFact] + public void NodeEdit_save_with_a_stale_token_is_refused() + { + var clusterId = SeedCluster(); + var nodeId = SeedNode(clusterId); + var cut = Render(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId)); + cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original")); + + ConcurrentEdit(db => db.ClusterNodes.Single(n => n.NodeId == nodeId).Host = "h-other-user"); + + cut.Find("#host").Change("h-stale"); + cut.Find("form").Submit(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this node")); + using var db = _sql.Factory.CreateDbContext(); + db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-other-user"); + } + + /// Positive control: with no concurrent edit the same save goes through. + [SqlServerFact] + public void NodeEdit_save_with_a_current_token_succeeds() + { + var clusterId = SeedCluster(); + var nodeId = SeedNode(clusterId); + var cut = Render(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId)); + cut.WaitForAssertion(() => cut.Find("#host").GetAttribute("value").ShouldBe("h-original")); + + cut.Find("#host").Change("h-saved"); + cut.Find("form").Submit(); + + cut.WaitForAssertion(() => + { + using var db = _sql.Factory.CreateDbContext(); + db.ClusterNodes.AsNoTracking().Single(n => n.NodeId == nodeId).Host.ShouldBe("h-saved"); + }); + cut.Markup.ShouldNotContain("Another user changed this node"); + } + + /// ClusterEdit: a stale token is refused; positive control on the same page after a reload-equivalent re-render. + [SqlServerFact] + public void ClusterEdit_save_with_a_stale_token_is_refused() + { + var clusterId = SeedCluster(); + var cut = Render(p => p.Add(x => x.ClusterId, clusterId)); + cut.WaitForAssertion(() => cut.Find("#notes")); + + ConcurrentEdit(db => db.ServerClusters.Single(c => c.ClusterId == clusterId).Notes = "other user"); + + cut.Find("#notes").Change("stale"); + cut.Find("form").Submit(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Another user changed this cluster")); + using (var db = _sql.Factory.CreateDbContext()) + db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("other user"); + + var fresh = Render(p => p.Add(x => x.ClusterId, clusterId)); + fresh.WaitForAssertion(() => fresh.Find("#notes")); + fresh.Find("#notes").Change("current"); + fresh.Find("form").Submit(); + fresh.WaitForAssertion(() => + { + using var db = _sql.Factory.CreateDbContext(); + db.ServerClusters.AsNoTracking().Single(c => c.ClusterId == clusterId).Notes.ShouldBe("current"); + }); + } + + /// A node with NodeDeploymentState rows (Restrict FK) deletes together with them — no raw FK error. + [SqlServerFact] + public void NodeEdit_delete_of_a_deployed_node_removes_its_deployment_states() + { + var clusterId = SeedCluster(); + var nodeId = SeedNode(clusterId); + var deploymentId = Guid.NewGuid(); + using (var seed = _sql.Factory.CreateDbContext()) + { + seed.Deployments.Add(new Deployment { DeploymentId = deploymentId, RevisionHash = new string('a', 64), CreatedBy = "t1049" }); + seed.NodeDeploymentStates.Add(new NodeDeploymentState { NodeId = nodeId, DeploymentId = deploymentId, Status = NodeDeploymentStatus.Applied }); + seed.SaveChanges(); + } + + var cut = Render(p => p.Add(x => x.ClusterId, clusterId).Add(x => x.NodeId, nodeId)); + cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger")); + cut.Find("button.btn-outline-danger").Click(); + cut.Find(".modal-footer .btn-danger").Click(); + + cut.WaitForAssertion(() => + { + using var db = _sql.Factory.CreateDbContext(); + db.ClusterNodes.Any(n => n.NodeId == nodeId).ShouldBeFalse(); + db.NodeDeploymentStates.Any(s => s.NodeId == nodeId).ShouldBeFalse(); + db.Deployments.Any(d => d.DeploymentId == deploymentId).ShouldBeTrue(); // the deployment itself is history, kept + }); + } + + /// A cluster that still has nodes is not deleted (Restrict FK) and the page names the reason; positive control: an empty one deletes. + [SqlServerFact] + public void ClusterEdit_delete_of_a_cluster_with_nodes_is_refused_with_a_reason() + { + var busy = SeedCluster(); + SeedNode(busy); + var cut = Render(p => p.Add(x => x.ClusterId, busy)); + cut.WaitForAssertion(() => cut.Find("button.btn-outline-danger")); + cut.Find("button.btn-outline-danger").Click(); + cut.Find(".modal-footer .btn-danger").Click(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("remove them first")); + using (var db = _sql.Factory.CreateDbContext()) + db.ServerClusters.Any(c => c.ClusterId == busy).ShouldBeTrue(); + + var empty = SeedCluster(); + var cut2 = Render(p => p.Add(x => x.ClusterId, empty)); + cut2.WaitForAssertion(() => cut2.Find("button.btn-outline-danger")); + cut2.Find("button.btn-outline-danger").Click(); + cut2.Find(".modal-footer .btn-danger").Click(); + cut2.WaitForAssertion(() => + { + using var db = _sql.Factory.CreateDbContext(); + db.ServerClusters.Any(c => c.ClusterId == empty).ShouldBeFalse(); + }); + } + + private sealed class FakeAuth : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => + Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal( + new System.Security.Claims.ClaimsIdentity("test")))); + } +}