Compare commits

...

8 Commits

Author SHA1 Message Date
6863cc4652 Merge pull request 'Task #219 follow-up — close AlarmConditionState child-NodeId + Part 9 event-propagation gaps' (#198) from task-219-followup-alarm-wiring into v2 2026-04-21 00:24:41 -04:00
Joseph Doherty
8221fac8c1 Task #219 follow-up — close AlarmConditionState child-NodeId + event-propagation gaps
PR #197 surfaced two integration-level wiring gaps in DriverNodeManager's
MarkAsAlarmCondition path; this commit fixes both and upgrades the integration
test to assert them end-to-end.

Fix 1 — addressable child nodes: AlarmConditionState inherits ~50 typed children
(Severity / Message / ActiveState / AckedState / EnabledState / …). The stack
was leaving them with Foundation-namespace NodeIds (type-declaration defaults) or
shared ns=0 counter allocations, so client Read on a child returned
BadNodeIdUnknown. Pass assignNodeIds=true to alarm.Create, then walk the condition
subtree and rewrite each descendant's NodeId symbolically as
  {condition-full-ref}.{symbolic-path}
in the node manager's namespace. Stable, unique, and collision-free across
multiple alarm instances in the same driver.

Fix 2 — event propagation to Server.EventNotifier: OPC UA Part 9 event
propagation relies on the alarm condition being reachable from Objects/Server
via HasNotifier. Call CustomNodeManager2.AddRootNotifier(alarm) after registering
the condition so subscriptions placed on Server-object EventNotifier receive the
ReportEvent calls ConditionSink emits per-transition.

Test upgrades in AlarmSubscribeIntegrationTests:
  - Driver_alarm_transition_updates_server_side_AlarmConditionState_node — now
    asserts Severity == 700, Message text, and ActiveState.Id == true through
    the OPC UA client (previously scoped out as BadNodeIdUnknown).
  - New: Driver_alarm_event_flows_to_client_subscription_on_Server_EventNotifier
    subscribes an OPC UA event monitor on ObjectIds.Server, fires a driver
    transition, and waits for the AlarmConditionType event to be delivered,
    asserting Message + Severity fields. Previously scoped out as "Part 9 event
    propagation out of reach."

Regression checks: 239 server tests pass (+1 new event-subscription test),
195 Core tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 00:22:02 -04:00
bc44711dca Merge pull request 'Task #219 — Server-integration test coverage for IAlarmSource dispatch path' (#197) from task-219-alarm-history-integration into v2 2026-04-20 23:36:26 -04:00
Joseph Doherty
acf31fd943 Task #219 — Server-integration test coverage for IAlarmSource dispatch path
Adds AlarmSubscribeIntegrationTests alongside HistoryReadIntegrationTests so both
optional driver capabilities — IHistoryProvider (already covered) and IAlarmSource
(new) — have end-to-end coverage that boots the full OPC UA stack and exercises the
wiring path from driver event → GenericDriverNodeManager forwarder → DriverNodeManager
ConditionSink through a real Session.

Two tests:
  1. Driver_alarm_transition_updates_server_side_AlarmConditionState_node — a fake
     IAlarmSource declares an IsAlarm=true variable, calls MarkAsAlarmCondition in
     DiscoverAsync, and fires OnAlarmEvent for that source. Verifies the
     client can browse the alarm condition node at FullReference + ".Condition"
     and reads the DisplayName back through Session.Read.
  2. Each_IsAlarm_variable_registers_its_own_condition_node_in_the_driver_namespace —
     two IsAlarm variables each produce their own addressable AlarmConditionState,
     proving the CapturingHandle per-variable registration works.

Scoped-out (documented in the class docstring): the stack exposes AlarmConditionState's
inherited children (Severity / Message / ActiveState / …) with Foundation-namespace
NodeIds that DriverNodeManager does not add to its predefined-node index, so reading
those child attributes through a client returns BadNodeIdUnknown. OPC UA Part 9 event
propagation (subscribe-on-Server + ConditionRefresh) is likewise out of reach until
the node manager wires HasNotifier + child-node registration. The existing Core-level
GenericDriverNodeManagerTests cover the in-memory alarm-sink fan-out semantics.

Full Server.Tests suite: 238 passed, 0 failed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 23:33:45 -04:00
7e143e293b Merge pull request 'Driver-instance bootstrap pipeline (#248) — DriverInstance rows materialise as live IDriver instances' (#196) from phase-7-fu-248-driver-bootstrap into v2 2026-04-20 22:52:12 -04:00
Joseph Doherty
2cb22598d6 Drop accidentally-committed LiteDB cache file + add to .gitignore
The previous commit (#248 wiring) inadvertently picked up
src/ZB.MOM.WW.OtOpcUa.Server/config_cache.db — generated by the live smoke
re-run that proved the bootstrapper works. Remove from tracking + ignore
going forward so future runs don't dirty the working tree.
2026-04-20 22:49:48 -04:00
Joseph Doherty
3d78033ea4 Driver-instance bootstrap pipeline (#248) — DriverInstance rows materialise as live IDriver instances
Closes the gap surfaced by Phase 7 live smoke (#240): DriverInstance rows in
the central config DB had no path to materialise as live IDriver instances in
DriverHost, so virtual-tag scripts read BadNodeIdUnknown for every tag.

## DriverFactoryRegistry (Core.Hosting)
Process-singleton type-name → factory map. Each driver project's static
Register call pre-loads its factory at Program.cs startup; the bootstrapper
looks up by DriverInstance.DriverType + invokes with (DriverInstanceId,
DriverConfig JSON). Case-insensitive; duplicate-type registration throws.

## GalaxyProxyDriverFactoryExtensions.Register (Driver.Galaxy.Proxy)
Static helper — no Microsoft.Extensions.DependencyInjection dep, keeps the
driver project free of DI machinery. Parses DriverConfig JSON for PipeName +
SharedSecret + ConnectTimeoutMs. DriverInstanceId from the row wins over JSON
per the schema's UX_DriverInstance_Generation_LogicalId.

## DriverInstanceBootstrapper (Server)
After NodeBootstrap loads the published generation: queries DriverInstance
rows scoped to that generation, looks up the factory per row, constructs +
DriverHost.RegisterAsync (which calls InitializeAsync). Per plan decision
#12 (driver isolation), failure of one driver doesn't prevent others —
logs ERR + continues + returns the count actually registered. Unknown
DriverType (factory not registered) logs WRN + skips so a missing-assembly
deployment doesn't take down the whole server.

## Wired into OpcUaServerService.ExecuteAsync
After NodeBootstrap.LoadCurrentGenerationAsync, before
PopulateEquipmentContentAsync + Phase7Composer.PrepareAsync. The Phase 7
chain now sees a populated DriverHost so CachedTagUpstreamSource has an
upstream feed.

## Live evidence on the dev box
Re-ran the Phase 7 smoke from task #240. Pre-#248 vs post-#248:
  Equipment namespace snapshots loaded for 0/0 driver(s)  ← before
  Equipment namespace snapshots loaded for 1/1 driver(s)  ← after

Galaxy.Host pipe ACL denied our SID (env-config issue documented in
docs/ServiceHosting.md, NOT a code issue) — the bootstrapper logged it as
"failed to initialize, driver state will reflect Faulted" and continued past
the failure exactly per plan #12. The rest of the pipeline (Equipment walker
+ Phase 7 composer) ran to completion.

## Tests — 5 new DriverFactoryRegistryTests
Register + TryGet round-trip, case-insensitive lookup, duplicate-type throws,
null-arg guards, RegisteredTypes snapshot. Pure functions; no DI/DB needed.
The bootstrapper's DB-query path is exercised by the live smoke (#240) which
operators run before each release.
2026-04-20 22:49:25 -04:00
48a43ac96e Merge pull request 'Phase 7 follow-up #240 — Live OPC UA E2E smoke runbook + seed + first-run evidence' (#195) from phase-7-fu-240-e2e-smoke into v2 2026-04-20 22:34:43 -04:00
11 changed files with 676 additions and 1 deletions

3
.gitignore vendored
View File

@@ -30,3 +30,6 @@ packages/
.claude/
.local/
# LiteDB local config cache (Phase 6.1 Stream D — runtime artifact, not source)
src/ZB.MOM.WW.OtOpcUa.Server/config_cache.db

View File

@@ -0,0 +1,64 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Core.Hosting;
/// <summary>
/// Process-singleton registry of <see cref="IDriver"/> factories keyed by
/// <c>DriverInstance.DriverType</c> string. Each driver project ships a DI
/// extension (e.g. <c>services.AddGalaxyProxyDriverFactory()</c>) that registers
/// its factory at startup; the bootstrapper looks up the factory by
/// <c>DriverInstance.DriverType</c> + invokes it with the row's
/// <c>DriverInstanceId</c> + <c>DriverConfig</c> JSON.
/// </summary>
/// <remarks>
/// Closes the gap surfaced by task #240 live smoke — DriverInstance rows in
/// the central config DB had no path to materialise as registered <see cref="IDriver"/>
/// instances. The factory registry is the seam.
/// </remarks>
public sealed class DriverFactoryRegistry
{
private readonly Dictionary<string, Func<string, string, IDriver>> _factories
= new(StringComparer.OrdinalIgnoreCase);
private readonly object _lock = new();
/// <summary>
/// Register a factory for <paramref name="driverType"/>. Throws if a factory is
/// already registered for that type — drivers are singletons by type-name in
/// this process.
/// </summary>
/// <param name="driverType">Matches <c>DriverInstance.DriverType</c>.</param>
/// <param name="factory">
/// Receives <c>(driverInstanceId, driverConfigJson)</c>; returns a new
/// <see cref="IDriver"/>. Must NOT call <see cref="IDriver.InitializeAsync"/>
/// itself — the bootstrapper calls it via <see cref="DriverHost.RegisterAsync"/>
/// so the host's per-driver retry semantics apply uniformly.
/// </param>
public void Register(string driverType, Func<string, string, IDriver> factory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverType);
ArgumentNullException.ThrowIfNull(factory);
lock (_lock)
{
if (_factories.ContainsKey(driverType))
throw new InvalidOperationException(
$"DriverType '{driverType}' factory already registered for this process");
_factories[driverType] = factory;
}
}
/// <summary>
/// Try to look up the factory for <paramref name="driverType"/>. Returns null
/// if no driver assembly registered one — bootstrapper logs + skips so a
/// missing-assembly deployment doesn't take down the whole server.
/// </summary>
public Func<string, string, IDriver>? TryGet(string driverType)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverType);
lock (_lock) return _factories.GetValueOrDefault(driverType);
}
public IReadOnlyCollection<string> RegisteredTypes
{
get { lock (_lock) return [.. _factories.Keys]; }
}
}

View File

@@ -0,0 +1,59 @@
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Proxy;
/// <summary>
/// Static factory registration helper for <see cref="GalaxyProxyDriver"/>. Server's
/// Program.cs calls <see cref="Register"/> once at startup; the bootstrapper (task #248)
/// then materialises Galaxy DriverInstance rows from the central config DB into live
/// driver instances. No dependency on Microsoft.Extensions.DependencyInjection so the
/// driver project stays free of DI machinery.
/// </summary>
public static class GalaxyProxyDriverFactoryExtensions
{
public const string DriverTypeName = "Galaxy";
/// <summary>
/// Register the Galaxy driver factory in the supplied <see cref="DriverFactoryRegistry"/>.
/// Throws if 'Galaxy' is already registered — single-instance per process.
/// </summary>
public static void Register(DriverFactoryRegistry registry)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, CreateInstance);
}
internal static GalaxyProxyDriver CreateInstance(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
// DriverConfig column is a JSON object that mirrors GalaxyProxyOptions.
// Required: PipeName, SharedSecret. Optional: ConnectTimeoutMs (defaults to 10s).
// The DriverInstanceId from the row wins over any value in the JSON — the row
// is the authoritative identity per the schema's UX_DriverInstance_Generation_LogicalId.
using var doc = JsonDocument.Parse(driverConfigJson);
var root = doc.RootElement;
string pipeName = root.TryGetProperty("PipeName", out var p) && p.ValueKind == JsonValueKind.String
? p.GetString()!
: throw new InvalidOperationException(
$"GalaxyProxyDriver config for '{driverInstanceId}' missing required PipeName");
string sharedSecret = root.TryGetProperty("SharedSecret", out var s) && s.ValueKind == JsonValueKind.String
? s.GetString()!
: throw new InvalidOperationException(
$"GalaxyProxyDriver config for '{driverInstanceId}' missing required SharedSecret");
var connectTimeout = root.TryGetProperty("ConnectTimeoutMs", out var t) && t.ValueKind == JsonValueKind.Number
? TimeSpan.FromMilliseconds(t.GetInt32())
: TimeSpan.FromSeconds(10);
return new GalaxyProxyDriver(new GalaxyProxyOptions
{
DriverInstanceId = driverInstanceId,
PipeName = pipeName,
SharedSecret = sharedSecret,
ConnectTimeout = connectTimeout,
});
}
}

View File

@@ -13,6 +13,7 @@
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core.Abstractions\ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core\ZB.MOM.WW.OtOpcUa.Core.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Shared.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian\ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.csproj"/>
</ItemGroup>

View File

@@ -0,0 +1,88 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
namespace ZB.MOM.WW.OtOpcUa.Server;
/// <summary>
/// Task #248 — bridges the gap surfaced by the Phase 7 live smoke (#240) where
/// <c>DriverInstance</c> rows in the central config DB had no path to materialise
/// as live <see cref="Core.Abstractions.IDriver"/> instances in <see cref="DriverHost"/>.
/// Called from <c>OpcUaServerService.ExecuteAsync</c> after the bootstrap loads
/// the published generation, before address-space build.
/// </summary>
/// <remarks>
/// <para>
/// Per row: looks up the <c>DriverType</c> string in
/// <see cref="DriverFactoryRegistry"/>, calls the factory with the row's
/// <c>DriverInstanceId</c> + <c>DriverConfig</c> JSON to construct an
/// <see cref="Core.Abstractions.IDriver"/>, then registers via
/// <see cref="DriverHost.RegisterAsync"/> which invokes <c>InitializeAsync</c>
/// under the host's lifecycle semantics.
/// </para>
/// <para>
/// Unknown <c>DriverType</c> = factory not registered = log a warning and skip.
/// Per plan decision #12 (driver isolation), failure to construct or initialize
/// one driver doesn't prevent the rest from coming up — the Server keeps serving
/// the others' subtrees + the operator can fix the misconfigured row + republish
/// to retry.
/// </para>
/// </remarks>
public sealed class DriverInstanceBootstrapper(
DriverFactoryRegistry factories,
DriverHost driverHost,
IServiceScopeFactory scopeFactory,
ILogger<DriverInstanceBootstrapper> logger)
{
public async Task<int> RegisterDriversFromGenerationAsync(long generationId, CancellationToken ct)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<OtOpcUaConfigDbContext>();
var rows = await db.DriverInstances.AsNoTracking()
.Where(d => d.GenerationId == generationId && d.Enabled)
.ToListAsync(ct).ConfigureAwait(false);
var registered = 0;
var skippedUnknownType = 0;
var failedInit = 0;
foreach (var row in rows)
{
var factory = factories.TryGet(row.DriverType);
if (factory is null)
{
logger.LogWarning(
"DriverInstance {Id} skipped — DriverType '{Type}' has no registered factory (known: {Known})",
row.DriverInstanceId, row.DriverType, string.Join(",", factories.RegisteredTypes));
skippedUnknownType++;
continue;
}
try
{
var driver = factory(row.DriverInstanceId, row.DriverConfig);
await driverHost.RegisterAsync(driver, row.DriverConfig, ct).ConfigureAwait(false);
registered++;
logger.LogInformation(
"DriverInstance {Id} ({Type}) registered + initialized", row.DriverInstanceId, row.DriverType);
}
catch (Exception ex)
{
// Plan decision #12 — driver isolation. Log + continue so one bad row
// doesn't deny the OPC UA endpoint to the rest of the fleet.
logger.LogError(ex,
"DriverInstance {Id} ({Type}) failed to initialize — driver state will reflect Faulted; operator can republish to retry",
row.DriverInstanceId, row.DriverType);
failedInit++;
}
}
logger.LogInformation(
"DriverInstanceBootstrapper: gen={Gen} registered={Registered} skippedUnknownType={Skipped} failedInit={Failed}",
generationId, registered, skippedUnknownType, failedInit);
return registered;
}
}

