Files
UA-.NETStandard/samples/Quickstarts.Servers/Boiler/BoilerNodeManager.cs
romanett 105508bcbd Mint runtime NodeIds through a single DefaultNodeIdFactory (#4433)
# Description

Nodes created at runtime now get their NodeIds from a single
`DefaultNodeIdFactory` rather than from a `New` override per
NodeManager.
The factory derives a deterministic identifier from a canonical,
length-prefixed browse path, which is injective where the classic
`{parent}_{child}` concatenation was not — `A_B` + `C` and `A` + `B_C`
both produced `A_B_C` — and it also records the parent's identifier type
and qualifies cross-namespace segments by URI, so identifiers no longer
shift with namespace-table ordering.

A NodeManager selects its style declaratively instead of writing
assignment code:

```csharp
NodeIdFactory = NodeIdFactory.WithMode(NodeIdAssignmentMode.Counter);
```

`NodeIdAssignmentMode` offers `String` (the canonical path verbatim, the
default), `Numeric` / `Guid` / `Opaque` (that path through SHA-256),
`Counter` (sequential, for nodes whose browse paths repeat — per-session
diagnostics, inference jobs, rediscovered assets) and `None`. The
counter
starts above `0x40000000`, out of reach of any authored model, so a
long-running server cannot walk a runtime instance onto a type node.

`New` overrides are gone from every NodeManager the stack ships except
two whose identifiers are a domain scheme rather than an assignment
policy: `FileSystemNodeManager`, whose NodeIds encode the file path they
resolve back to, and `RoboticsNodeManager`, whose build coordinator
reserves identifiers across managers with ownership tracking.

**Namespace rule.** Every identifier is minted into the NodeManager's
own
namespace. Neither the parent's namespace nor the browse name's is
consulted: a parent can belong to a companion-specification model whose
NodeIds are fixed by its NodeSet (`DeviceSet` in the DI namespace), and
a
browse name only names the type that declared the child. NodeManagers
whose instance namespace is not their first one rebase with
`WithDefaultNamespaceIndex`.

**Types vs instances.** An authored NodeId on a node that stands on its
own is kept. A node hanging off a parent is re-minted, because it
reached
the factory through `AssignNodeIds` walking a subtree copied from a type
declaration. Keeping those would alias every instance onto the type's
own
nodes, and the predefined-node index takes the last writer, so the type
would quietly become an instance rather than the clash being reported.

New `ISystemContext.CreateInstance(...)` builds an instance of a
generated
type and rebases its subtree through `AssignInstanceNodeId` — the path
the
generated `CreateInstanceOf<Type>` helpers already took. The AI
NodeManager was the one place calling `NodeState.Create` directly, so
its
roots kept the NodeId their state object is born with (the type's own);
it now uses the shared path.

## Breaking changes

- `IAsyncNodeManager` extends `INodeIdFactory` and gains `AddNode` and
  `AddRootNotifier`. This lets the fluent surface mint and register
  through the interface instead of type-testing for
  `AsyncCustomNodeManager` and silently falling back to a concatenated
  identifier when the test failed — that fallback was itself a source of
  divergent NodeIds.
- `AsyncNodeManagerAdapter` delegates `New` to the wrapped NodeManager,
so
**`CustomNodeManager2` behaves exactly as before**: it mints nothing and
  a node keeps whatever NodeId it already has. Servers built on it are
  unaffected.

## Notes for reviewers

- `docs/NodeIdAssignment.md` is new and describes the whole mechanism:
the
  factory contract, identifier formats, type declarations vs instances,
  the generated helpers and their parameters, per-NodeManager behaviour,
  and an inventory of every member involved.
- The three commits are independently revertible.
- Two pieces that look redundant are deliberately kept, with the
reasoning
  recorded in the doc: `assignInstanceNodeIds` (it *suppresses* minting,
  where the rebase rule *forces* it) and the generator's
  `NodeId.Equals(TypeNodeIdConstant)` guard (it distinguishes a
  caller-assigned NodeId from a declaration's).
- Fluent builder tests previously passed only because of the removed
  fallback; they now run against a real `DefaultNodeIdFactory` through a
  shared `FluentTestNodeManager` helper.

## Related Issues

_No tracking issue yet._

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

> Test runs were on **net10.0 only** — .NET Framework was not exercised
> locally. Suites run green on an idle machine: Server 4950/4955, GDS
> 1116/1170, WotCon 1225/1225, Vision 484/485, DI 424/424, AI 174/174,
> ISA95 136/136, Positioning 69/69, RobotIntent 22/22. One unrelated
> pre-existing failure remains in `Opc.Ua.Types.Tests`
> (`EveryEmbeddedExampleMatchesItsRecordedHash`) — a WoT fixture checked
> out with CRLF, fixed by
> `git add --renormalize tests/Opc.Ua.Types.Tests/Wot/Assets`.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 14:37:19 +00:00

279 lines
10 KiB
C#

/* ========================================================================
* 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.Collections.Generic;
using Opc.Ua;
using Opc.Ua.Sample;
using Opc.Ua.Server;
namespace Boiler
{
/// <summary>
/// The factory class to create the boiler node manager.
/// </summary>
public class BoilerNodeManagerFactory : INodeManagerFactory
{
/// <inheritdoc/>
public INodeManager Create(IServerInternal server, ApplicationConfiguration configuration)
{
return new BoilerNodeManager(server, configuration, NamespacesUris.ToArray()!);
}
/// <inheritdoc/>
public ArrayOf<string> NamespacesUris
=> [Namespaces.Boiler, Namespaces.Boiler + "Instance"];
}
/// <summary>
/// A node manager for the boiler exposed by the server.
/// </summary>
public class BoilerNodeManager : SampleNodeManager
{
/// <summary>
/// Initializes the node manager.
/// </summary>
public BoilerNodeManager(
IServerInternal server,
ApplicationConfiguration? configuration,
string[] namespaceUris)
: base(server)
{
_ = configuration;
NamespaceUris = namespaceUris;
Server.NamespaceUris.GetIndexOrAppend(namespaceUris[0]);
m_namespaceIndex = Server.NamespaceUris.GetIndexOrAppend(namespaceUris[1]);
// counter identifiers in the boiler namespace, which is the
// second one this manager owns.
NodeIdFactory = NodeIdFactory
.WithMode(NodeIdAssignmentMode.Counter)
.WithDefaultNamespaceIndex(m_namespaceIndex);
m_boilers = [];
}
/// <summary>
/// Does any initialization required before the address space can be used.
/// </summary>
/// <remarks>
/// The externalReferences is an out parameter that allows the node manager to link to nodes
/// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
/// should have a reference to the root folder node(s) exposed by this node manager.
/// </remarks>
public override void CreateAddressSpace(
IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
base.CreateAddressSpace(externalReferences);
CreateBoiler(SystemContext, 2);
}
}
/// <summary>
/// Creates a boiler and adds it to the address space.
/// </summary>
/// <param name="context">The context to use.</param>
/// <param name="unitNumber">The unit number for the boiler.</param>
private void CreateBoiler(ISystemContext context, int unitNumber)
{
var boiler = new BoilerState(null);
string name = Utils.Format("Boiler #{0}", unitNumber);
// A generated state object is born carrying its own type's NodeId,
// and Create only replaces that when handed one. Passing the null
// NodeId would leave this boiler sitting on BoilerType, so the
// second boiler would overwrite the ObjectType in the index.
// CreateInstance builds the subtree and then rebases the root and
// its children onto fresh instance identifiers.
context.CreateInstance(
boiler,
new QualifiedName(name, m_namespaceIndex),
new LocalizedText(name));
NodeState folder = FindPredefinedNode<NodeState>(
ExpandedNodeId.ToNodeId(ObjectIds.Boilers, Server.NamespaceUris)!)!;
folder.AddReference(Opc.Ua.ReferenceTypeIds.Organizes, false, boiler.NodeId);
boiler.AddReference(Opc.Ua.ReferenceTypeIds.Organizes, true, folder.NodeId);
string unitLabel = Utils.Format("{0}0", unitNumber);
UpdateDisplayName(boiler.InputPipe!, unitLabel);
UpdateDisplayName(boiler.Drum!, unitLabel);
UpdateDisplayName(boiler.OutputPipe!, unitLabel);
UpdateDisplayName(boiler.LevelController!, unitLabel);
UpdateDisplayName(boiler.FlowController!, unitLabel);
UpdateDisplayName(boiler.CustomController!, unitLabel);
m_boilers.Add(boiler);
AddPredefinedNode(context, boiler);
// Autostart boiler simulation state machine
MethodState start = boiler.Simulation!.Start!;
ArrayOf<Variant> inputArguments = [];
List<Variant> outputArguments = [];
var errors = new List<ServiceResult>();
start.Call(context, boiler.NodeId, inputArguments, errors, outputArguments);
}
/// <summary>
/// Updates the display name for an instance with the unit label name.
/// </summary>
/// <param name="instance">The instance to update.</param>
/// <param name="unitLabel">The label to apply.</param>
/// <remarks>This method assumes the DisplayName has the form NameX001 where X0 is the unit label placeholder.</remarks>
private static void UpdateDisplayName(BaseInstanceState instance, string unitLabel)
{
LocalizedText displayName = instance.DisplayName;
if (!displayName.IsNullOrEmpty)
{
string? text = displayName.Text;
if (text != null)
{
text = text.Replace("X0", unitLabel, StringComparison.Ordinal);
}
displayName = new LocalizedText(displayName.Locale, text);
}
instance.DisplayName = displayName;
}
/// <summary>
/// Loads a node set from a file or resource and adds them to the set of predefined nodes.
/// </summary>
protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context)
{
return new NodeStateCollection().AddBoiler(context);
}
/// <summary>
/// Replaces the generic node with a node specific to the model.
/// </summary>
protected override NodeState AddBehaviourToPredefinedNode(
ISystemContext context,
NodeState predefinedNode)
{
if (predefinedNode is not BaseObjectState passiveNode)
{
return predefinedNode;
}
NodeId typeId = passiveNode.TypeDefinitionId;
if (!IsNodeIdInNamespace(typeId) || !typeId.TryGetValue(out uint typeIdNumeric))
{
return predefinedNode;
}
switch (typeIdNumeric)
{
case ObjectTypes.BoilerType:
if (passiveNode is not BoilerState activeNode)
{
activeNode = new BoilerState(passiveNode.Parent);
activeNode.Create(context, passiveNode);
// replace the node in the parent.
passiveNode.Parent?.ReplaceChild(context, activeNode);
}
// Autostart boiler simulation state machine
MethodState start = activeNode.Simulation!.Start!;
ArrayOf<Variant> inputArguments = [];
List<Variant> outputArguments = [];
var errors = new List<ServiceResult>();
start.Call(context, activeNode.NodeId, inputArguments, errors, outputArguments);
return activeNode;
}
return predefinedNode;
}
/// <summary>
/// Does any processing after a monitored item is created.
/// </summary>
protected override void OnCreateMonitoredItem(
ISystemContext systemContext,
MonitoredItemCreateRequest itemToCreate,
MonitoredNode monitoredNode,
DataChangeMonitoredItem monitoredItem)
{
// TBD
}
/// <summary>
/// Does any processing after a monitored item is created.
/// </summary>
protected override void OnModifyMonitoredItem(
ISystemContext systemContext,
MonitoredItemModifyRequest itemToModify,
MonitoredNode monitoredNode,
DataChangeMonitoredItem monitoredItem,
double previousSamplingInterval)
{
// TBD
}
/// <summary>
/// Does any processing after a monitored item is deleted.
/// </summary>
protected override void OnDeleteMonitoredItem(
ISystemContext systemContext,
MonitoredNode monitoredNode,
DataChangeMonitoredItem monitoredItem)
{
// TBD
}
/// <summary>
/// Does any processing after a monitored item is created.
/// </summary>
protected override void OnSetMonitoringMode(
ISystemContext systemContext,
MonitoredNode monitoredNode,
DataChangeMonitoredItem monitoredItem,
MonitoringMode previousMode,
MonitoringMode currentMode)
{
// TBD
}
private readonly ushort m_namespaceIndex;
private readonly List<BoilerState> m_boilers;
}
}