Files
romanett 41db5aca60 Fluent: publish Configure-created nodes' references on foreign-manager nodes (Objects folder placement) (#4331)
# 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>
2026-08-29 10:38:56 +02:00

392 lines
14 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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace Opc.Ua.SourceGeneration
{
internal static partial class Extensions
{
/// <summary>
/// Get options from file options
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public static NodesetFileOptions ToNodeSetOptions(this AnalyzerConfigOptions options)
{
if (options == null)
{
return new NodesetFileOptions();
}
return new NodesetFileOptions
{
Ignore = options.GetBool(nameof(NodesetFileOptions.Ignore), false),
Prefix = options.GetString(nameof(NodesetFileOptions.Prefix), false),
Version = options.GetString(nameof(NodesetFileOptions.Version), false),
Name = options.GetString(nameof(NodesetFileOptions.Name), false),
ModelUri = options.GetString(nameof(NodesetFileOptions.ModelUri), false),
IdentifierFile = options.GetString(nameof(NodesetFileOptions.IdentifierFile), false)
};
}
/// <summary>
/// Create collection
/// </summary>
public static NodesetFileCollection ToNodeSetFileCollection(
this ImmutableArray<(AdditionalText, NodesetFileOptions)> nodeset2Files,
ImmutableArray<AdditionalText> csvFiles,
IFileSystem fileSystem,
ITelemetryContext telemetry)
{
return new NodesetFileCollection(
[.. nodeset2Files.Select(f => (f.Item1.Path, f.Item2))],
[.. csvFiles.Select(f => f.Path)],
fileSystem,
telemetry);
}
/// <summary>
/// Design files end in xml but are not nodeset2.xml files.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool IsDesignOrNodeset2File(this AdditionalText text)
{
return text.HasFileExtension("xml");
}
/// <summary>
/// The canonical, unconditionally recognized WoT Thing Model / Thing
/// Description file extensions.
/// </summary>
internal static readonly string[] WotFileExtensions =
[
".tm.json",
".td.json",
".tm.jsonld",
".td.jsonld"
];
/// <summary>
/// Per-file <c>AdditionalFiles</c> metadata name (without the
/// generator prefix) that opts a plain <c>.jsonld</c> file into WoT
/// model processing. Set
/// <c>&lt;ModelSourceGeneratorWot&gt;true&lt;/ModelSourceGeneratorWot&gt;</c>
/// on the <c>AdditionalFiles</c> item.
/// </summary>
private const string WotOptInPropertyName = "Wot";
/// <summary>
/// WoT Thing Model and Thing Description files supported as model
/// inputs. The canonical <c>.tm.json</c>, <c>.td.json</c>,
/// <c>.tm.jsonld</c> and <c>.td.jsonld</c> extensions are always
/// recognized. A plain <c>.jsonld</c> file is treated as arbitrary
/// JSON-LD — <b>not</b> consumed as a model input — unless the
/// AdditionalFiles item explicitly opts in with
/// <c>ModelSourceGeneratorWot=true</c> metadata.
/// </summary>
public static bool IsWotFile(this AdditionalText text, AnalyzerConfigOptions options)
{
string path = text.Path;
foreach (string extension in WotFileExtensions)
{
if (path.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
if (!path.EndsWith(".jsonld", StringComparison.OrdinalIgnoreCase))
{
return false;
}
// A bare .jsonld (i.e. none of the canonical suffixes above matched)
// is only a WoT input when explicitly opted in per-file: arbitrary
// JSON-LD documents must not be silently consumed as model input.
return options != null &&
options.GetBool(WotOptInPropertyName, buildProperty: false);
}
/// <summary>
/// Identifier files contain at least one legacy identifier CSV row.
/// </summary>
public static bool IsIdentifierFile(this AdditionalText text)
{
if (!text.HasFileExtension("csv"))
{
return false;
}
SourceText sourceText = text.GetText();
if (sourceText == null)
{
return false;
}
foreach (TextLine sourceLine in sourceText.Lines)
{
string line = sourceLine.ToString().TrimStart('\uFEFF').Trim();
if (string.IsNullOrEmpty(line) ||
line.StartsWith("#", StringComparison.Ordinal))
{
continue;
}
string[] columns = line.Split(',');
if (columns.Length < 2)
{
continue;
}
string identifier = columns[1].Trim();
if (uint.TryParse(identifier, out _) ||
(identifier.Length > 1 &&
identifier.StartsWith("\"", StringComparison.Ordinal) &&
identifier.EndsWith("\"", StringComparison.Ordinal)))
{
return true;
}
}
return false;
}
/// <summary>
/// Has file extension check
/// </summary>
public static bool HasFileExtension(this AdditionalText text, string extension)
{
return text.Path.EndsWith("." + extension, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Get value
/// </summary>
/// <typeparam name="T"></typeparam>
public static T GetValue<T>(
this AnalyzerConfigOptions options,
string propertyName,
Func<string, T> converter,
bool buildProperty = true)
{
string prefix = buildProperty ? "build_property" : "build_metadata.AdditionalFiles";
options.TryGetValue(
$"{prefix}.{SourceGenerator.Name}{propertyName}".ToLowerInvariant(),
out string value);
return converter(value);
}
/// <summary>
/// Get integer value from build properties
/// </summary>
public static int GetInteger(
this AnalyzerConfigOptions config,
string propertyName,
bool buildProperty = true)
{
return config.GetValue(propertyName,
s => s != null && int.TryParse(s, out int integer) ?
integer :
0,
buildProperty);
}
/// <summary>
/// Get boolean option from options
/// </summary>
public static bool GetBool(
this AnalyzerConfigOptions config,
string propertyName,
bool buildProperty = true)
{
return config.GetValue(propertyName,
s => string.Equals(s, "true", StringComparison.OrdinalIgnoreCase),
buildProperty);
}
/// <summary>
/// Get string option from options
/// </summary>
public static string GetString(
this AnalyzerConfigOptions config,
string propertyName,
bool buildProperty = true)
{
return config.GetValue(propertyName, s => s, buildProperty)
?? string.Empty;
}
/// <summary>
/// Get string option from options
/// </summary>
public static List<string> GetStrings(
this AnalyzerConfigOptions config,
string propertyName,
bool buildProperty = true)
{
return config.GetValue(propertyName, Split, buildProperty);
static List<string> Split(string s)
{
return s == null ? [] : [.. s
.Split(';', ',', '+')
.Select(e => e.Trim())
.Where(s => !string.IsNullOrEmpty(s))];
}
}
/// <summary>
/// Get namespace information
/// </summary>
public static string GetFullNamespace(this INamedTypeSymbol symbol)
{
var parts = new List<string>();
INamespaceSymbol ns = symbol.ContainingNamespace;
while (ns != null && !ns.IsGlobalNamespace)
{
parts.Insert(0, ns.Name);
ns = ns.ContainingNamespace;
}
return string.Join(".", parts);
}
/// <summary>
/// Get fully qualified type name string with global::
/// prefix and no global namespace
/// </summary>
public static string GetFullyQualifiedTypeName(this ITypeSymbol type)
{
return "global::" +
type.ToDisplayString(
SymbolDisplayFormat.FullyQualifiedFormat
.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted));
}
/// <summary>
/// Check whether the type implements an interface with the
/// given name, regardless of namespace. This is used to check for
/// specific interfaces without needing the full namespace.
/// </summary>
public static bool ImplementsInterface(
this ITypeSymbol type,
string interfaceName)
{
return type.AllInterfaces.Any(i => i.Name == interfaceName);
}
/// <summary>
/// Check if a type symbol has a specific attribute by name.
/// </summary>
public static bool HasAttribute(
this ITypeSymbol type,
string attributeName)
{
return type.GetAttributes().Any(a =>
a.AttributeClass?.Name == attributeName);
}
/// <summary>
/// Get a named argument from the attribute
/// </summary>
public static string GetValue(
this AttributeData attr,
string name)
{
if (attr == null)
{
return null;
}
foreach (KeyValuePair<string, TypedConstant> kvp in attr.NamedArguments)
{
if (kvp.Key == name && kvp.Value.Value is string s)
{
return s;
}
}
return null;
}
/// <summary>
/// Get a named string-array argument from the attribute. Returns
/// <c>null</c> when the argument is absent or empty; entries
/// that are not non-empty strings are skipped.
/// </summary>
public static string[] GetStringArray(
this AttributeData attr,
string name)
{
if (attr == null)
{
return null;
}
foreach (KeyValuePair<string, TypedConstant> kvp in attr.NamedArguments)
{
if (kvp.Key != name ||
kvp.Value.Kind != TypedConstantKind.Array ||
kvp.Value.IsNull)
{
continue;
}
string[] values = [.. kvp.Value.Values
.Select(v => v.Value as string)
.Where(s => !string.IsNullOrEmpty(s))];
return values.Length > 0 ? values : null;
}
return null;
}
/// <summary>
/// Get a named argument from the attribute
/// </summary>
public static int GetInteger(
this AttributeData attr,
string name,
int defaultValue = default)
{
if (attr == null)
{
return defaultValue;
}
foreach (KeyValuePair<string, TypedConstant> kvp in attr.NamedArguments)
{
if (kvp.Key == name && kvp.Value.Value is int i)
{
return i;
}
}
return defaultValue;
}
}
}