View File

@@ -371,7 +371,20 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
BrowseName = new QualifiedName(_variable.BrowseName.Name + "_Condition", _owner.NamespaceIndex),
DisplayName = new LocalizedText(info.SourceName),
};
alarm.Create(_owner.SystemContext, alarm.NodeId, alarm.BrowseName, alarm.DisplayName, false);
// assignNodeIds=true makes the stack allocate NodeIds for every inherited
// AlarmConditionState child (Severity / Message / ActiveState / AckedState /
// EnabledState / …). Without this the children keep Foundation (ns=0) type-
// declaration NodeIds that aren't in the node manager's predefined-node index.
// The newly-allocated NodeIds default to ns=0 via the shared identifier
// counter — we remap them to the node manager's namespace below so client
// Read/Browse on children resolves against the predefined-node dictionary.
alarm.Create(_owner.SystemContext, alarm.NodeId, alarm.BrowseName, alarm.DisplayName, true);
// Assign every descendant a stable, collision-free NodeId in the node manager's
// namespace keyed on the condition path. The stack's default assignNodeIds path
// allocates from a shared ns=0 counter and does not update parent→child
// references when we remap, so we do the rename up front, symbolically:
// {condition-full-ref}/{symbolic-path-under-condition}
AssignSymbolicDescendantIds(alarm, alarm.NodeId, _owner.NamespaceIndex);
alarm.SourceName.Value = info.SourceName;
alarm.Severity.Value = (ushort)MapSeverity(info.InitialSeverity);
alarm.Message.Value = new LocalizedText(info.InitialDescription ?? info.SourceName);
@@ -382,10 +395,20 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
alarm.AckedState.Id.Value = true;
alarm.ActiveState.Value = new LocalizedText("Inactive");
alarm.ActiveState.Id.Value = false;
// Enable ConditionRefresh support so clients that connect *after* a transition
// can pull the current retained-condition snapshot.
alarm.ClientUserId.Value = string.Empty;
alarm.BranchId.Value = NodeId.Null;
_variable.AddChild(alarm);
_owner.AddPredefinedNode(_owner.SystemContext, alarm);
// Part 9 event propagation: AddRootNotifier registers the alarm as an event
// source reachable from Objects/Server so subscriptions placed on Server-object
// EventNotifier receive the ReportEvent calls ConditionSink.OnTransition emits.
// Without this the Report fires but has no subscribers to deliver to.
_owner.AddRootNotifier(alarm);
return new ConditionSink(_owner, alarm);
}
}
@@ -398,6 +421,26 @@ public sealed class DriverNodeManager : CustomNodeManager2, IAddressSpaceBuilder
AlarmSeverity.Critical => 900,
_ => 500,
};
// After alarm.Create(assignNodeIds=true), every descendant has *some* NodeId but
// they default to ns=0 via the shared identifier counter — allocations from two
// different alarms collide when we move them into the driver's namespace. Rewriting
// symbolically based on the condition path gives each descendant a unique, stable
// NodeId in the node manager's namespace. Browse + Read resolve against the current
// NodeId because the stack's CustomNodeManager2.Browse traverses NodeState.Children
// (NodeState references) and uses each child's current .NodeId in the response.
private static void AssignSymbolicDescendantIds(
NodeState parent, NodeId parentNodeId, ushort namespaceIndex)
{
var children = new List<BaseInstanceState>();
parent.GetChildren(null!, children);
foreach (var child in children)
{
child.NodeId = new NodeId(
$"{parentNodeId.Identifier}.{child.SymbolicName}", namespaceIndex);
AssignSymbolicDescendantIds(child, child.NodeId, namespaceIndex);
}
}
}
private sealed class ConditionSink(DriverNodeManager owner, AlarmConditionState alarm)

