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>
This commit is contained in:
Joseph Doherty
2026-04-17 21:35:25 -04:00
parent fc0ce36308
commit 01fd90c178
128 changed files with 12352 additions and 4 deletions

View File

@@ -0,0 +1,68 @@
using System.Reflection;
using MessagePack;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Tests;
[Trait("Category", "Unit")]
public sealed class ContractRoundTripTests
{
/// <summary>
/// Every MessagePack contract in the Shared project must round-trip. Byte-for-byte equality
/// on re-serialization proves the contract is deterministic — critical for the Hello
/// version-negotiation hash and for debugging wire dumps.
/// </summary>
[Fact]
public void All_MessagePackObject_contracts_round_trip_byte_for_byte()
{
var contractTypes = typeof(Hello).Assembly.GetTypes()
.Where(t => t.GetCustomAttribute<MessagePackObjectAttribute>() is not null)
.ToList();
contractTypes.Count.ShouldBeGreaterThan(15, "scan should find all contracts");
foreach (var type in contractTypes)
{
var instance = Activator.CreateInstance(type);
var bytes1 = MessagePackSerializer.Serialize(type, instance);
var hydrated = MessagePackSerializer.Deserialize(type, bytes1);
var bytes2 = MessagePackSerializer.Serialize(type, hydrated);
bytes2.ShouldBe(bytes1, $"{type.Name} did not round-trip byte-for-byte");
}
}
[Fact]
public void Hello_default_reports_current_protocol_version()
{
var h = new Hello { PeerName = "Proxy", SharedSecret = "x" };
h.ProtocolMajor.ShouldBe(Hello.CurrentMajor);
h.ProtocolMinor.ShouldBe(Hello.CurrentMinor);
}
[Fact]
public void OpenSessionRequest_round_trips_values()
{
var req = new OpenSessionRequest { DriverInstanceId = "gal-1", DriverConfigJson = "{\"x\":1}" };
var bytes = MessagePackSerializer.Serialize(req);
var hydrated = MessagePackSerializer.Deserialize<OpenSessionRequest>(bytes);
hydrated.DriverInstanceId.ShouldBe("gal-1");
hydrated.DriverConfigJson.ShouldBe("{\"x\":1}");
}
[Fact]
public void Contracts_reference_only_BCL_and_MessagePack()
{
var asm = typeof(Hello).Assembly;
var references = asm.GetReferencedAssemblies()
.Select(n => n.Name!)
.Where(n => !n.StartsWith("System.") && n != "mscorlib" && n != "netstandard")
.ToList();
// Only MessagePack should appear outside BCL — no System.Text.Json, no EF, no AspNetCore.
references.ShouldAllBe(n => n == "MessagePack" || n == "MessagePack.Annotations");
}
}

View File

@@ -0,0 +1,74 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Tests;
[Trait("Category", "Unit")]
public sealed class FramingTests
{
[Fact]
public async Task FrameWriter_FrameReader_round_trip_preserves_kind_and_body()
{
using var ms = new MemoryStream();
using (var writer = new FrameWriter(ms, leaveOpen: true))
{
await writer.WriteAsync(MessageKind.Hello,
new Hello { PeerName = "p", SharedSecret = "s" }, TestContext.Current.CancellationToken);
await writer.WriteAsync(MessageKind.Heartbeat,
new Heartbeat { SequenceNumber = 7, UtcUnixMs = 42 }, TestContext.Current.CancellationToken);
}
ms.Position = 0;
using var reader = new FrameReader(ms, leaveOpen: true);
var f1 = (await reader.ReadFrameAsync(TestContext.Current.CancellationToken))!.Value;
f1.Kind.ShouldBe(MessageKind.Hello);
FrameReader.Deserialize<Hello>(f1.Body).PeerName.ShouldBe("p");
var f2 = (await reader.ReadFrameAsync(TestContext.Current.CancellationToken))!.Value;
f2.Kind.ShouldBe(MessageKind.Heartbeat);
FrameReader.Deserialize<Heartbeat>(f2.Body).SequenceNumber.ShouldBe(7L);
var eof = await reader.ReadFrameAsync(TestContext.Current.CancellationToken);
eof.ShouldBeNull();
}
[Fact]
public async Task FrameReader_rejects_frames_larger_than_the_cap()
{
using var ms = new MemoryStream();
var evilLen = Framing.MaxFrameBodyBytes + 1;
ms.Write(new byte[]
{
(byte)((evilLen >> 24) & 0xFF),
(byte)((evilLen >> 16) & 0xFF),
(byte)((evilLen >> 8) & 0xFF),
(byte)( evilLen & 0xFF),
}, 0, 4);
ms.WriteByte((byte)MessageKind.Hello);
ms.Position = 0;
using var reader = new FrameReader(ms, leaveOpen: true);
await Should.ThrowAsync<InvalidDataException>(() =>
reader.ReadFrameAsync(TestContext.Current.CancellationToken).AsTask());
}
private static class TestContext
{
public static TestContextHelper Current { get; } = new();
}
private sealed class TestContextHelper
{
public CancellationToken CancellationToken => CancellationToken.None;
}
}
file static class TaskExtensions
{
public static Task AsTask<T>(this ValueTask<T> vt) => vt.AsTask();
public static Task AsTask<T>(this Task<T> t) => t;
}

View File

@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="1.1.0"/>
<PackageReference Include="Shouldly" Version="4.3.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.csproj"/>
</ItemGroup>
<ItemGroup>
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-37gx-xxp4-5rgx"/>
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-w3x6-4m5h-cxqf"/>
</ItemGroup>
</Project>