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,18 @@
@* Root Blazor component. *@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>OtOpcUa Admin</title>
<base href="/"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"/>
<link rel="stylesheet" href="app.css"/>
<HeadOutlet/>
</head>
<body>
<Routes/>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="_framework/blazor.web.js"></script>
</body>
</html>

View File

@@ -0,0 +1,17 @@
@* ScadaLink-parity sidebar layout per decision #102 (Bootstrap 5, dark sidebar, main content area). *@
@inherits LayoutComponentBase
<div class="d-flex" style="min-height: 100vh;">
<nav class="bg-dark text-light p-3" style="width: 220px;">
<h5 class="mb-4">OtOpcUa Admin</h5>
<ul class="nav flex-column">
<li class="nav-item"><a class="nav-link text-light" href="/clusters">Clusters</a></li>
<li class="nav-item"><a class="nav-link text-light" href="/generations">Generations</a></li>
<li class="nav-item"><a class="nav-link text-light" href="/equipment">Equipment</a></li>
<li class="nav-item"><a class="nav-link text-light" href="/acls">ACLs</a></li>
</ul>
</nav>
<main class="flex-grow-1 p-4">
@Body
</main>
</div>

View File

@@ -0,0 +1,42 @@
@page "/clusters"
@using ZB.MOM.WW.OtOpcUa.Admin.Services
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@inject ClusterService ClusterSvc
<h1 class="mb-4">Clusters</h1>
@if (_clusters is null)
{
<p>Loading…</p>
}
else if (_clusters.Count == 0)
{
<p class="text-muted">No clusters yet. Use the stored-proc <code>sp_PublishGeneration</code> workflow to bootstrap.</p>
}
else
{
<table class="table table-hover">
<thead><tr><th>ClusterId</th><th>Name</th><th>Enterprise/Site</th><th>RedundancyMode</th><th>Enabled</th></tr></thead>
<tbody>
@foreach (var c in _clusters)
{
<tr>
<td><code>@c.ClusterId</code></td>
<td>@c.Name</td>
<td>@c.Enterprise / @c.Site</td>
<td>@c.RedundancyMode</td>
<td>@(c.Enabled ? "Yes" : "No")</td>
</tr>
}
</tbody>
</table>
}
@code {
private List<ServerCluster>? _clusters;
protected override async Task OnInitializedAsync()
{
_clusters = await ClusterSvc.ListAsync(CancellationToken.None);
}
}

View File

@@ -0,0 +1,16 @@
@page "/"
<h1 class="mb-4">OtOpcUa fleet overview</h1>
<p class="text-muted">Phase 1 scaffold — full dashboard lands in Phase 1 Stream E completion.</p>
<div class="row g-3">
<div class="col-md-4">
<div class="card"><div class="card-body"><h5 class="card-title">Clusters</h5><a href="/clusters" class="btn btn-primary btn-sm">Manage</a></div></div>
</div>
<div class="col-md-4">
<div class="card"><div class="card-body"><h5 class="card-title">Generations</h5><a href="/generations" class="btn btn-primary btn-sm">Manage</a></div></div>
</div>
<div class="col-md-4">
<div class="card"><div class="card-body"><h5 class="card-title">Equipment</h5><a href="/equipment" class="btn btn-primary btn-sm">Manage</a></div></div>
</div>
</div>

View File

@@ -0,0 +1,11 @@
@using Microsoft.AspNetCore.Components.Routing
@using ZB.MOM.WW.OtOpcUa.Admin.Components.Layout
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)"><p>Not found.</p></LayoutView>
</NotFound>
</Router>

View File

@@ -0,0 +1,10 @@
@using System.Net.Http
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using ZB.MOM.WW.OtOpcUa.Admin
@using ZB.MOM.WW.OtOpcUa.Admin.Components
@using ZB.MOM.WW.OtOpcUa.Admin.Components.Layout

View File

@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Serilog;
using ZB.MOM.WW.OtOpcUa.Admin.Components;
using ZB.MOM.WW.OtOpcUa.Admin.Services;
using ZB.MOM.WW.OtOpcUa.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((ctx, cfg) => cfg
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.File("logs/otopcua-admin-.log", rollingInterval: RollingInterval.Day));
builder.Services.AddRazorComponents().AddInteractiveServerComponents();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.Cookie.Name = "OtOpcUa.Admin";
o.LoginPath = "/login";
o.ExpireTimeSpan = TimeSpan.FromHours(8);
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("CanEdit", p => p.RequireRole(AdminRoles.ConfigEditor, AdminRoles.FleetAdmin))
.AddPolicy("CanPublish", p => p.RequireRole(AdminRoles.FleetAdmin));
builder.Services.AddDbContext<OtOpcUaConfigDbContext>(opt =>
opt.UseSqlServer(builder.Configuration.GetConnectionString("ConfigDb")
?? throw new InvalidOperationException("ConnectionStrings:ConfigDb not configured")));
builder.Services.AddScoped<ClusterService>();
builder.Services.AddScoped<GenerationService>();
var app = builder.Build();
app.UseSerilogRequestLogging();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
await app.RunAsync();
// Public for WebApplicationFactory testability.
public partial class Program;

View File