View File

@@ -18,6 +18,7 @@ public sealed class OpcUaServerService(
DriverHost driverHost,
OpcUaApplicationHost applicationHost,
DriverEquipmentContentRegistry equipmentContentRegistry,
DriverInstanceBootstrapper driverBootstrapper,
Phase7Composer phase7Composer,
IServiceScopeFactory scopeFactory,
ILogger<OpcUaServerService> logger) : BackgroundService
@@ -37,6 +38,13 @@ public sealed class OpcUaServerService(
// address space until the first publish, then the registry fills on next restart.
if (result.GenerationId is { } gen)
{
// Task #248 — register IDriver instances from the published DriverInstance
// rows BEFORE the equipment-content load + Phase 7 compose, so the rest of
// the pipeline sees a populated DriverHost. Without this step Phase 7's
// CachedTagUpstreamSource has no upstream feed + virtual-tag scripts read
// BadNodeIdUnknown for every tag path (gap surfaced by task #240 smoke).
await driverBootstrapper.RegisterDriversFromGenerationAsync(gen, stoppingToken);
await PopulateEquipmentContentAsync(gen, stoppingToken);
// Phase 7 follow-up #246 — load Script + VirtualTag + ScriptedAlarm rows,

View File

@@ -9,6 +9,7 @@ using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.LocalCache;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Proxy;
using ZB.MOM.WW.OtOpcUa.Server;
using ZB.MOM.WW.OtOpcUa.Server.OpcUa;
using ZB.MOM.WW.OtOpcUa.Server.Phase7;
@@ -89,6 +90,18 @@ builder.Services.AddSingleton<ILocalConfigCache>(_ => new LiteDbConfigCache(opti
builder.Services.AddSingleton<DriverHost>();
builder.Services.AddSingleton<NodeBootstrap>();
// Task #248 — driver-instance bootstrap pipeline. DriverFactoryRegistry is the
// type-name → factory map; each driver project's static Register call pre-loads
// its factory so the bootstrapper can materialise DriverInstance rows from the
// central DB into live IDriver instances.
builder.Services.AddSingleton<DriverFactoryRegistry>(_ =>
{
var registry = new DriverFactoryRegistry();
GalaxyProxyDriverFactoryExtensions.Register(registry);
return registry;
});
builder.Services.AddSingleton<DriverInstanceBootstrapper>();
// ADR-001 Option A wiring — the registry is the handoff between OpcUaServerService's
// bootstrap-time population pass + OpcUaApplicationHost's StartAsync walker invocation.
// DriverEquipmentContentRegistry.Get is the equipmentContentLookup delegate that PR #155

View File

@@ -34,6 +34,7 @@
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core.VirtualTags\ZB.MOM.WW.OtOpcUa.Core.VirtualTags.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms\ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian\ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Proxy\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Proxy.csproj"/>
<ProjectReference Include="..\ZB.MOM.WW.OtOpcUa.Analyzers\ZB.MOM.WW.OtOpcUa.Analyzers.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false"/>
</ItemGroup>

View File

@@ -0,0 +1,322 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using ZB.MOM.WW.OtOpcUa.Server.OpcUa;
using ZB.MOM.WW.OtOpcUa.Server.Security;
namespace ZB.MOM.WW.OtOpcUa.Server.Tests;
/// <summary>
/// Task #219 — end-to-end server integration coverage for the <see cref="IAlarmSource"/>
/// dispatch path. Boots the full OPC UA stack + a fake <see cref="IAlarmSource"/> driver,
/// opens a client session, raises a driver-side transition, and asserts it propagates
/// through <c>GenericDriverNodeManager</c>'s alarm forwarder into
/// <c>DriverNodeManager.ConditionSink</c>, updates the server-side
/// <c>AlarmConditionState</c> child attributes (Severity / Message / ActiveState), and
/// flows out to an OPC UA subscription on the Server object's EventNotifier.
///
/// Companion to <see cref="HistoryReadIntegrationTests"/> which covers the
/// <see cref="IHistoryProvider"/> dispatch path; together they close the server-side
/// integration gap for optional driver capabilities (plan decision #62).
/// </summary>
[Trait("Category", "Integration")]
public sealed class AlarmSubscribeIntegrationTests : IAsyncLifetime
{
private static readonly int Port = 48700 + Random.Shared.Next(0, 99);
private readonly string _endpoint = $"opc.tcp://localhost:{Port}/OtOpcUaAlarmTest";
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-alarm-test-{Guid.NewGuid():N}");
private DriverHost _driverHost = null!;
private OpcUaApplicationHost _server = null!;
private AlarmDriver _driver = null!;
public async ValueTask InitializeAsync()
{
_driverHost = new DriverHost();
_driver = new AlarmDriver();
await _driverHost.RegisterAsync(_driver, "{}", CancellationToken.None);
var options = new OpcUaServerOptions
{
EndpointUrl = _endpoint,
ApplicationName = "OtOpcUaAlarmTest",
ApplicationUri = "urn:OtOpcUa:Server:AlarmTest",
PkiStoreRoot = _pkiRoot,
AutoAcceptUntrustedClientCertificates = true,
HealthEndpointsEnabled = false,
};
_server = new OpcUaApplicationHost(options, _driverHost, new DenyAllUserAuthenticator(),
NullLoggerFactory.Instance, NullLogger<OpcUaApplicationHost>.Instance);
await _server.StartAsync(CancellationToken.None);
}
public async ValueTask DisposeAsync()
{
await _server.DisposeAsync();
await _driverHost.DisposeAsync();
try { Directory.Delete(_pkiRoot, recursive: true); } catch { /* best-effort */ }
}
[Fact]
public async Task Driver_alarm_transition_updates_server_side_AlarmConditionState_node()
{
using var session = await OpenSessionAsync();
var nsIndex = (ushort)session.NamespaceUris.GetIndex("urn:OtOpcUa:alarm-driver");
_driver.RaiseAlarm(new AlarmEventArgs(
SubscriptionHandle: new FakeHandle("sub"),
SourceNodeId: "Tank.HiHi",
ConditionId: "cond-1",
AlarmType: "Active",
Message: "Level exceeded upper-upper",
Severity: AlarmSeverity.High,
SourceTimestampUtc: DateTime.UtcNow));
// The alarm-condition node's identifier is the driver full-reference + ".Condition"
// (DriverNodeManager.VariableHandle.MarkAsAlarmCondition). Server-side state changes
// are applied synchronously under DriverNodeManager.Lock inside ConditionSink.OnTransition,
// so by the time RaiseAlarm returns the node state has been flushed.
var conditionNodeId = new NodeId("Tank.HiHi.Condition", nsIndex);
// Browse the condition node for the well-known Part-9 child variables. The stack
// materializes Severity / Message / ActiveState / AckedState as children below the
// AlarmConditionState; their NodeIds are allocated by the stack so we discover them
// by BrowseName rather than guessing.
var browseDescriptions = new BrowseDescriptionCollection
{
new()
{
NodeId = conditionNodeId,
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true,
NodeClassMask = 0,
ResultMask = (uint)BrowseResultMask.All,
},
};
session.Browse(null, null, 0, browseDescriptions, out var browseResults, out _);
var children = browseResults[0].References
.ToDictionary(r => r.BrowseName.Name,
r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris),
StringComparer.Ordinal);
children.ShouldContainKey("Severity");
children.ShouldContainKey("Message");
children.ShouldContainKey("ActiveState");
// Severity / Message / ActiveState.Id reflect the driver-fired transition — verifies
// the forwarder → ConditionSink.OnTransition → alarm.ClearChangeMasks pipeline
// landed the new values in addressable child nodes. DriverNodeManager's
// AssignSymbolicDescendantIds keeps each child reachable under the node manager's
// namespace so Read resolves against the predefined-node dictionary.
var severity = session.ReadValue(children["Severity"]);
var message = session.ReadValue(children["Message"]);
severity.Value.ShouldBe((ushort)700); // AlarmSeverity.High → 700 (MapSeverity)
((LocalizedText)message.Value).Text.ShouldBe("Level exceeded upper-upper");
// ActiveState exposes its boolean Id as a HasProperty child.
var activeBrowse = new BrowseDescriptionCollection
{
new()
{
NodeId = children["ActiveState"],
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HasProperty,
IncludeSubtypes = true,
ResultMask = (uint)BrowseResultMask.All,
},
};
session.Browse(null, null, 0, activeBrowse, out var activeChildren, out _);
var idRef = activeChildren[0].References.Single(r => r.BrowseName.Name == "Id");
var activeId = session.ReadValue(ExpandedNodeId.ToNodeId(idRef.NodeId, session.NamespaceUris));
activeId.Value.ShouldBe(true);
}
[Fact]
public async Task Driver_alarm_event_flows_to_client_subscription_on_Server_EventNotifier()
{
// AddRootNotifier registers the AlarmConditionState as a Server-object notifier
// source, so a subscription with an EventFilter on Server receives the
// ReportEvent calls ConditionSink emits per-transition.
using var session = await OpenSessionAsync();
var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 };
session.AddSubscription(subscription);
await subscription.CreateAsync();
var received = new List<EventFieldList>();
var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var filter = new EventFilter();
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventId);
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.SourceName);
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Message);
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Severity);
filter.WhereClause = new ContentFilter();
filter.WhereClause.Push(FilterOperator.OfType,
new LiteralOperand { Value = new Variant(ObjectTypeIds.AlarmConditionType) });
var item = new MonitoredItem(subscription.DefaultItem)
{
StartNodeId = ObjectIds.Server,
AttributeId = Attributes.EventNotifier,
NodeClass = NodeClass.Object,
SamplingInterval = 0,
QueueSize = 100,
Filter = filter,
};
item.Notification += (_, e) =>
{
if (e.NotificationValue is EventFieldList fields)
{
lock (received) { received.Add(fields); gate.TrySetResult(); }
}
};
subscription.AddItem(item);
await subscription.ApplyChangesAsync();
// Give the publish loop a tick to establish before firing.
await Task.Delay(200);
_driver.RaiseAlarm(new AlarmEventArgs(
new FakeHandle("sub"), "Tank.HiHi", "cond-x", "Active",
"High-high tripped", AlarmSeverity.Critical, DateTime.UtcNow));
var delivered = await Task.WhenAny(gate.Task, Task.Delay(TimeSpan.FromSeconds(10)));
delivered.ShouldBe(gate.Task, "alarm event must arrive at the client within 10s");
EventFieldList first;
lock (received) first = received[0];
// Filter field order: 0=EventId, 1=SourceName, 2=Message, 3=Severity.
((LocalizedText)first.EventFields[2].Value).Text.ShouldBe("High-high tripped");
first.EventFields[3].Value.ShouldBe((ushort)900); // Critical → 900
}
[Fact]
public async Task Each_IsAlarm_variable_registers_its_own_condition_node_in_the_driver_namespace()
{
// Tag-scoped alarm wiring: DiscoverAsync declares two IsAlarm variables and calls
// MarkAsAlarmCondition on each. The server-side DriverNodeManager wraps each call in
// a CapturingHandle that creates a sibling AlarmConditionState + registers a sink
// under the driver full-reference. Browse should show both condition nodes with
// distinct NodeIds using the FullReference + ".Condition" convention.
using var session = await OpenSessionAsync();
var nsIndex = (ushort)session.NamespaceUris.GetIndex("urn:OtOpcUa:alarm-driver");
_driver.RaiseAlarm(new AlarmEventArgs(
new FakeHandle("sub"), "Tank.HiHi", "c", "Active", "first", AlarmSeverity.High,
DateTime.UtcNow));
var attrs = new ReadValueIdCollection
{
new() { NodeId = new NodeId("Tank.HiHi.Condition", nsIndex), AttributeId = Attributes.DisplayName },
new() { NodeId = new NodeId("Heater.OverTemp.Condition", nsIndex), AttributeId = Attributes.DisplayName },
};
session.Read(null, 0, TimestampsToReturn.Neither, attrs, out var results, out _);
results[0].StatusCode.Code.ShouldBe(StatusCodes.Good);
results[1].StatusCode.Code.ShouldBe(StatusCodes.Good);
((LocalizedText)results[0].Value).Text.ShouldBe("Tank.HiHi");
((LocalizedText)results[1].Value).Text.ShouldBe("Heater.OverTemp");
}
private async Task<ISession> OpenSessionAsync()
{
var cfg = new ApplicationConfiguration
{
ApplicationName = "OtOpcUaAlarmTestClient",
ApplicationUri = "urn:OtOpcUa:AlarmTestClient",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(_pkiRoot, "client-own"),
SubjectName = "CN=OtOpcUaAlarmTestClient",
},
TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(_pkiRoot, "client-issuers") },
TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(_pkiRoot, "client-trusted") },
RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(_pkiRoot, "client-rejected") },
AutoAcceptUntrustedCertificates = true,
AddAppCertToTrustedStore = true,
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
};
await cfg.Validate(ApplicationType.Client);
cfg.CertificateValidator.CertificateValidation += (_, e) => e.Accept = true;
var instance = new ApplicationInstance { ApplicationConfiguration = cfg, ApplicationType = ApplicationType.Client };
await instance.CheckApplicationInstanceCertificate(true, CertificateFactory.DefaultKeySize);
var selected = CoreClientUtils.SelectEndpoint(cfg, _endpoint, useSecurity: false);
var endpointConfig = EndpointConfiguration.Create(cfg);
var configuredEndpoint = new ConfiguredEndpoint(null, selected, endpointConfig);
return await Session.Create(cfg, configuredEndpoint, false, "OtOpcUaAlarmTestClientSession", 60000,
new UserIdentity(new AnonymousIdentityToken()), null);
}
/// <summary>
/// Stub <see cref="IAlarmSource"/> driver. <see cref="DiscoverAsync"/> emits two alarm-
/// bearing variables (so tag-scoped fan-out can be asserted); <see cref="RaiseAlarm"/>
/// fires <see cref="OnAlarmEvent"/> exactly like a real driver would.
/// </summary>
private sealed class AlarmDriver : IDriver, ITagDiscovery, IAlarmSource
{
public string DriverInstanceId => "alarm-driver";
public string DriverType => "AlarmStub";
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
public Task InitializeAsync(string driverConfigJson, CancellationToken ct) => Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken ct) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken ct) => Task.CompletedTask;
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
public long GetMemoryFootprint() => 0;
public Task FlushOptionalCachesAsync(CancellationToken ct) => Task.CompletedTask;
public Task DiscoverAsync(IAddressSpaceBuilder builder, CancellationToken ct)
{
var tank = builder.Folder("Tank", "Tank");
var hiHi = tank.Variable("HiHi", "HiHi", new DriverAttributeInfo(
"Tank.HiHi", DriverDataType.Boolean, false, null,
SecurityClassification.FreeAccess, false, IsAlarm: true));
hiHi.MarkAsAlarmCondition(new AlarmConditionInfo(
"Tank.HiHi", AlarmSeverity.High, "High-high alarm"));
var heater = builder.Folder("Heater", "Heater");
var ot = heater.Variable("OverTemp", "OverTemp", new DriverAttributeInfo(
"Heater.OverTemp", DriverDataType.Boolean, false, null,
SecurityClassification.FreeAccess, false, IsAlarm: true));
ot.MarkAsAlarmCondition(new AlarmConditionInfo(
"Heater.OverTemp", AlarmSeverity.Critical, "Over-temperature"));
return Task.CompletedTask;
}
public void RaiseAlarm(AlarmEventArgs args) => OnAlarmEvent?.Invoke(this, args);
public Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
IReadOnlyList<string> _, CancellationToken __)
=> Task.FromResult<IAlarmSubscriptionHandle>(new FakeHandle("sub"));
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle _, CancellationToken __)
=> Task.CompletedTask;
public Task AcknowledgeAsync(
IReadOnlyList<AlarmAcknowledgeRequest> _, CancellationToken __)
=> Task.CompletedTask;
}
private sealed class FakeHandle(string diagnosticId) : IAlarmSubscriptionHandle
{
public string DiagnosticId { get; } = diagnosticId;
}
}

