Files
romanett a05a360550 Adopt the fluent builder's node-creation surface in the remaining hand-rolled node managers (#4460)
Closes #4429.

PR #4428 added the node-creation surface to `INodeManagerBuilder`. This
picks up the remaining candidates that needed a base-class change first,
and reports on the two that turn out not to be candidates at all.

## Converted

**`samples/WotCon/FlatTagServer/FlatTagNodeManager.cs`** — now derives
from `FluentNodeManagerBase`. The private `CreateObject` /
`CreateVariable` / `CreateMethod` helpers are gone, along with every
`pumpNodeId + ".Operational.Measurements.MassFlow"` concatenation; nodes
are staged with `AddObject` / `AddVariable<T>` / `AddMethod` and the
hand-maintained `externalReferences[ObjectsFolder]` entry is replaced by
`CompleteConfigureAsync`.

The `EventNotifier` bits and `AddRootNotifierAsync(pump)` are kept
verbatim — the pump is the notifier an aggregating server subscribes to,
and OPC 10000-3 only delivers the supervision conditions to a client
that can reach one.

`SupervisionSignal` loses its `namespaceIndex` and `tagPath` parameters
and derives both from the supervision Object it hangs off, so the signal
follows wherever that Object was staged.

**`samples/Redundancy/RedundantServer/HaSampleNodeManager.cs`** — same
shape. The `Counter` still reaches `EnableDistributedValueParticipation`
through `INodeBuilder.Node`. The variables keep their `Organizes`
reference type, which the fluent default would otherwise have made
`HasComponent`.

**`samples/DI/PumpDeviceIntegrationServer/OpenUsdComposition.cs`** —
both `AddPredefinedNodeAsync` sites stage on the builder now, threaded
through `ConfigureAsync`; `DiNodeManager.CreateAddressSpaceAsync`
already calls `RegisterAuthoredNodesAsync` between `ConfigureAsync` and
the reverse-reference pass, so no new plumbing was needed. Both methods
became synchronous. The NodeIds are unchanged because the hand
`SystemContext.NodeIdFactory.New(...)` calls and
`AssignInstanceChildNodeIds` were already doing exactly what staging
does.

`CreateRepresentedComponent` is left alone: it sits on
`CreatePumpAsync`, a public runtime API, and so is out of scope for the
same reason as the DI device builders.

## NodeIds are part of two samples' contracts

The issue expected the staged path to mint through the manager's
`INodeIdFactory`, and it does — but for two of these samples the
identifiers are a published contract, not an implementation detail:

- the aggregating client's checked-in Thing Descriptions under
`samples/WotCon/AggregationClient/Documents/` spell out
`nsu=…SourceA;s=Pump1.Identification.Manufacturer`;
- `samples/Redundancy/RedundantClient/Program.cs` addresses `new
NodeId("Counter", ns)` directly.

Both managers therefore override `New` for those nodes instead of taking
the default factory's derived identifier, which satisfies the acceptance
criterion that each manager keeps its current address-space shape.
FlatTag mints the full dotted browse path; the HA sample mints the bare
browse name, but only for the sample folder and its direct children.

Two things are worth knowing for anyone writing such an override.

**It has to keep an identifier the caller already chose.**
`DefaultNodeIdFactory.New` returns `node.NodeId` unchanged when it is
non-null and in the manager's own namespace. Without that same guard,
`NodeState.Create(context, nodeId, …, assignNodeIds: true)` sets the
explicit id and then `AssignNodeIds` overwrites it from the factory —
which silently moved `…SupervisionProcessFluid.Cavitation.Alarm` to
`…SupervisionProcessFluid.CavitationAlarm` and broke five alarm tests
until the guard was added.

**It has to be narrow.** A browse name is unique only among its
siblings. The HA override originally named every node the manager
minted, and the historian hangs an `HA Configuration` object off each
node it historizes — so the Counter's and the HistoryEvents' one both
landed on `ns=2;s=HA Configuration` and the strong active/passive
replicas refused to start. It is now limited to the nodes the redundant
client actually spells out.

## Merge with master