@@ -0,0 +1,16 @@
namespace ZB.MOM.WW.OtOpcUa.Admin.Services;
/// <summary>
/// The three admin roles per <c>admin-ui.md</c> §"Admin Roles" — mapped from LDAP groups at
/// sign-in. Each role has a fixed set of capabilities (cluster CRUD, draft → publish, fleet
/// admin). The ACL-driven runtime permissions (<c>NodePermissions</c>) govern OPC UA clients;
/// these roles govern the Admin UI itself.
/// </summary>
public static class AdminRoles
{
public const string ConfigViewer = "ConfigViewer";
public const string ConfigEditor = "ConfigEditor";
public const string FleetAdmin = "FleetAdmin";
public static IReadOnlyList<string> All => [ConfigViewer, ConfigEditor, FleetAdmin];
}

View File

@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Admin.Services;
/// <summary>
/// Cluster CRUD surface used by the Blazor pages. Writes go through stored procs in later
/// phases; Phase 1 reads via EF Core directly (DENY SELECT on <c>dbo</c> schema means this
/// service connects as a DB owner during dev — production swaps in a read-only view grant).
/// </summary>
public sealed class ClusterService(OtOpcUaConfigDbContext db)
{
public Task<List<ServerCluster>> ListAsync(CancellationToken ct) =>
db.ServerClusters.AsNoTracking().OrderBy(c => c.ClusterId).ToListAsync(ct);
public Task<ServerCluster?> FindAsync(string clusterId, CancellationToken ct) =>
db.ServerClusters.AsNoTracking().FirstOrDefaultAsync(c => c.ClusterId == clusterId, ct);
public async Task<ServerCluster> CreateAsync(ServerCluster cluster, string createdBy, CancellationToken ct)
{
cluster.CreatedAt = DateTime.UtcNow;
cluster.CreatedBy = createdBy;
db.ServerClusters.Add(cluster);
await db.SaveChangesAsync(ct);
return cluster;
}
}

View File

@@ -0,0 +1,71 @@
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
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.Admin.Services;
/// <summary>
/// Owns the draft → diff → publish workflow (decision #89). Publish + rollback call into the
/// stored procedures; diff queries <c>sp_ComputeGenerationDiff</c>.
/// </summary>
public sealed class GenerationService(OtOpcUaConfigDbContext db)
{
public async Task<ConfigGeneration> CreateDraftAsync(string clusterId, string createdBy, CancellationToken ct)
{
var gen = new ConfigGeneration
{
ClusterId = clusterId,
Status = GenerationStatus.Draft,
CreatedBy = createdBy,
CreatedAt = DateTime.UtcNow,
};
db.ConfigGenerations.Add(gen);
await db.SaveChangesAsync(ct);
return gen;
}
public Task<List<ConfigGeneration>> ListRecentAsync(string clusterId, int limit, CancellationToken ct) =>
db.ConfigGenerations.AsNoTracking()
.Where(g => g.ClusterId == clusterId)
.OrderByDescending(g => g.GenerationId)
.Take(limit)
.ToListAsync(ct);
public async Task PublishAsync(string clusterId, long draftGenerationId, string? notes, CancellationToken ct)
{
await db.Database.ExecuteSqlRawAsync(
"EXEC dbo.sp_PublishGeneration @ClusterId = {0}, @DraftGenerationId = {1}, @Notes = {2}",
[clusterId, draftGenerationId, (object?)notes ?? DBNull.Value],
ct);
}
public async Task RollbackAsync(string clusterId, long targetGenerationId, string? notes, CancellationToken ct)
{
await db.Database.ExecuteSqlRawAsync(
"EXEC dbo.sp_RollbackToGeneration @ClusterId = {0}, @TargetGenerationId = {1}, @Notes = {2}",
[clusterId, targetGenerationId, (object?)notes ?? DBNull.Value],
ct);
}
public async Task<List<DiffRow>> ComputeDiffAsync(long from, long to, CancellationToken ct)
{
var results = new List<DiffRow>();
await using var conn = (SqlConnection)db.Database.GetDbConnection();
if (conn.State != System.Data.ConnectionState.Open) await conn.OpenAsync(ct);
await using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_ComputeGenerationDiff @FromGenerationId = @f, @ToGenerationId = @t";
cmd.Parameters.AddWithValue("@f", from);
cmd.Parameters.AddWithValue("@t", to);
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
results.Add(new DiffRow(reader.GetString(0), reader.GetString(1), reader.GetString(2)));
return results;
}
}
public sealed record DiffRow(string TableName, string LogicalId, string ChangeKind);

View File

@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Admin</RootNamespace>
<AssemblyName>OtOpcUa.Admin</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.0"/>
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Configuration\ZB.MOM.WW.OtOpcUa.Configuration.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>

View File

@@ -0,0 +1,8 @@
{
"ConnectionStrings": {
"ConfigDb": "Server=localhost,14330;Database=OtOpcUaConfig;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;"
},
"Serilog": {
"MinimumLevel": "Information"
}
}

View File

@@ -0,0 +1,3 @@
/* OtOpcUa Admin — ScadaLink-parity palette. Keep it minimal here; lean on Bootstrap 5. */
body { background-color: #f5f6fa; }
.nav-link.active { background-color: rgba(255,255,255,0.1); border-radius: 4px; }