View File

@@ -0,0 +1,73 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
namespace ZB.MOM.WW.OtOpcUa.Server.Tests;
/// <summary>
/// Task #248 — covers the <see cref="DriverFactoryRegistry"/> contract that
/// <see cref="DriverInstanceBootstrapper"/> consumes.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DriverFactoryRegistryTests
{
private static IDriver FakeDriver(string id, string config) => new FakeIDriver(id);
[Fact]
public void Register_then_TryGet_returns_factory()
{
var r = new DriverFactoryRegistry();
r.Register("MyDriver", FakeDriver);
r.TryGet("MyDriver").ShouldNotBeNull();
r.TryGet("Nope").ShouldBeNull();
}
[Fact]
public void Register_is_case_insensitive()
{
var r = new DriverFactoryRegistry();
r.Register("Galaxy", FakeDriver);
r.TryGet("galaxy").ShouldNotBeNull();
r.TryGet("GALAXY").ShouldNotBeNull();
}
[Fact]
public void Register_duplicate_type_throws()
{
var r = new DriverFactoryRegistry();
r.Register("Galaxy", FakeDriver);
Should.Throw<InvalidOperationException>(() => r.Register("Galaxy", FakeDriver));
}
[Fact]
public void Register_null_args_rejected()
{
var r = new DriverFactoryRegistry();
Should.Throw<ArgumentException>(() => r.Register("", FakeDriver));
Should.Throw<ArgumentNullException>(() => r.Register("X", null!));
}
[Fact]
public void RegisteredTypes_returns_snapshot()
{
var r = new DriverFactoryRegistry();
r.Register("A", FakeDriver);
r.Register("B", FakeDriver);
r.RegisteredTypes.ShouldContain("A");
r.RegisteredTypes.ShouldContain("B");
}
private sealed class FakeIDriver(string id) : IDriver
{
public string DriverInstanceId => id;
public string DriverType => "Fake";
public Task InitializeAsync(string _, CancellationToken __) => Task.CompletedTask;
public Task ReinitializeAsync(string _, CancellationToken __) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken _) => Task.CompletedTask;
public Task FlushOptionalCachesAsync(CancellationToken _) => Task.CompletedTask;
public DriverHealth GetHealth() => new(DriverState.Healthy, null, null);
public long GetMemoryFootprint() => 0;
}
}