Merged `origin/master` (`0e600c0f0`). The one conflict was in
`HaSampleNodeManager.CreateAddressSpaceAsync`, where #4445 added
`AddFactoryAssignedNodes` next to the `HistoryEvents` object this branch
had converted. Both are kept, and the factory-assigned subtree stays
hand-built and unstaged on purpose: it exists to show what an identity
minted straight through `NodeIdFactory` looks like beside the sample's
named ones. It is attached once the folder has been staged, so those
identifiers survive untouched and the subtree is still registered as
part of the folder's. Its parent's identifier is `s=HighAvailability` on
both sides, so the ids it mints are unchanged from master.

## Not candidates

**`src/Opc.Ua.PubSub.Server/PubSubNodeManager.cs`** is out for the
issue's own DI-device-builder reasoning. All three of its build paths
are reachable from runtime Method calls — `OnAddDataSetFolder` and
`OnRemoveDataSetFolder` → `RebuildConfigurationAddressSpaceAsync`,
`OnAddPushTarget` / `OnRemovePushTarget` →
`RebuildKeyPushTargetAddressSpaceAsync`, `OnGetSecurityGroup` /
`OnAddSecurityGroup` / `OnRemoveSecurityGroup` →
`RebuildSecurityGroupAddressSpaceAsync` — plus `ConfigurationChanged`.
Each removes its previous roots and rebuilds them, and `Add*` throws
`BadInvalidState` once `RegisterAuthoredNodesAsync` has run.
Independently of that, its parents (`PublishSubscribe`,
`PublishedDataSets`, `SecurityGroups`, `KeyPushTargets`) are owned by
the diagnostics node manager, so `AttachToParent` would reject them as
`BadNodeIdUnknown`.


**`src/Opc.Ua.OpenUsd.Server/Scene/UsdSceneMaterializer.Properties.cs`**
— the issue asked whether a builder is reachable at those call sites. It
is not. `MaterializeUsdStage` is a public, documented `ISystemContext`
extension (`docs/OpenUsd.md`, the package README) whose only input is
the context; it returns a detached subtree for the caller to register.
It already mints through `context.RequireNodeIdFactory()`, which is the
same factory the staged path uses, so there is nothing to gain and a
public signature to break.

## Verification

Run against the merged tree:

- `Opc.Ua.Di.Tests` — 425/425 pass (covers `PumpOpenUsdE2eTests`,
`PumpHostedReferenceTests`).
- `Opc.Ua.Redundancy.Samples.Tests` — 14/14 pass, including both
variants of master's new
`FactoryAssignedNodeIdsSurviveActiveReplicaFailureAsync` and
`StrongHistorianContinuationsSurviveActiveReplicaFailureAsync`.
- `Opc.Ua.WotCon.Samples.Tests` — 25 pass, 4 fail. The same 4 fail on a
clean baseline worktree
(`CompanionTypeDefinitionsMatchNativePumpServerAsync`,
`WotPumpInstanceMatchesNativePumpSubsetAsync`,
`RealSamplesAggregateSubscribeAndReplaceGenerationAsync`,
`RealSamplesRouteManagementAndConditionActionsToEachSourceAsync` — all
`BadConfigurationError` out of the aggregation client). Pre-existing,
unrelated to this change.
- All three sample projects build with 0 warnings and 0 errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 12:11:55 +00:00

