mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-19 15:22:15 +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>
266 lines
10 KiB
C#
266 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 System.IO;
|
|
using System.Linq;
|
|
using Opc.Ua.Schema.Model;
|
|
|
|
namespace Opc.Ua.SourceGeneration
|
|
{
|
|
/// <summary>
|
|
/// Model options
|
|
/// </summary>
|
|
public sealed record class DesignFileOptions
|
|
{
|
|
/// <summary>
|
|
/// -version [v104, v105]
|
|
/// </summary>
|
|
public string Version { get; init; }
|
|
|
|
/// <summary>
|
|
/// -id [start id]
|
|
/// </summary>
|
|
public uint StartId { get; init; }
|
|
|
|
/// <summary>
|
|
/// -mv [model version]
|
|
/// </summary>
|
|
public string ModelVersion { get; init; }
|
|
|
|
/// <summary>
|
|
/// -pd [publication date]
|
|
/// </summary>
|
|
public string ModelPublicationDate { get; init; }
|
|
|
|
/// <summary>
|
|
/// -rc
|
|
/// </summary>
|
|
public bool ReleaseCandidate { get; init; } = true;
|
|
|
|
/// <summary>
|
|
/// When <c>true</c>, also emits a <c>{Namespace}NodeManager</c>
|
|
/// (a <c>partial class</c> deriving from
|
|
/// <c>Opc.Ua.Server.AsyncCustomNodeManager</c>) and a matching
|
|
/// <c>{Namespace}NodeManagerFactory</c> implementing
|
|
/// <c>Opc.Ua.Server.INodeManagerFactory</c>.
|
|
/// <para>
|
|
/// The generated manager exposes a
|
|
/// <c>partial void Configure(INodeManagerBuilder builder)</c>
|
|
/// extensibility hook that user code can implement in a sibling
|
|
/// partial to wire callbacks via the fluent
|
|
/// <c>Opc.Ua.Server.Fluent</c> API.
|
|
/// </para>
|
|
/// </summary>
|
|
public bool GenerateNodeManager { get; init; }
|
|
|
|
/// <summary>
|
|
/// Optional override for the namespace of the generated
|
|
/// <c>NodeManager</c> partial. When set, the generator emits
|
|
/// <c>partial class {NodeManagerClassName}</c> in this namespace
|
|
/// instead of using the design file <c>Prefix</c>. Used by the
|
|
/// <c>[NodeManager]</c> attribute discovery path.
|
|
/// </summary>
|
|
public string NodeManagerNamespace { get; init; }
|
|
|
|
/// <summary>
|
|
/// Optional override for the class name of the generated
|
|
/// <c>NodeManager</c> partial. Defaults to
|
|
/// <c>{Prefix}NodeManager</c>. Used by the <c>[NodeManager]</c>
|
|
/// attribute discovery path.
|
|
/// </summary>
|
|
public string NodeManagerClassName { get; init; }
|
|
|
|
/// <summary>
|
|
/// Whether to also emit the <c>{ClassName}Factory</c>. Defaults
|
|
/// to <c>true</c>. Set to <c>false</c> when the consumer wants
|
|
/// to author the factory by hand.
|
|
/// </summary>
|
|
public bool EmitNodeManagerFactory { get; init; } = true;
|
|
|
|
/// <summary>
|
|
/// Additional namespace URIs (beyond the model namespace) that
|
|
/// the generated <c>NodeManager</c> constructor reports to the
|
|
/// base node manager and the generated factory advertises via
|
|
/// <c>NamespacesUris</c>. Used by the <c>[NodeManager]</c>
|
|
/// attribute discovery path
|
|
/// (<c>AdditionalNamespaceUris</c> named argument).
|
|
/// </summary>
|
|
public IReadOnlyList<string> NodeManagerAdditionalNamespaceUris { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Collection of design files and options
|
|
/// </summary>
|
|
public sealed record class DesignFileCollection
|
|
{
|
|
/// <summary>
|
|
/// Design files to generate code for. Typically a single file.
|
|
/// </summary>
|
|
public IReadOnlyList<string> Targets { get; init; } = [];
|
|
|
|
/// <summary>
|
|
/// Design files referenced by <see cref="Targets"/> but not
|
|
/// generated. They provide node resolution only (e.g. when a
|
|
/// target imports types from another companion specification).
|
|
/// </summary>
|
|
public IReadOnlyList<string> Dependencies { get; init; } = [];
|
|
|
|
/// <summary>
|
|
/// Optional identifier file if not same name and side
|
|
/// by side with design files
|
|
/// </summary>
|
|
public string IdentifierFilePath { get; init; }
|
|
|
|
/// <summary>
|
|
/// Design file options
|
|
/// </summary>
|
|
public DesignFileOptions Options { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validate model design
|
|
/// </summary>
|
|
internal static class DesignFileExtensions
|
|
{
|
|
/// <summary>
|
|
/// Get design file groups for processing. A group is a set of design files
|
|
/// in the same common folder with an optional csv file included. Each group
|
|
/// carries the same <see cref="DesignFileCollection.Dependencies"/> so that
|
|
/// cross-model references resolve for every target.
|
|
/// </summary>
|
|
/// <exception cref="ArgumentNullException"><paramref name="collection"/>
|
|
/// is <c>null</c>.</exception>
|
|
public static IEnumerable<DesignFileCollection> Group(
|
|
this DesignFileCollection collection,
|
|
List<string> identifierFiles = null)
|
|
{
|
|
if (collection is null)
|
|
{
|
|
throw new ArgumentNullException(nameof(collection));
|
|
}
|
|
var idFiles = new Dictionary<string, List<string>>();
|
|
if (identifierFiles != null)
|
|
{
|
|
foreach (string idFile in identifierFiles)
|
|
{
|
|
string dir = Path.GetDirectoryName(idFile);
|
|
if (!idFiles.TryGetValue(dir, out List<string> value))
|
|
{
|
|
value = [];
|
|
idFiles[dir] = value;
|
|
}
|
|
value.Add(idFile);
|
|
}
|
|
}
|
|
IReadOnlyList<string> dependencies = collection.Dependencies ?? [];
|
|
return collection.Targets
|
|
.GroupBy(Path.GetDirectoryName)
|
|
.Select(g => new DesignFileCollection
|
|
{
|
|
Targets = [.. g],
|
|
Dependencies = dependencies,
|
|
IdentifierFilePath = idFiles.TryGetValue(g.Key, out List<string> files) ?
|
|
files.FirstOrDefault() : collection.IdentifierFilePath,
|
|
Options = collection.Options
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validates the model design files
|
|
/// </summary>
|
|
public static IModelDesign OpenModelDesign(
|
|
this IFileSystem fileSystem,
|
|
DesignFileCollection designFiles,
|
|
IReadOnlyList<string> exclusions,
|
|
ITelemetryContext telemetry,
|
|
bool useAllowSubtypes = true)
|
|
{
|
|
return OpenModelDesign(
|
|
fileSystem,
|
|
designFiles,
|
|
exclusions,
|
|
telemetry,
|
|
useAllowSubtypes,
|
|
referencedDependencies: null);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Validates the model design files, optionally importing
|
|
/// per-namespace model dependency payloads from referenced
|
|
/// assemblies before validation. The payloads pre-populate the
|
|
/// validator's node table so downstream models can resolve
|
|
/// upstream types without an explicit <c>AdditionalFiles</c>
|
|
/// entry for them.
|
|
/// </summary>
|
|
public static IModelDesign OpenModelDesign(
|
|
this IFileSystem fileSystem,
|
|
DesignFileCollection designFiles,
|
|
IReadOnlyList<string> exclusions,
|
|
ITelemetryContext telemetry,
|
|
bool useAllowSubtypes,
|
|
IReadOnlyDictionary<string, Dependency.ModelDependencyV1> referencedDependencies)
|
|
{
|
|
DesignFileOptions options = designFiles.Options ?? new DesignFileOptions();
|
|
var validator = new ModelDesignValidator(
|
|
fileSystem,
|
|
options.StartId,
|
|
exclusions,
|
|
telemetry,
|
|
SpecificationVersion.V105)
|
|
{
|
|
UseAllowSubtypes = useAllowSubtypes,
|
|
ReleaseCandidate = options.ReleaseCandidate,
|
|
ModelVersion = options.ModelVersion,
|
|
ModelPublicationDate = options.ModelPublicationDate
|
|
};
|
|
|
|
if (referencedDependencies != null)
|
|
{
|
|
foreach (KeyValuePair<string, Dependency.ModelDependencyV1> entry in referencedDependencies)
|
|
{
|
|
if (entry.Value == null)
|
|
{
|
|
continue;
|
|
}
|
|
validator.ImportDependency(entry.Value, prefix: null, name: null);
|
|
}
|
|
}
|
|
|
|
string identifierFilePath = designFiles.IdentifierFilePath;
|
|
validator.Validate(
|
|
designFiles.Targets,
|
|
designFiles.Dependencies ?? [],
|
|
identifierFilePath);
|
|
return validator;
|
|
}
|
|
}
|
|
}
|