Files
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

569 lines
20 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 System.Globalization;
using Opc.Ua;
using Opc.Ua.Sample;
using Opc.Ua.Server;
namespace MemoryBuffer
{
/// <summary>
/// The factory to create the node manager for memory buffers.
/// </summary>
public class MemoryBufferNodeManagerFactory : INodeManagerFactory
{
/// <inheritdoc/>
public INodeManager Create(IServerInternal server, ApplicationConfiguration configuration)
{
return new MemoryBufferNodeManager(server, configuration, NamespacesUris.ToArray()!);
}
/// <inheritdoc/>
public ArrayOf<string> NamespacesUris
=> [Namespaces.MemoryBuffer, Namespaces.MemoryBuffer + "/Instance"];
}
/// <summary>
/// A node manager for a variety of memory buffers.
/// </summary>
public class MemoryBufferNodeManager : SampleNodeManager
{
/// <summary>
/// Initializes the node manager.
/// </summary>
public MemoryBufferNodeManager(
IServerInternal server,
ApplicationConfiguration configuration,
string[] namespaceUris)
: base(server)
{
NamespaceUris = namespaceUris;
// get the configuration for the node manager.
m_configuration =
configuration.ParseExtension<MemoryBufferConfiguration>() ??
new MemoryBufferConfiguration();
// use suitable defaults if no configuration exists.
m_buffers = [];
}
/// <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);
// create the nodes from configuration.
ushort namespaceIndex = Server.NamespaceUris
.GetIndexOrAppend(Namespaces.MemoryBuffer);
BaseInstanceState root = FindPredefinedNode<BaseInstanceState>(
new NodeId(Objects.MemoryBuffers, namespaceIndex))!;
// create the nodes from configuration.
namespaceIndex = Server.NamespaceUris
.GetIndexOrAppend(Namespaces.MemoryBuffer + "/Instance");
// the buffers live in the instance namespace, so their
// children are minted there too rather than in the model
// namespace the base class would otherwise have adopted.
NodeIdFactory = NodeIdFactory.WithDefaultNamespaceIndex(namespaceIndex);
if (m_configuration != null && !m_configuration.Buffers.IsNull)
{
for (int ii = 0; ii < m_configuration.Buffers.Count; ii++)
{
MemoryBufferInstance instance = m_configuration.Buffers[ii]!;
// create a new buffer.
var bufferNode = new MemoryBufferState(SystemContext, instance);
// assign node ids.
bufferNode.Create(
SystemContext,
new NodeId(bufferNode.SymbolicName, namespaceIndex),
new QualifiedName(bufferNode.SymbolicName, namespaceIndex),
default,
true);
bufferNode.CreateBuffer(instance.DataType, instance.TagCount);
bufferNode.InitializeMonitoring(Server, this);
// link to root.
root.AddChild(bufferNode);
// Register the buffer subtree. Its own properties -
// StartAddress and SizeInBytes - are real nodes with
// real identifiers, and a client that browses the
// buffer is handed them; without this they resolve to
// nothing. The virtual tags below are still ephemeral
// and are not registered.
AddPredefinedNode(SystemContext, bufferNode);
// save the buffers for easy look up later.
m_buffers[bufferNode.SymbolicName] = bufferNode;
}
}
}
}
/// <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().AddMemoryBuffer(context);
}
/// <summary>
/// Frees any resources allocated for the address space.
/// </summary>
public override void DeleteAddressSpace()
{
lock (Lock)
{
base.DeleteAddressSpace();
}
}
/// <summary>
/// Returns a unique handle for the node.
/// </summary>
/// <remarks>
/// This must efficiently determine whether the node belongs to the node manager. If it does belong to
/// NodeManager it should return a handle that does not require the NodeId to be validated again when
/// the handle is passed into other methods such as 'Read' or 'Write'.
/// </remarks>
protected override object? GetManagerHandle(
ISystemContext context,
NodeId nodeId,
IDictionary<NodeId, NodeState>? cache)
{
lock (Lock)
{
if (!IsNodeIdInNamespace(nodeId))
{
return null;
}
if (nodeId.TryGetValue(out string? id))
{
// check for a reference to the buffer.
if (m_buffers.TryGetValue(id!, out MemoryBufferState? buffer))
{
return buffer;
}
// Tag ids have the syntax <bufferName>[<address>]. An id
// in any other shape is an ordinary registered node - the
// buffer's own properties carry identifiers minted by the
// manager's factory - so it falls through to the base
// lookup rather than being reported as unknown.
MemoryTagState? tag = ResolveVirtualTag(id!);
if (tag != null)
{
return tag;
}
}
return base.GetManagerHandle(context, nodeId, cache);
}
}
/// <summary>
/// Resolves an identifier of the form <c>&lt;bufferName&gt;[&lt;address&gt;]</c>
/// to a tag inside that buffer.
/// </summary>
/// <remarks>
/// The tags carry all the metadata the UA operations need plus
/// pointers into the buffer object, and are discarded once the
/// operation completes. That is what lets the server expose millions
/// of nodes without holding millions of objects in memory.
/// </remarks>
/// <param name="id">The string identifier to parse.</param>
/// <returns>The tag, or <c>null</c> when the id is not a tag id.</returns>
private MemoryTagState? ResolveVirtualTag(string id)
{
if (id.Length == 0 || id[^1] != ']')
{
return null;
}
int index = id.IndexOf('[', StringComparison.Ordinal);
if (index == -1)
{
return null;
}
if (!m_buffers.TryGetValue(id[..index], out MemoryBufferState? buffer))
{
return null;
}
string offsetText = id.Substring(index + 1, id.Length - index - 2);
for (int ii = 0; ii < offsetText.Length; ii++)
{
if (!char.IsDigit(offsetText[ii]))
{
return null;
}
}
if (offsetText.Length == 0)
{
return null;
}
uint offset = Convert.ToUInt32(offsetText, CultureInfo.InvariantCulture);
if (offset >= buffer.SizeInBytes!.Value)
{
return null;
}
return new MemoryTagState(buffer, offset);
}
/// <summary>
/// Creates a new set of monitored items for a set of variables.
/// </summary>
/// <remarks>
/// This method only handles data change subscriptions. Event subscriptions are created by the SDK.
/// </remarks>
protected override ServiceResult CreateMonitoredItem(
ISystemContext context,
NodeState source,
uint subscriptionId,
double publishingInterval,
DiagnosticsMasks diagnosticsMasks,
TimestampsToReturn timestampsToReturn,
MonitoredItemCreateRequest itemToCreate,
bool createDurable,
MonitoredItemIdFactory monitoredItemIdFactory,
out MonitoringFilterResult filterError,
out IMonitoredItem monitoredItem)
{
filterError = null!;
monitoredItem = null!;
// use default behavior for non-tag sources.
if (source is not MemoryTagState tag)
{
return base.CreateMonitoredItem(
context,
source,
subscriptionId,
publishingInterval,
diagnosticsMasks,
timestampsToReturn,
itemToCreate,
createDurable,
monitoredItemIdFactory,
out filterError,
out monitoredItem);
}
// validate parameters.
MonitoringParameters parameters = itemToCreate.RequestedParameters;
// no filters supported at this time.
var filter = (MonitoringFilter?)ExtensionObject.ToEncodeable(parameters.Filter);
if (filter != null)
{
return StatusCodes.BadFilterNotAllowed;
}
// index range not supported.
if (!itemToCreate.ItemToMonitor.ParsedIndexRange.IsNull)
{
return StatusCodes.BadIndexRangeInvalid;
}
// data encoding not supported.
if (!itemToCreate.ItemToMonitor.DataEncoding.IsNull)
{
return StatusCodes.BadDataEncodingUnsupported;
}
// read initial value.
var initialValue = new DataValue(
Variant.Null,
StatusCodes.Good,
DateTime.MinValue,
DateTime.UtcNow);
ServiceResult error = source.ReadAttribute(
context,
itemToCreate.ItemToMonitor.AttributeId,
itemToCreate.ItemToMonitor.ParsedIndexRange,
itemToCreate.ItemToMonitor.DataEncoding,
ref initialValue);
if (ServiceResult.IsBad(error))
{
return error;
}
// get the monitored node for the containing buffer.
if (tag.Parent is not MemoryBufferState buffer)
{
return StatusCodes.BadInternalError;
}
// determine the sampling interval.
double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval;
if (samplingInterval < 0)
{
samplingInterval = publishingInterval;
}
// create the item.
MemoryBufferMonitoredItem datachangeItem = buffer.CreateDataChangeItem(
(ServerSystemContext)context,
tag,
subscriptionId,
monitoredItemIdFactory.GetNextId(),
itemToCreate.ItemToMonitor,
diagnosticsMasks,
timestampsToReturn,
itemToCreate.MonitoringMode,
itemToCreate.RequestedParameters.ClientHandle,
samplingInterval,
createDurable);
// report the initial value.
datachangeItem.QueueValue(initialValue, null);
// update monitored item list.
monitoredItem = datachangeItem;
return ServiceResult.Good;
}
/// <summary>
/// Restore a single monitored Item after a restart
/// </summary>
/// <returns>true if sucesfully restored</returns>
protected override bool RestoreMonitoredItem(
ServerSystemContext context,
NodeState source,
IStoredMonitoredItem storedMonitoredItem,
out IMonitoredItem monitoredItem)
{
monitoredItem = null!;
// use default behavior for non-tag sources.
if (source is not MemoryTagState tag)
{
return base.RestoreMonitoredItem(
context,
source,
storedMonitoredItem,
out monitoredItem);
}
// get the monitored node for the containing buffer.
if (tag.Parent is not MemoryBufferState buffer)
{
return false;
}
// create the item.
// update monitored item list.
monitoredItem = buffer.RestoreDataChangeItem(context, tag, storedMonitoredItem);
return true;
}
/// <summary>
/// Modifies the parameters for a monitored item.
/// </summary>
protected override ServiceResult ModifyMonitoredItem(
ISystemContext context,
DiagnosticsMasks diagnosticsMasks,
TimestampsToReturn timestampsToReturn,
IMonitoredItem monitoredItem,
MonitoredItemModifyRequest itemToModify,
out MonitoringFilterResult filterError)
{
filterError = null!;
// check for valid handle.
if (monitoredItem.ManagerHandle is not MemoryBufferState)
{
return base.ModifyMonitoredItem(
context,
diagnosticsMasks,
timestampsToReturn,
monitoredItem,
itemToModify,
out filterError);
}
// owned by this node manager.
itemToModify.Processed = true;
// get the monitored item.
if (monitoredItem is not MemoryBufferMonitoredItem datachangeItem)
{
return StatusCodes.BadMonitoredItemIdInvalid;
}
// validate parameters.
MonitoringParameters parameters = itemToModify.RequestedParameters;
// no filters supported at this time.
var filter = (MonitoringFilter?)ExtensionObject.ToEncodeable(parameters.Filter);
if (filter != null)
{
return StatusCodes.BadFilterNotAllowed;
}
// modify the monitored item parameters.
_ = datachangeItem.Modify(
diagnosticsMasks,
timestampsToReturn,
itemToModify.RequestedParameters.ClientHandle,
itemToModify.RequestedParameters.SamplingInterval);
return ServiceResult.Good;
}
/// <summary>
/// Deletes a monitored item.
/// </summary>
protected override ServiceResult DeleteMonitoredItem(
ISystemContext context,
IMonitoredItem monitoredItem,
out bool processed)
{
// check for valid handle.
if (monitoredItem.ManagerHandle is not MemoryBufferState buffer)
{
return base.DeleteMonitoredItem(context, monitoredItem, out processed);
}
// owned by this node manager.
processed = true;
// get the monitored item.
if (monitoredItem is not MemoryBufferMonitoredItem datachangeItem)
{
return StatusCodes.BadMonitoredItemIdInvalid;
}
// delete the item.
buffer.DeleteItem(datachangeItem);
return ServiceResult.Good;
}
/// <summary>
/// Changes the monitoring mode for an item.
/// </summary>
protected override ServiceResult SetMonitoringMode(
ISystemContext context,
IMonitoredItem monitoredItem,
MonitoringMode monitoringMode,
out bool processed)
{
// check for valid handle.
if (monitoredItem.ManagerHandle is not MemoryBufferState buffer)
{
return base.SetMonitoringMode(
context,
monitoredItem,
monitoringMode,
out processed);
}
// owned by this node manager.
processed = true;
// get the monitored item.
if (monitoredItem is not MemoryBufferMonitoredItem datachangeItem)
{
return StatusCodes.BadMonitoredItemIdInvalid;
}
// delete the item.
MonitoringMode previousMode = datachangeItem.SetMonitoringMode(monitoringMode);
// need to provide an immediate update after enabling.
if (previousMode == MonitoringMode.Disabled &&
monitoringMode != MonitoringMode.Disabled)
{
var initialValue = new DataValue(
Variant.Null,
StatusCodes.Good,
DateTime.MinValue,
DateTime.UtcNow);
var tag = new MemoryTagState(buffer, datachangeItem.Offset);
ServiceResult error = tag.ReadAttribute(
context,
datachangeItem.AttributeId,
default,
default,
ref initialValue);
datachangeItem.QueueValue(initialValue, error);
}
return ServiceResult.Good;
}
private readonly MemoryBufferConfiguration m_configuration;
private readonly Dictionary<string, MemoryBufferState> m_buffers;
}
}