328 lines
16 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Opc.Ua;
using Opc.Ua.OpenUsd;
using Opc.Ua.OpenUsd.Server;
using Opc.Ua.Pumps;
using Opc.Ua.Server;
using Opc.Ua.Server.Fluent;
using Opc.Ua.Server.NodeManager;
namespace Pumps
{
/// <summary>
/// Wires the draft OPC UA — OpenUSD Bindings composition/aggregation model
/// (spec §5.12–5.14) onto the server: the pump composed 1:1 of Impeller and
/// Bearing component Objects (child prims), and a ProductionLine aggregating
/// 1..n pumps (Many, instanceable) with a dynamically added/removed pump
/// (model-change events) and a cross-server component (federation).
/// </summary>
public partial class PumpNodeManager
{
private BaseObjectState? m_productionLine;
private FolderState? m_linePumps;
private NodeId m_dynamicPumpNodeId;
private const string LinePrimPath = "/Plant/Line1";
// 1:1 (Child): create Impeller + Bearing component Objects on the pump, each
// with its own representation, and declare One <Component> bindings.
private void AttachPumpComponents(
PumpState pump, OpenUsdRepresentationState pumpRep, ushort ns, string primPath)
{
(BaseObjectState _, OpenUsdRepresentationState impellerRep) = CreateRepresentedComponent(
pump, "Impeller", pump.BrowseName.NamespaceIndex, primPath + "/Impeller", ns);
(BaseObjectState _, OpenUsdRepresentationState bearingRep) = CreateRepresentedComponent(
pump, "Bearing", pump.BrowseName.NamespaceIndex, primPath + "/Bearing", ns);
CreateComponentBinding(pumpRep, ns, "ImpellerComponent",
GuidFor("ImpellerComponent"),
OpenUsdCardinalityEnum.One, OpenUsdCompositionArcEnum.Child,
primPath + "/Impeller", componentRepresentation: impellerRep.NodeId);
CreateComponentBinding(pumpRep, ns, "BearingComponent",
GuidFor("BearingComponent"),
OpenUsdCardinalityEnum.One, OpenUsdCompositionArcEnum.Child,
primPath + "/Bearing", componentRepresentation: bearingRep.NodeId);
}
/// <summary>
/// Composes one full-fidelity pump prim per configured pump.
/// </summary>
/// <remarks>
/// <para>
/// The DeviceSet carries a plant-level representation anchored on
/// <c>/Plant</c> with a single <c>Many</c> component binding scoped to
/// <c>PumpType</c>. A connector resolves that binding against the
/// DeviceSet's children and composes
/// <c>/Plant/Pumps/&lt;BrowseName&gt;</c> for each pump from the served
/// <c>pump.usda</c> component asset, so the rendered scene follows
/// <c>--pumps N</c> without the stage having to author anything per pump.
/// </para>
/// <para>
/// The arc is <c>Reference</c>, not <c>Instance</c>: an instanceable prim
/// turns its descendants into a shared prototype, and a shared prototype
/// cannot carry the per-pump impeller rotation, casing colour or gauge
/// needles that make each machine read as its own.
/// </para>
/// </remarks>
private void MaterialisePlantAggregation(INodeManagerBuilder builder)
{
if (m_plantStage == null)
{
return;
}
try
{
ushort ns = (ushort)Server.NamespaceUris.GetIndex(Opc.Ua.OpenUsd.Namespaces.OpenUSD);
NodeState? deviceSet = PredefinedNodes.FindById(NodeId.Create(
Opc.Ua.Di.Objects.DeviceSet, DiNamespaceUri, Server.NamespaceUris));
if (deviceSet == null)
{
return;
}
OpenUsdRepresentationState plantRep = SystemContext.CreateRepresentation(
deviceSet, m_plantStage.NodeId, PlantPrimPath, ns);
NodeId pumpTypeId = NodeId.Create(
Opc.Ua.Pumps.ObjectTypes.PumpType,
Opc.Ua.Pumps.Namespaces.Pumps,
Server.NamespaceUris);
// Not dynamic: the configured pump set is fixed by --pumps N at
// start-up, and the dynamic add/remove path is already demonstrated
// by the ProductionLine. Declaring it dynamic here would also make
// the connector's stale-prim reconciliation sweep every prim under
// /Plant/Pumps — including the Impeller and Bearing component prims
// this scope now contains — and deactivate them.
CreateComponentBinding(plantRep, ns, "ConfiguredPumps",
new Guid("a1b2c3d4-0004-4000-8000-000000000001"),
OpenUsdCardinalityEnum.Many, OpenUsdCompositionArcEnum.Reference,
"Pumps",
assetReference: "@pump.usda@</Pump>",
componentTypeDefinition: pumpTypeId);
// Staging assigns the whole subtree its final NodeIds - the same
// pass AssignInstanceChildNodeIds used to run here - and leaves
// the registration to CreateAddressSpaceAsync.
builder.Add(plantRep, deviceSet.NodeId);
if (m_openUsdRoot?.Representations is FolderState registry)
{
plantRep.RegisterInDiscovery(registry);
}
m_logger.MaterialisedPlantAggregation(m_twins.Count);
}
catch (Exception ex)
{
m_logger.LogError(ex, "Failed to materialise the plant aggregation.");
}
}
// 1..n + dynamic aggregation: a ProductionLine aggregating pumps. The
// aggregation is an address-space demo only - it carries no OpenUSD
// representation, so the rendered hall holds exactly the pumps the
// connected server simulates and nothing else. A line pump is a static
// topology entry, not a machine anyone is driving; rendering it put
// phantom pumps in the twin that no client could account for.
// The subtree is staged on the builder rather than registered here: the
// manager's CreateAddressSpaceAsync registers everything staged during
// Configure and runs the reverse-reference pass over it, and staging
// mints the NodeIds through the same factory this method used to call
// by hand.
private void MaterialiseProductionLine(INodeManagerBuilder builder)
{
if (m_plantStage == null)
{
return;
}
try
{
ushort ns = (ushort)Server.NamespaceUris.GetIndex(Opc.Ua.OpenUsd.Namespaces.OpenUSD);
NodeState? deviceSet = PredefinedNodes.FindById(NodeId.Create(
Opc.Ua.Di.Objects.DeviceSet, DiNamespaceUri, Server.NamespaceUris));
if (deviceSet == null)
{
return;
}
BaseObjectState line = builder
.AddObject(new QualifiedName("ProductionLine", ns), deviceSet.NodeId)
.Node;
FolderState pumps = builder
.AddFolder(new QualifiedName("Pumps", ns), line.NodeId)
.Node;
m_linePumps = pumps;
// Two static aggregated entries (1..n baseline).
CreateAggregatedPump(builder, pumps.NodeId, "P-201", ns);
CreateAggregatedPump(builder, pumps.NodeId, "P-202", ns);
// Dynamic composition: emit model-change events on runtime add/remove.
ModelChangeEmissionEnabled = true;
_ = RunDynamicCompositionAsync(ns);
m_productionLine = line;
m_logger.LogInformation("Materialised ProductionLine (aggregates 1..n pumps).");
}
catch (Exception ex)
{
m_logger.LogError(ex, "Failed to materialise the ProductionLine.");
}
}
// An aggregated line entry: a plain topology Object with no
// representation, because it is not a machine the server simulates.
private static void CreateAggregatedPump(
INodeManagerBuilder builder, NodeId parentId, string name, ushort ns)
{
BaseObjectState entry = builder
.AddObject(new QualifiedName(name, ns), parentId)
.Node;
entry.ReferenceTypeId = ReferenceTypeIds.Organizes;
}
// Dynamic demo (§5.13): repeatedly add a pump (emits a GeneralModelChange),
// hold, then remove it (emits again), so a connector observes both the add and
// the remove regardless of when it connects. Bounded so the server quiesces.
private async Task RunDynamicCompositionAsync(ushort ns)
{
try
{
for (int i = 0; i < 3; i++)
{
await Task.Delay(4000).ConfigureAwait(false);
m_dynamicPumpNodeId = await AddLinePumpAsync("P-203",
LinePrimPath + "/Pumps/P_203", ns).ConfigureAwait(false);
await Task.Delay(4000).ConfigureAwait(false);
if (!m_dynamicPumpNodeId.IsNull)
{
await DeleteNodeAsync(SystemContext, m_dynamicPumpNodeId, CancellationToken.None)
.ConfigureAwait(false);
m_logger.RemovedLinePump(m_dynamicPumpNodeId);
m_dynamicPumpNodeId = NodeId.Null;
}
}
// Final add: leave P-203 in place so the composed stage renders it.
await Task.Delay(2000).ConfigureAwait(false);
m_dynamicPumpNodeId = await AddLinePumpAsync("P-203",
LinePrimPath + "/Pumps/P_203", ns).ConfigureAwait(false);
m_logger.LogInformation("Dynamic composition: P-203 left added (final state).");
}
catch (Exception ex)
{
m_logger.LogWarning(ex, "Dynamic composition demo failed.");
}
}
private async Task<NodeId> AddLinePumpAsync(string name, string primPath, ushort ns)
{
if (m_linePumps == null)
{
return NodeId.Null;
}
var pump = new BaseObjectState(null)
{
SymbolicName = name,
BrowseName = new QualifiedName(name, ns),
DisplayName = new LocalizedText(name),
TypeDefinitionId = Opc.Ua.ObjectTypeIds.BaseObjectType
};
_ = SystemContext.CreateRepresentation(
pump, m_plantStage!.NodeId, primPath, ns);
NodeId newId = await CreateNodeAsync(SystemContext, m_linePumps.NodeId,
ReferenceTypeIds.Organizes, new QualifiedName(name, ns), pump, CancellationToken.None)
.ConfigureAwait(false);
m_logger.AddedLinePump(name, newId);
return newId;
}
private (BaseObjectState, OpenUsdRepresentationState) CreateRepresentedComponent(
NodeState parent, string name, ushort objNs, string primPath, ushort openUsdNs,
NodeId refType = default)
{
var obj = new BaseObjectState(parent)
{
SymbolicName = name,
BrowseName = new QualifiedName(name, objNs),
DisplayName = new LocalizedText(name),
ReferenceTypeId = refType.IsNull ? ReferenceTypeIds.HasComponent : refType,
TypeDefinitionId = Opc.Ua.ObjectTypeIds.BaseObjectType
};
parent.AddChild(obj);
obj.NodeId = SystemContext.NodeIdFactory.New(SystemContext, obj);
OpenUsdRepresentationState rep = SystemContext.CreateRepresentation(
obj, m_plantStage!.NodeId, primPath, openUsdNs);
return (obj, rep);
}
// Thin adapter over the reusable Opc.Ua.OpenUsd.Server authoring API: the
// component/composition-binding logic lives in the SDK
// (OpenUsdRepresentationAuthoring.AddComponentBinding), not in this sample.
private void CreateComponentBinding(
OpenUsdRepresentationState rep, ushort ns, string name, Guid bindingDefinitionId,
OpenUsdCardinalityEnum cardinality, OpenUsdCompositionArcEnum arc, string targetPrimPath,
NodeId componentRepresentation = default, string? assetReference = null,
bool dynamic = false, NodeId changeEventSource = default,
string? componentServerUri = null, string? componentEndpointUrl = null,
NodeId componentTypeDefinition = default)
{
_ = rep.AddComponentBinding(
SystemContext, ns, name, bindingDefinitionId, cardinality, arc, targetPrimPath,
componentRepresentation, assetReference, dynamic, changeEventSource,
componentServerUri, componentEndpointUrl, componentTypeDefinition);
}
}
internal static partial class OpenUsdCompositionLog
{
[LoggerMessage(EventId = PumpDeviceIntegrationServerEventIds.OpenUsdComposition + 1,
Level = LogLevel.Information,
Message = "Dynamic composition: removed line pump (NodeId={NodeId}); model-change emitted.")]
public static partial void RemovedLinePump(this ILogger logger, NodeId nodeId);
[LoggerMessage(EventId = PumpDeviceIntegrationServerEventIds.OpenUsdComposition + 2,
Level = LogLevel.Information,
Message = "Dynamic composition: added line pump '{Name}' (NodeId={NodeId}); model-change emitted.")]
public static partial void AddedLinePump(this ILogger logger, string name, NodeId nodeId);
[LoggerMessage(EventId = PumpDeviceIntegrationServerEventIds.OpenUsdComposition + 3,
Level = LogLevel.Information,
Message = "Plant aggregation composes {PumpCount} configured pump(s) from pump.usda.")]
public static partial void MaterialisedPlantAggregation(this ILogger logger, int pumpCount);
}
}