Files
UA-.NETStandard/tools/Opc.Ua.SourceGeneration/Extensions.cs
T
Marc SchierandCopilot e73e71184d [WotCon] Add OPC UA WoT Connectivity 1.1 with the Types, source generation, Server and xRegistry work it builds on (#4128)
## Summary

Adds OPC UA WoT Connectivity 1.1 to the stack, together with the Types,
source generation, Server and xRegistry work it is built on. This branch
is the merge point for the fourteen-PR stack that replaced integration
PR #4093; every constituent PR was reviewed and approved separately and
is listed below.

414 files changed, +108,936 / -3,199. Roughly 46k added lines of product
code, 57k of tests, plus samples, tools and documentation.

## Types

- Complete `ExtensionObject` raw-body decoding for binary, XML and JSON
bodies by resolving the concrete type through the message context's
encodeable factory, and simplify the `Variant` structure helpers by
delegating to it (#4128).
- Add `IAtomicFileReplace` as an optional `IFileSystem` capability so
existing external implementations keep working, with atomic publish for
`LocalFileSystem` via `File.Replace`/`File.Move` and for
`VirtualFileSystem` by re-keying the in-memory entry (#4128).
- Add lossless conversion between WoT documents and NodeSet2
(`Opc.Ua.Wot.WotNodeSetConverter`). A byte-exact `uav:nodeSet` envelope
is preserved when requested, the structured `uav:nodes` projection is
used when the readable vocabulary is incomplete, and NodeSet2 is
otherwise synthesized from readable WoT terms. Unmapped JSON members
survive a round trip as pointer-addressed residue (#4131).

## Source generation

- Improve the NodeSet to ModelDesign conversion and the generated node
state (#4132).
- Generate OPC UA models directly from WoT Thing Description files
(#4134).

## Server

- Add live NodeManager shadow and immediate reload. A reload
materializes a new generation beside the active one and switches
atomically; the superseded generation is retired gracefully so existing
MonitoredItems keep being served until they drain, or immediately when
the caller asks for it. Includes the request admission and drain
machinery that lets an orderly shutdown wait for admitted requests
instead of tearing down underneath them (#4147).
- Make subscription transfer between sessions transactional, so a failed
transfer leaves neither session holding a partially moved subscription
(#4150).

## xRegistry

- Allow clients to use explicit registry roots rather than assuming a
well-known location (#4130).

## WoT Connectivity

- Add the WoT Connectivity 1.1 information model: a registry-first
revision layered on the abstract xRegistry base model, incorporating the
complete published OPC 10100-1 v1.02 surface as deprecated nodes in the
same namespace so existing 1.02 clients keep working (#4139).
- Add the protocol binding abstractions and planners that compile WoT
forms into executable plans (#4140).
- Add the HTTP, Modbus, OPC UA and MQTT binding executors (#4144).
- Add the registry and its stores, including document versioning,
validation, dependency resolution and refresh (#4146).
- Add the registry client (#4142).
- Materialize WoT Thing Descriptions into the server address space,
deriving types from Thing Models and instances from Thing Descriptions
(#4154).
- Restore the WoT asset registry bridge so the deprecated 1.02 asset
surface is backed by the registry (#4171).
- Add the WoT Connectivity samples and complete the documentation
(#4156), and restore the remaining coverage and docs (#4172).

## New projects

`src/Opc.Ua.WotCon.Bindings`, `src/Opc.Ua.WotCon.Bindings.Mqtt`,
`tests/Opc.Ua.WotCon.Bindings.Tests`,
`tests/Opc.Ua.WotCon.Samples.Tests`, and the `samples/WotCon`
AggregationServer, AggregationClient and FlatTagServer samples.

## Constituent pull requests

Merged into this branch top-down, each independently approved:

| PR | Title |
| --- | --- |
| #4128 | [Types] Complete ExtensionObject decoding and add an atomic
file replace capability |
| #4131 | [Types] Add lossless conversion between WoT documents and
NodeSet2 |
| #4132 | [SourceGeneration] Improve NodeSet to ModelDesign conversion
and generated node state |
| #4134 | [SourceGeneration] Generate OPC UA models from WoT Thing
Description files |
| #4147 | [Server] Add live NodeManager shadow and immediate reload |
| #4150 | [Server] Make subscription transfer between sessions
transactional |
| #4130 | [XRegistry] Allow clients to use explicit registry roots |
| #4139 | [WotCon] Add the WoT Connectivity 1.1 information model |
| #4140 | [WotCon] Add the WoT protocol binding abstractions and
planners |
| #4144 | [WotCon] Add the HTTP, Modbus, OPC UA and MQTT binding
executors |
| #4146 | [WotCon] Add the WoT Connectivity registry and its stores |
| #4142 | [WotCon] Add the WoT Connectivity registry client |
| #4154 | [WotCon] Materialize WoT Thing Descriptions into the server
address space |
| #4156 | [WotCon] Add the WoT Connectivity samples and complete the
documentation |
| #4171 | Restore WoT asset registry bridge |
| #4172 | Restore WoT coverage and docs |

Supersedes #4093.

## Follow-up

The WoT Connectivity and WoT Binding drafts have moved to 1.1-draft2
since this work was authored. Aligning with that revision - the removed
group vocabulary, the new projection/View construct, the remaining model
vocabulary terms and the two new portable-identity validation rules - is
tracked separately and will follow in its own pull request.

## Validation

Built for every target framework with zero warnings and zero errors, and
validated at the tip of the stack with `Opc.Ua.WotCon.Tests` at 999
passed / 0 failed and `Opc.Ua.Server.Tests` at 4024 passed / 0 failed.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9e6a5abf-3299-4cd1-9855-010fedbf0ad8
2026-08-05 10:14:15 +02:00

363 lines
13 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 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;
}
}
}