Files
UA-.NETStandard/tools/Opc.Ua.SourceGeneration.Core/Generators/NodeManagerGenerator.cs
T
Marc Schier 02ea934a31 Complete fluent node manager extensibility (#4418)
# Description

Complete the fluent node-manager extensibility surface needed by dynamic
and externally backed address spaces.

This change:

- adds virtual node families with cheap NodeId ownership checks, async
materialization, per-operation caching, custom browsing, and
family-level callbacks;
- adds monitored-item pre-creation decisions, complete lifecycle hooks,
async batch hooks, stack-managed custom monitored items, and
subscription-gated polling;
- exposes the startup `ApplicationConfiguration` to generated manager
partials through `FluentNodeManagerBase`;
- fixes typed builder proxy support, concrete object wrapper types, and
fully-qualified generated model composition;
- reports unresolved `[NodeManager]` namespace expressions as
`MODELGEN035` instead of silently dropping them;
- documents the new APIs and compatibility behavior.

## Related Issues

- Fixes #4397
- Fixes #4398
- Fixes #4399
- Fixes #4403
- Fixes #4404
- Fixes #4405

## Validation

- `Opc.Ua.Server.Tests` on `net10.0`: 4,886 passed, 5 skipped.
- `Opc.Ua.SourceGeneration.Core.Tests` on `net10.0`: 3,807 passed, 8
skipped.
- `Opc.Ua.SourceGeneration.Tests` on `net10.0`: 164 passed.
- Runtime and generator regression selections passed on `net48`.
- Review-feedback validation: 376 fluent tests passed on `net10.0`; 22
focused tests passed on `net48`.
- The CI timing regression was repeated five times on `net48` and once
on `net10.0`.
- All 266 applicable GitHub Actions and Azure Pipelines checks,
including CodeQL and coverage, pass on `83c571423`.
- AppVeyor reports an immediate zero-duration no-run failure because
`appveyor.yml` whitelists only the `appveyor` branch; it did not execute
this PR.
- `UA.slnx` builds successfully for `net10.0`; affected project builds
are warning-free.
- The repository-wide `dotnet test UA.slnx` invocation is currently
blocked by the solution's mixed VSTest/Microsoft.Testing.Platform
configuration under the .NET 10 SDK, so the affected test projects were
run individually.

## 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.
- [x] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [x] I have addressed **all** PR feedback received.

---------

Copilot-Session: afaa67c9-fc97-4185-a785-edd54a937d95
2026-09-05 09:25:49 +02:00

208 lines
8.9 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.IO;
using Opc.Ua.Schema.Model;
namespace Opc.Ua.SourceGeneration
{
/// <summary>
/// Emits a partial <c>{Namespace}NodeManager</c> deriving from
/// <c>AsyncCustomNodeManager</c> plus a matching
/// <c>{Namespace}NodeManagerFactory</c> implementing
/// <c>IAsyncNodeManagerFactory</c>. Opt-in via
/// <see cref="DesignFileOptions.GenerateNodeManager"/>.
/// </summary>
/// <remarks>
/// The generated manager wires the predefined nodes from the existing
/// <c>Add{Namespace}(NodeStateCollection, ISystemContext)</c> extension
/// (emitted by <see cref="NodeStateGenerator"/>) and exposes a
/// <c>partial void Configure(INodeManagerBuilder builder)</c> hook for
/// user code-behind. Lifecycle dispatchers (<c>AddPredefinedNode</c>,
/// <c>RemovePredefinedNode</c>, <c>OnMonitoredItemCreated</c>) are wired
/// to the runtime fluent dispatcher so callbacks registered via the
/// builder are invoked at the right times.
/// <para>
/// When an attribute-driven binding supplies a class name and namespace
/// override (via <see cref="DesignFileOptions.NodeManagerClassName"/> and
/// <see cref="DesignFileOptions.NodeManagerNamespace"/>), the generator
/// emits the partial under that user-chosen identity instead of the
/// design-derived defaults. Factory emission can be suppressed via
/// <see cref="DesignFileOptions.EmitNodeManagerFactory"/>.
/// </para>
/// </remarks>
internal sealed class NodeManagerGenerator : IGenerator
{
/// <summary>
/// Optional override for the namespace of the generated partial.
/// Defaults to the design's <c>TargetNamespace.Prefix</c>.
/// </summary>
public string OverrideNamespace { get; init; }
/// <summary>
/// Optional override for the class name of the generated partial.
/// Defaults to <c>{Prefix}NodeManager</c>.
/// </summary>
public string OverrideClassName { get; init; }
/// <summary>
/// When <c>false</c> the matching <c>{ClassName}Factory</c> is
/// not emitted. Defaults to <c>true</c>.
/// </summary>
public bool EmitFactory { get; init; } = true;
/// <summary>
/// Additional namespace URIs (beyond the model namespace) that
/// the generated constructor passes to the base node manager and
/// the generated factory advertises via <c>NamespacesUris</c>.
/// Typically a sample's separate instance namespace. Optional.
/// </summary>
public IReadOnlyList<string> AdditionalNamespaceUris { get; init; }
/// <summary>
/// Create node manager generator.
/// </summary>
public NodeManagerGenerator(IGeneratorContext context)
{
m_context = context ?? throw new ArgumentNullException(nameof(context));
}
/// <inheritdoc/>
public IEnumerable<Resource> Emit()
{
string nsPrefix = m_context.ModelDesign.TargetNamespace.Prefix;
string typeStem = nsPrefix.Replace(".", string.Empty, StringComparison.Ordinal);
string nsUriSymbol = m_context.ModelDesign.Namespaces
.GetConstantSymbolForNamespace(m_context.ModelDesign.TargetNamespace.Value);
string targetNamespace = string.IsNullOrEmpty(OverrideNamespace)
? nsPrefix
: OverrideNamespace;
string targetClass = string.IsNullOrEmpty(OverrideClassName)
? typeStem + "NodeManager"
: OverrideClassName;
string factoryClass = string.IsNullOrEmpty(OverrideClassName)
? typeStem + "NodeManagerFactory"
: OverrideClassName + "Factory";
string fileStem = string.IsNullOrEmpty(OverrideClassName)
? nsPrefix
: OverrideClassName;
var resources = new List<Resource>(2)
{
EmitNodeManager(nsPrefix, targetNamespace, targetClass, typeStem, nsUriSymbol, fileStem)
};
if (EmitFactory)
{
resources.Add(EmitFactoryFile(targetNamespace, targetClass, factoryClass, nsUriSymbol, fileStem));
}
return resources;
}
private TextFileResource EmitNodeManager(
string modelNamespace,
string targetNamespace,
string targetClass,
string typeStem,
string nsUriSymbol,
string fileStem)
{
string fileName = Path.Combine(
m_context.OutputFolder,
CoreUtils.Format("{0}.NodeManager.g.cs", fileStem));
using TextWriter writer = m_context.FileSystem.CreateTextWriter(fileName);
using var templateWriter = new TemplateWriter(writer);
var template = new Template(templateWriter, NodeManagerTemplates.File);
template.AddReplacement(Tokens.NamespacePrefix, targetNamespace);
template.AddReplacement(Tokens.Prefix, modelNamespace);
template.AddReplacement(Tokens.Namespace, typeStem);
template.AddReplacement(Tokens.NodeManagerClassName, targetClass);
template.AddReplacement(Tokens.NamespaceUri, nsUriSymbol);
template.AddReplacement(
Tokens.AdditionalNamespaceUris,
FormatAdditionalNamespaceUris());
template.Render();
return fileName.AsTextFileResource();
}
/// <summary>
/// Renders the additional namespace URIs as a trailing
/// <c>, "uri"</c> argument list, or an empty string when none
/// were configured.
/// </summary>
private string FormatAdditionalNamespaceUris()
{
if (AdditionalNamespaceUris == null || AdditionalNamespaceUris.Count == 0)
{
return string.Empty;
}
var buffer = new System.Text.StringBuilder();
foreach (string uri in AdditionalNamespaceUris)
{
if (string.IsNullOrEmpty(uri))
{
continue;
}
buffer.Append(", ").Append(uri.AsStringLiteral());
}
return buffer.ToString();
}
private TextFileResource EmitFactoryFile(
string targetNamespace,
string targetClass,
string factoryClass,
string nsUriSymbol,
string fileStem)
{
string fileName = Path.Combine(
m_context.OutputFolder,
CoreUtils.Format("{0}.NodeManagerFactory.g.cs", fileStem));
using TextWriter writer = m_context.FileSystem.CreateTextWriter(fileName);
using var templateWriter = new TemplateWriter(writer);
var template = new Template(templateWriter, NodeManagerTemplates.FactoryFile);
template.AddReplacement(Tokens.NamespacePrefix, targetNamespace);
template.AddReplacement(Tokens.NodeManagerClassName, targetClass);
template.AddReplacement(Tokens.NodeManagerFactoryClassName, factoryClass);
template.AddReplacement(Tokens.NamespaceUri, nsUriSymbol);
template.AddReplacement(
Tokens.AdditionalNamespaceUris,
FormatAdditionalNamespaceUris());
template.Render();
return fileName.AsTextFileResource();
}
private readonly IGeneratorContext m_context;
}
}