Files
lmxopcua/tests/ZB.MOM.WW.OtOpcUa.Configuration.Tests/GenerationApplierTests.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

132 lines
5.4 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Apply;
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;
[Trait("Category", "Unit")]
public sealed class GenerationApplierTests
{
private static DraftSnapshot SnapshotWith(
IReadOnlyList<DriverInstance>? drivers = null,
IReadOnlyList<Equipment>? equipment = null,
IReadOnlyList<Tag>? tags = null) => new()
{
GenerationId = 1, ClusterId = "c",
DriverInstances = drivers ?? [],
Equipment = equipment ?? [],
Tags = tags ?? [],
};
private static DriverInstance Driver(string id) =>
new() { DriverInstanceId = id, ClusterId = "c", NamespaceId = "ns", Name = id, DriverType = "ModbusTcp", DriverConfig = "{}" };
private static Equipment Eq(string id, Guid uuid) =>
new() { EquipmentUuid = uuid, EquipmentId = id, DriverInstanceId = "d", UnsLineId = "line-a", Name = id, MachineCode = id };
private static Tag Tag(string id, string name) =>
new() { TagId = id, DriverInstanceId = "d", Name = name, FolderPath = "/a", DataType = "Int32", AccessLevel = TagAccessLevel.Read, TagConfig = "{}" };
[Fact]
public void Diff_from_empty_to_one_driver_five_equipment_fifty_tags_is_all_Added()
{
var uuid = (int i) => Guid.Parse($"00000000-0000-0000-0000-{i:000000000000}");
var equipment = Enumerable.Range(1, 5).Select(i => Eq($"eq-{i}", uuid(i))).ToList();
var tags = Enumerable.Range(1, 50).Select(i => Tag($"tag-{i}", $"T{i}")).ToList();
var diff = GenerationDiffer.Compute(from: null,
to: SnapshotWith(drivers: [Driver("d-1")], equipment: equipment, tags: tags));
diff.Drivers.Count.ShouldBe(1);
diff.Drivers.ShouldAllBe(c => c.Kind == ChangeKind.Added);
diff.Equipment.Count.ShouldBe(5);
diff.Equipment.ShouldAllBe(c => c.Kind == ChangeKind.Added);
diff.Tags.Count.ShouldBe(50);
diff.Tags.ShouldAllBe(c => c.Kind == ChangeKind.Added);
}
[Fact]
public void Diff_flags_single_tag_name_change_as_Modified_only_for_that_tag()
{
var before = SnapshotWith(tags: [Tag("tag-1", "Old"), Tag("tag-2", "Keep")]);
var after = SnapshotWith(tags: [Tag("tag-1", "New"), Tag("tag-2", "Keep")]);
var diff = GenerationDiffer.Compute(before, after);
diff.Tags.Count.ShouldBe(1);
diff.Tags[0].Kind.ShouldBe(ChangeKind.Modified);
diff.Tags[0].LogicalId.ShouldBe("tag-1");
}
[Fact]
public void Diff_flags_Removed_equipment_and_its_tags()
{
var uuid1 = Guid.NewGuid();
var before = SnapshotWith(
equipment: [Eq("eq-1", uuid1), Eq("eq-2", Guid.NewGuid())],
tags: [Tag("tag-1", "A"), Tag("tag-2", "B")]);
var after = SnapshotWith(
equipment: [Eq("eq-2", before.Equipment[1].EquipmentUuid)],
tags: [Tag("tag-2", "B")]);
var diff = GenerationDiffer.Compute(before, after);
diff.Equipment.ShouldContain(c => c.Kind == ChangeKind.Removed && c.LogicalId == "eq-1");
diff.Tags.ShouldContain(c => c.Kind == ChangeKind.Removed && c.LogicalId == "tag-1");
}
[Fact]
public async Task Apply_dispatches_callbacks_in_dependency_order_and_survives_idempotent_retry()
{
var callLog = new List<string>();
var applier = new GenerationApplier(new ApplyCallbacks
{
OnDriver = (c, _) => { callLog.Add($"drv:{c.Kind}:{c.LogicalId}"); return Task.CompletedTask; },
OnEquipment = (c, _) => { callLog.Add($"eq:{c.Kind}:{c.LogicalId}"); return Task.CompletedTask; },
OnTag = (c, _) => { callLog.Add($"tag:{c.Kind}:{c.LogicalId}"); return Task.CompletedTask; },
});
var to = SnapshotWith(
drivers: [Driver("d-1")],
equipment: [Eq("eq-1", Guid.NewGuid())],
tags: [Tag("tag-1", "A")]);
var result1 = await applier.ApplyAsync(from: null, to, CancellationToken.None);
result1.Succeeded.ShouldBeTrue();
// Driver Added must come before Equipment Added must come before Tag Added
var drvIdx = callLog.FindIndex(s => s.StartsWith("drv:Added"));
var eqIdx = callLog.FindIndex(s => s.StartsWith("eq:Added"));
var tagIdx = callLog.FindIndex(s => s.StartsWith("tag:Added"));
drvIdx.ShouldBeLessThan(eqIdx);
eqIdx.ShouldBeLessThan(tagIdx);
// Idempotent retry: re-applying the same diff must not blow up
var countBefore = callLog.Count;
var result2 = await applier.ApplyAsync(from: null, to, CancellationToken.None);
result2.Succeeded.ShouldBeTrue();
callLog.Count.ShouldBe(countBefore * 2);
}
[Fact]
public async Task Apply_collects_errors_from_failing_callback_without_aborting()
{
var applier = new GenerationApplier(new ApplyCallbacks
{
OnTag = (c, _) =>
c.LogicalId == "tag-bad"
? throw new InvalidOperationException("simulated")
: Task.CompletedTask,
});
var to = SnapshotWith(tags: [Tag("tag-ok", "A"), Tag("tag-bad", "B")]);
var result = await applier.ApplyAsync(from: null, to, CancellationToken.None);
result.Succeeded.ShouldBeFalse();
result.Errors.ShouldContain(e => e.Contains("tag-bad") && e.Contains("simulated"));
}
}