mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-21 00:56:28 +08:00
41db5aca60
# Description A node created inside the fluent `Configure` hook (source-generated `[NodeManager]` partial, or the hosting `AddNodeManager(uri, build)` route) had no way to appear below the Objects folder — or below any node owned by another node manager. `AsyncCustomNodeManager.AddReverseReferencesAsync` mirrors inverse references into the `externalReferences` dictionary **before** the `Configure` partials run, and the fluent surface never sees the dictionary, so a configure-created node with an inverse `Organizes` reference to `ObjectsFolder` existed and simulated but never showed up under Objects. This implements the three coordinated pieces proposed in #4329, plus the companion namespace gap: **1. Idempotent mirroring pass** (independently worthwhile hardening) - `AddExternalReference` in `AsyncCustomNodeManager` and `CustomNodeManager2` now has if-missing semantics (linear scan of the per-source list). - `TypeTable.AddEncoding` no longer appends a duplicate encoding id; re-registering the same encoding is a succeeding no-op. (`AddRootNotifierAsync` and the node-side `AddReferenceIfMissing` branch were already idempotent.) **2. Re-run the pass after `Configure`** - New protected `FluentNodeManagerBase.CompleteConfigureAsync(externalReferences, ct)` wraps `AddReverseReferencesAsync` so hand-written managers using `CreateFluentBuilder` benefit too. - The generator-emitted `CreateAddressSpaceAsync` and the hosting `FluentNodeManager` invoke it once between the `Configure` callbacks and `Seal()`. Timing is safe: the master distributes `externalReferences` only after every manager's `CreateAddressSpaceAsync` returns. Side benefit: inverse `HasNotifier` references on configure-created event sources get root-notifier registration for free. - The hosting `FluentNodeManager`'s hand-rolled `externalReferences` workaround for its root folder is deleted — the root's inverse `Organizes` reference now flows through the shared pass (mirrored exactly once, covered by a test). **3. Discoverable fluent sugar** - `OrganizedBy(parentId)` / `UnderObjectsFolder()` on `INodeBuilder` write the inverse `Organizes` reference; with piece 2, placement is just "write the inverse reference". - A parentless `CreateInstance<TState>` on `INodeManagerBuilder` takes a constructor-style factory (`p => new BoilerState(p)`, keeping the surface reflection-free and AOT-safe), materializes the subtree from the type model via `NodeState.Create`, rebases all NodeIds through the manager's `INodeIdFactory` (`AssignInstanceNodeId`/`AssignInstanceChildNodeIds` — the same pair the generated factories use, so declaration-id children cannot collide with the type model), and registers via `AddPredefinedNodeSynchronously`. The Boiler #2 shape becomes fully fluent: ```csharp builder.CreateInstance( new QualifiedName("Boiler #2", NamespaceIndexes[1]), p => new BoilerState(p)) .Configure(n => n.UnderObjectsFolder()); ``` **Companion gap, same theme:** `[NodeManager]` grows `AdditionalNamespaceUris`, flowing through attribute discovery → binding → generator so the generated constructor reports a second (instance) namespace at construction and the generated factory advertises it in `NamespacesUris` — today `SetNamespaces` after construction is not enough because `MasterNodeManager` builds its namespace routing from what the manager reported when it was built. **Scope boundary** (as discussed in the issue): startup-time configuration only; for nodes created after startup the correct primitive remains `IMasterNodeManager.AddReferencesAsync`. **Reviewer notes** - The generated-code change was validated against the real pipeline: a forced fresh compile of `Opc.Ua.Server.Tests` (whose CoverageNodeSet managers are `[NodeManager]`-generated) emits `await CompleteConfigureAsync(externalReferences, cancellationToken)` between `Configure` and `Seal()` and compiles against the real base class. - The distribution consumer (`AddReferencesAsync`) already used `AddReferenceIfMissing`, so the whole chain is defense-in-depth idempotent. - 15 new tests: double-run idempotence, second-pass pickup of late-registered nodes, the new reference sugar, root-instance creation incl. child-id rebasing and reference remapping, hosting end-to-end Objects-folder placement, emitted-sequence and `AdditionalNamespaceUris` generator tests, and a full Roslyn-pipeline attribute test. Docs updated in `docs/NodeManagers.md` (new "Creating nodes under other managers' nodes" section, attribute docs, fluent-surface sections). - Verified locally: all touched projects build with 0 warnings; full `Opc.Ua.Server.Tests` (4,725 passed / 0 failed / 5 skipped, net9.0), `TypeTableTests` (113), `Opc.Ua.SourceGeneration.Core.Tests` (41), `Opc.Ua.SourceGeneration.Tests` (132), and the Quickstarts.Servers sample all pass. ## Related Issues - Fixes #4329 - Motivating case: OPCFoundation/UA-.NETStandard-Samples#756 / OPCFoundation/UA-.NETStandard-Samples#795 (Workshop/Boiler migration) ## Checklist - [x] 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. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
324 lines
17 KiB
C#
324 lines
17 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/
|
|
* ======================================================================*/
|
|
|
|
namespace Opc.Ua.SourceGeneration
|
|
{
|
|
/// <summary>
|
|
/// Templates emitted by the <see cref="NodeManagerGenerator"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// All emitted code uses fully-qualified type names so the consuming
|
|
/// project only needs to reference <c>Opc.Ua.Server</c> (which itself
|
|
/// transitively brings in <c>Opc.Ua.Core</c>).
|
|
/// </remarks>
|
|
internal static class NodeManagerTemplates
|
|
{
|
|
/// <summary>
|
|
/// Top-level template for the partial <c>NodeManager</c> class.
|
|
/// </summary>
|
|
public static readonly TemplateString File = TemplateString.Parse(
|
|
$$"""
|
|
{{Tokens.CodeHeader}}
|
|
|
|
namespace {{Tokens.NamespacePrefix}}
|
|
{
|
|
/// <summary>
|
|
/// Source-generated node manager for the
|
|
/// <c>{{Tokens.NamespaceUri}}</c> namespace.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Implement <c>partial void Configure(INodeManagerBuilder builder)</c>
|
|
/// in a sibling partial to wire per-node callbacks using the
|
|
/// fluent API in <c>Opc.Ua.Server.Fluent</c>.
|
|
/// </remarks>
|
|
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{Tokens.Tool}}", "{{Tokens.Version}}")]
|
|
public partial class {{Tokens.NodeManagerClassName}} : global::Opc.Ua.Server.Fluent.FluentNodeManagerBase
|
|
{
|
|
private global::Opc.Ua.Server.Fluent.NodeManagerBuilder? __m_builder;
|
|
|
|
/// <summary>
|
|
/// Initializes a new <see cref="{{Tokens.NodeManagerClassName}}"/>.
|
|
/// </summary>
|
|
public {{Tokens.NodeManagerClassName}}(
|
|
global::Opc.Ua.Server.IServerInternal server,
|
|
global::Opc.Ua.ApplicationConfiguration configuration)
|
|
: base(server, configuration, {{Tokens.NamespaceUri}}{{Tokens.AdditionalNamespaceUris}})
|
|
{
|
|
SystemContext.NodeIdFactory = this;
|
|
}
|
|
|
|
/// <summary>
|
|
/// User extensibility hook. Implement in a sibling
|
|
/// <c>partial</c> to wire callbacks via the fluent builder.
|
|
/// </summary>
|
|
partial void Configure(global::Opc.Ua.Server.Fluent.INodeManagerBuilder builder);
|
|
|
|
/// <summary>
|
|
/// Source-generated typed counterpart of
|
|
/// <see cref="Configure(global::Opc.Ua.Server.Fluent.INodeManagerBuilder)"/>.
|
|
/// Implement in a sibling <c>partial</c> to wire callbacks via the
|
|
/// strongly-typed model-traversal surface generated for this manager.
|
|
/// </summary>
|
|
partial void Configure(I{{Tokens.NodeManagerClassName}}Builder builder);
|
|
|
|
/// <inheritdoc/>
|
|
protected override global::System.Threading.Tasks.ValueTask<global::Opc.Ua.NodeStateCollection> LoadPredefinedNodesAsync(
|
|
global::Opc.Ua.ISystemContext context,
|
|
global::System.Threading.CancellationToken cancellationToken = default)
|
|
{
|
|
return new global::System.Threading.Tasks.ValueTask<global::Opc.Ua.NodeStateCollection>(
|
|
new global::Opc.Ua.NodeStateCollection().Add{{Tokens.Namespace}}(context));
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public override async global::System.Threading.Tasks.ValueTask CreateAddressSpaceAsync(
|
|
global::System.Collections.Generic.IDictionary<global::Opc.Ua.NodeId,
|
|
global::System.Collections.Generic.IList<global::Opc.Ua.IReference>> externalReferences,
|
|
global::System.Threading.CancellationToken cancellationToken = default)
|
|
{
|
|
await base.CreateAddressSpaceAsync(externalReferences, cancellationToken).ConfigureAwait(false);
|
|
|
|
ushort __nsIndex = Server.NamespaceUris.GetIndexOrAppend({{Tokens.NamespaceUri}});
|
|
|
|
__m_builder = new global::Opc.Ua.Server.Fluent.NodeManagerBuilder(
|
|
SystemContext,
|
|
this,
|
|
__nsIndex,
|
|
__FindRootByBrowseName,
|
|
__FindRootByNodeId,
|
|
__FindByTypeDefinitionId,
|
|
__FindByDataTypeId);
|
|
|
|
// Attach the FluentNodeManagerBase event-source registry
|
|
// to the builder so Publish(...) extensions can resolve
|
|
// it before the user's Configure partial(s) run.
|
|
AttachToBuilder(__m_builder);
|
|
|
|
Configure(__m_builder);
|
|
Configure(new {{Tokens.NodeManagerClassName}}TypedBuilder(__m_builder));
|
|
|
|
// Mirror references from configure-created nodes to
|
|
// nodes owned by other node managers (e.g. the Objects
|
|
// folder) into the externalReferences dictionary.
|
|
await CompleteConfigureAsync(externalReferences, cancellationToken).ConfigureAwait(false);
|
|
|
|
__m_builder.Seal();
|
|
|
|
foreach (global::Opc.Ua.NodeState __node in PredefinedNodes.Values)
|
|
{
|
|
__m_builder.Dispatcher.NotifyNodeAdded(SystemContext, __node);
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override async global::System.Threading.Tasks.ValueTask AddPredefinedNodeAsync(
|
|
global::Opc.Ua.ISystemContext context,
|
|
global::Opc.Ua.NodeState node,
|
|
global::System.Threading.CancellationToken cancellationToken = default)
|
|
{
|
|
await base.AddPredefinedNodeAsync(context, node, cancellationToken).ConfigureAwait(false);
|
|
if (__m_builder is { } __b)
|
|
{
|
|
__b.Dispatcher.NotifyNodeAdded(context, node);
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override async global::System.Threading.Tasks.ValueTask RemovePredefinedNodeAsync(
|
|
global::Opc.Ua.ISystemContext context,
|
|
global::Opc.Ua.NodeState node,
|
|
global::System.Collections.Generic.List<global::Opc.Ua.Server.LocalReference> referencesToRemove,
|
|
global::System.Threading.CancellationToken cancellationToken = default)
|
|
{
|
|
if (__m_builder is { } __b)
|
|
{
|
|
__b.Dispatcher.NotifyNodeRemoved(context, node);
|
|
}
|
|
await base.RemovePredefinedNodeAsync(context, node, referencesToRemove, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
protected override void OnMonitoredItemCreated(
|
|
global::Opc.Ua.Server.ServerSystemContext context,
|
|
global::Opc.Ua.Server.NodeHandle handle,
|
|
global::Opc.Ua.Server.ISampledDataChangeMonitoredItem monitoredItem)
|
|
{
|
|
base.OnMonitoredItemCreated(context, handle, monitoredItem);
|
|
if (__m_builder is { } __b && handle?.Node is { } __node)
|
|
{
|
|
__b.Dispatcher.NotifyMonitoredItemCreated(context, __node, monitoredItem);
|
|
}
|
|
}
|
|
|
|
private global::Opc.Ua.NodeState __FindRootByBrowseName(global::Opc.Ua.QualifiedName browseName)
|
|
{
|
|
if (browseName == null)
|
|
{
|
|
return null;
|
|
}
|
|
foreach (global::Opc.Ua.NodeState __node in PredefinedNodes.Values)
|
|
{
|
|
if (__node.BrowseName == browseName)
|
|
{
|
|
return __node;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private global::Opc.Ua.NodeState __FindRootByNodeId(global::Opc.Ua.NodeId nodeId)
|
|
{
|
|
if (nodeId.IsNull)
|
|
{
|
|
return null;
|
|
}
|
|
return PredefinedNodes.TryGetValue(nodeId, out global::Opc.Ua.NodeState __node) ? __node : null;
|
|
}
|
|
|
|
private global::System.Collections.Generic.IReadOnlyList<global::Opc.Ua.NodeState> __FindByTypeDefinitionId(
|
|
global::Opc.Ua.NodeId typeDefinitionId)
|
|
{
|
|
if (typeDefinitionId == null || typeDefinitionId.IsNull)
|
|
{
|
|
return global::System.Array.Empty<global::Opc.Ua.NodeState>();
|
|
}
|
|
|
|
var __matches = new global::System.Collections.Generic.List<global::Opc.Ua.NodeState>();
|
|
var __queue = new global::System.Collections.Generic.Queue<global::Opc.Ua.NodeState>();
|
|
var __seen = new global::System.Collections.Generic.HashSet<global::Opc.Ua.NodeState>();
|
|
var __scratch = new global::System.Collections.Generic.List<global::Opc.Ua.BaseInstanceState>();
|
|
foreach (global::Opc.Ua.NodeState __root in PredefinedNodes.Values)
|
|
{
|
|
if (__root != null && __seen.Add(__root))
|
|
{
|
|
__queue.Enqueue(__root);
|
|
}
|
|
}
|
|
while (__queue.Count > 0)
|
|
{
|
|
global::Opc.Ua.NodeState __current = __queue.Dequeue();
|
|
if (__current is global::Opc.Ua.BaseInstanceState __instance &&
|
|
__instance.TypeDefinitionId == typeDefinitionId)
|
|
{
|
|
__matches.Add(__current);
|
|
}
|
|
__scratch.Clear();
|
|
__current.GetChildren(SystemContext, __scratch);
|
|
for (int __i = 0; __i < __scratch.Count; __i++)
|
|
{
|
|
global::Opc.Ua.BaseInstanceState __child = __scratch[__i];
|
|
if (__child != null && __seen.Add(__child))
|
|
{
|
|
__queue.Enqueue(__child);
|
|
}
|
|
}
|
|
}
|
|
return __matches;
|
|
}
|
|
|
|
private global::Opc.Ua.ArrayOf<global::Opc.Ua.NodeState> __FindByDataTypeId(
|
|
global::Opc.Ua.NodeId dataTypeId)
|
|
{
|
|
if (dataTypeId == null || dataTypeId.IsNull)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
var __matches = new global::System.Collections.Generic.List<global::Opc.Ua.NodeState>();
|
|
var __queue = new global::System.Collections.Generic.Queue<global::Opc.Ua.NodeState>();
|
|
var __seen = new global::System.Collections.Generic.HashSet<global::Opc.Ua.NodeState>();
|
|
var __scratch = new global::System.Collections.Generic.List<global::Opc.Ua.BaseInstanceState>();
|
|
foreach (global::Opc.Ua.NodeState __root in PredefinedNodes.Values)
|
|
{
|
|
if (__root != null && __seen.Add(__root))
|
|
{
|
|
__queue.Enqueue(__root);
|
|
}
|
|
}
|
|
while (__queue.Count > 0)
|
|
{
|
|
global::Opc.Ua.NodeState __current = __queue.Dequeue();
|
|
if (__current is global::Opc.Ua.BaseVariableState __variable &&
|
|
__variable.DataType == dataTypeId)
|
|
{
|
|
__matches.Add(__current);
|
|
}
|
|
__scratch.Clear();
|
|
__current.GetChildren(SystemContext, __scratch);
|
|
for (int __i = 0; __i < __scratch.Count; __i++)
|
|
{
|
|
global::Opc.Ua.BaseInstanceState __child = __scratch[__i];
|
|
if (__child != null && __seen.Add(__child))
|
|
{
|
|
__queue.Enqueue(__child);
|
|
}
|
|
}
|
|
}
|
|
return new global::Opc.Ua.ArrayOf<global::Opc.Ua.NodeState>(
|
|
__matches.ToArray());
|
|
}
|
|
}
|
|
}
|
|
""");
|
|
|
|
/// <summary>
|
|
/// Top-level template for the generated factory class.
|
|
/// </summary>
|
|
public static readonly TemplateString FactoryFile = TemplateString.Parse(
|
|
$$"""
|
|
{{Tokens.CodeHeader}}
|
|
|
|
namespace {{Tokens.NamespacePrefix}}
|
|
{
|
|
/// <summary>
|
|
/// Source-generated <see cref="global::Opc.Ua.Server.INodeManagerFactory"/>
|
|
/// for the <c>{{Tokens.NamespaceUri}}</c> namespace.
|
|
/// </summary>
|
|
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{Tokens.Tool}}", "{{Tokens.Version}}")]
|
|
public partial class {{Tokens.NodeManagerFactoryClassName}} : global::Opc.Ua.Server.IAsyncNodeManagerFactory
|
|
{
|
|
/// <inheritdoc/>
|
|
public virtual global::Opc.Ua.ArrayOf<string> NamespacesUris
|
|
=> new global::Opc.Ua.ArrayOf<string>(new string[] { {{Tokens.NamespaceUri}}{{Tokens.AdditionalNamespaceUris}} });
|
|
|
|
/// <inheritdoc/>
|
|
public virtual global::System.Threading.Tasks.ValueTask<global::Opc.Ua.Server.IAsyncNodeManager> CreateAsync(
|
|
global::Opc.Ua.Server.IServerInternal server,
|
|
global::Opc.Ua.ApplicationConfiguration configuration,
|
|
global::System.Threading.CancellationToken cancellationToken = default)
|
|
{
|
|
return new global::System.Threading.Tasks.ValueTask<global::Opc.Ua.Server.IAsyncNodeManager>(
|
|
new {{Tokens.NodeManagerClassName}}(server, configuration));
|
|
}
|
|
}
|
|
}
|
|
""");
|
|
}
|
|
}
|