mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 22:55:08 +08:00
5795e50b58
* Add async read/write hooks to BaseVariableState and AsyncCustomNodeManager
Introduces an end-to-end async path for variable Value-attribute reads
and writes that does not require holding lock(this) while the user
callback executes:
* New AttributeReadResult, AttributeSimpleReadResult and AttributeWriteResult
readonly record structs in NodeState carry the typed result of an async
Value-attribute hook (no ref/out params across await).
* Four new async delegates (NodeValueEventHandlerAsync,
NodeValueSimpleEventHandlerAsync, NodeValueWriteEventHandlerAsync,
NodeValueSimpleWriteEventHandlerAsync) sit alongside the existing sync
hooks.
* NodeState gains virtual ReadAttributeAsync / WriteAttributeAsync methods.
The default implementation wraps the synchronous call in lock(this) so
callers that have not opted into async hooks see bit-identical behaviour.
* BaseVariableState exposes OnReadValueAsync, OnSimpleReadValueAsync,
OnWriteValueAsync and OnSimpleWriteValueAsync slots and overrides the new
virtuals to dispatch to them WITHOUT holding the lock during the await.
On simple-read the framework still applies index range, data encoding and
copy policy; on simple-write the cached value/status/timestamp are
updated under lock after the hook completes.
* AsyncCustomNodeManager.ReadAsync and WriteAsync now await the new
ReadAttributeAsync / WriteAttributeAsync entry points instead of taking
lock(source) around the synchronous call. Existing per-source locking
semantics are preserved by the default async wrappers.
* The fluent INodeBuilder surface gains four new async OnRead/OnWrite
overloads that wire to the new BaseVariableState slots, with the same
ThrowIfSlotOccupied + null-check pattern as the sync overloads.
* Add typed IVariableBuilder<T> fluent surface
Adds typed sub-interfaces and impls so the existing fluent surface
can expose simple Func<T> / Action<T> / Func<CancellationToken,
ValueTask<T>> overloads for variables — without losing the lower-level
Variant-based overloads on INodeBuilder.
* IVariableBuilder<TValue> + VariableBuilder<TValue> derive from
INodeBuilder<BaseVariableState> / NodeBuilder<BaseVariableState>
(NodeBuilder<TState> unsealed).
* Marshalling uses Variant.AsBoxedObject(BoxingBehavior.Legacy) for
reads and Variant(object) for writes; the AOT-unsafe write path is
scoped-suppressed with a TODO pointing at the planned per-type
generated walker.
* INodeManagerBuilder gains Variable<T>(string),
Variable<T>(NodeId), VariableFromTypeId<T>(NodeId),
VariableFromTypeId<T>(NodeId, QualifiedName).
Server library builds clean across all 6 TFMs.
* Add relative-child traversal API on INodeBuilder
Adds INodeBuilder.Child(QualifiedName), Child<TState>(QualifiedName)
and Variable<TValue>(QualifiedName) so source-generated typed
wrappers can walk one segment at a time without re-resolving from
the manager root. Resolution uses NodeState.FindChild and reuses
NodeManagerBuilder.ToVariableBuilder to keep the typed-variable
marshalling story consistent.
Adds 7 NUnit cases (Fluent category) covering the happy path,
type-mismatch, null/missing browse-name, and non-variable
rejection. All 66 fluent tests pass.
* Mix old + new fluent APIs in MinimalBoilerServer demo
BoilerNodeManager.Configure now exercises five wiring styles:
(1) browse-path with the legacy ref-Variant callback
(2) absolute NodeId with the legacy ref-Variant callback
(3) typed Variable<double>(NodeId) + simple Func<double> sync getter
(4) typed Variable<double>(NodeId) + Func<CancellationToken, ValueTask<double>>
async getter — exercises the BaseVariableState.OnReadValueAsync
slot end-to-end through AsyncCustomNodeManager.ReadAsync
(5) NodeFromTypeId with OnNodeAdded lifecycle hook
All five styles compose against the same INodeManagerBuilder, with
the typed and async callbacks pulling in the new IVariableBuilder<T>
surface (committed at e557ecdd9) and the BaseVariableState async
path (committed at 2e2efb4ad).
* Add async-hook tests for BaseVariableState
15 NUnit cases covering the new On{Read,Write}ValueAsync and On
Simple{Read,Write}ValueAsync slots plus the
ReadAttributeAsync/WriteAttributeAsync overrides on
BaseVariableState:
* full async slot routes Value reads/writes
* lock(this) is released around the awaited handler
* simple async slot reapplies cached StatusCode and respects index
ranges (BadIndexRangeInvalid for non-null ranges)
* exceptions and OperationCanceledException from the hook are
caught and surfaced as BadUnexpectedError, mirroring the sync flow
* CancellationToken propagates to the hook
* cache (m_value, m_statusCode, m_timestamp) is updated on success
and skipped on Bad return
* fallback to base sync ReadAttribute/WriteAttribute when no async
slot is set (preserves today's lock(this) semantics)
* non-Value attributes never invoke the async hook
* CurrentRead/CurrentWrite access checks short-circuit before the
hook runs
All 596 State tests pass on net10.0.
* Add round-trip tests for typed IVariableBuilder<T>
Covers the typed Func<T>/Action<T>/Func<...,ValueTask<T>> overloads
on IVariableBuilder<TValue>: each registers the appropriate hook
slot on the underlying BaseDataVariableState, and driving the
variable through ReadAttribute/WriteAttribute (sync) and
ReadAttributeAsync/WriteAttributeAsync (async) reproduces the
typed values the user supplied.
* Add typed model-traversal source generator
Adds FluentBuilderGenerator that walks the design's predefined-instance tree and emits a typed sibling for every NodeManagerBuilder. Each generated wrapper exposes IntelliSense-friendly accessors for child instances, variables (IVariableBuilder<T>) and methods (sync/async OnCall) so wiring sites become builder.Boilers.Boiler__1.LCX001.Measurement.OnRead(...) instead of a stringly typed browse path. The NodeManager template now also emits a Configure(I{Manager}NodeManagerBuilder) partial alongside the existing Configure(INodeManagerBuilder); both partials run, both are optional, and the typed surface is fully AOT-safe (no dynamic, no MakeGenericType, no reflection).
* Add tests for the typed model-traversal source generator
Adds 9 snapshot tests in Tests/Opc.Ua.SourceGeneration.Core.Tests covering the FluentBuilderGenerator's opt-in flag, typed-manager-interface and proxy emission, internal-sealed visibility, lazy child resolution via Context.NamespaceUris.GetIndexOrAppend, IVariableBuilder<TValue> accessors, sync+async OnCall overloads on method wrappers, and the dual Configure(INodeManagerBuilder)/Configure(I{Manager}NodeManagerBuilder) partial wiring in the NodeManager template. Adds 2 end-to-end AOT tests in Tests/Opc.Ua.Aot.Tests that exercise typed-traversal sync read on LCX001/Measurement and typed-traversal async OnCall on Simulation/Halt through the AOT-compiled MinimalBoilerServer fixture.
* Document the typed model-traversal Configure(I{Manager}NodeManagerBuilder) partial
293 lines
14 KiB
C#
293 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.IO;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Logging;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Tests;
|
|
|
|
namespace Opc.Ua.SourceGeneration.Generator.Tests
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for the <see cref="NodeManagerGenerator"/>: verify the
|
|
/// opt-in flag, the file pair, and the structural shape of the
|
|
/// emitted partial NodeManager + factory.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Generator")]
|
|
[SetCulture("en-us")]
|
|
[SetUICulture("en-us")]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public class NodeManagerGeneratorTests
|
|
{
|
|
[Test]
|
|
public void Emit_WithoutOptIn_ProducesNoNodeManagerFiles()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: false);
|
|
|
|
Assert.That(files.Keys, Has.None.EndsWith(".NodeManager.g.cs"));
|
|
Assert.That(files.Keys, Has.None.EndsWith(".NodeManagerFactory.g.cs"));
|
|
}
|
|
|
|
[Test]
|
|
public void Emit_WithOptIn_ProducesNodeManagerAndFactoryFiles()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
|
|
|
|
Assert.That(files.Keys, Has.Some.EndsWith(".NodeManager.g.cs"),
|
|
"Generator should emit a NodeManager file when GenerateNodeManager=true");
|
|
Assert.That(files.Keys, Has.Some.EndsWith(".NodeManagerFactory.g.cs"),
|
|
"Generator should emit a NodeManagerFactory file when GenerateNodeManager=true");
|
|
}
|
|
|
|
[Test]
|
|
public void EmittedNodeManager_HasRequiredStructuralMembers()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
|
|
|
|
string mgr = files.Single(kv => kv.Key.EndsWith(".NodeManager.g.cs", StringComparison.Ordinal)).Value;
|
|
|
|
// Inheritance and partial — required so users can extend.
|
|
Assert.That(mgr, Does.Contain(": global::Opc.Ua.Server.Fluent.FluentNodeManagerBase"));
|
|
Assert.That(mgr, Does.Match(@"public\s+partial\s+class\s+\w+NodeManager"));
|
|
|
|
// Lifecycle overrides that wire the runtime fluent dispatcher.
|
|
Assert.That(mgr, Does.Contain("LoadPredefinedNodesAsync"));
|
|
Assert.That(mgr, Does.Contain("CreateAddressSpaceAsync"));
|
|
Assert.That(mgr, Does.Contain("AddPredefinedNodeAsync"));
|
|
Assert.That(mgr, Does.Contain("RemovePredefinedNodeAsync"));
|
|
Assert.That(mgr, Does.Contain("OnMonitoredItemCreated"));
|
|
|
|
// The user code-behind hook + the runtime builder type.
|
|
Assert.That(mgr, Does.Contain("partial void Configure("));
|
|
Assert.That(mgr, Does.Contain("global::Opc.Ua.Server.Fluent.NodeManagerBuilder"));
|
|
Assert.That(mgr, Does.Contain("global::Opc.Ua.Server.Fluent.INodeManagerBuilder"));
|
|
|
|
// The Configure/Seal sequence inside CreateAddressSpace must be
|
|
// wired before any NotifyNodeAdded replays. Order is part of
|
|
// the contract and is exercised by the hybrid integration test.
|
|
int idxConfigure = mgr.IndexOf("Configure(__m_builder)", StringComparison.Ordinal);
|
|
int idxSeal = mgr.IndexOf(".Seal()", StringComparison.Ordinal);
|
|
int idxNotify = mgr.IndexOf("NotifyNodeAdded(", StringComparison.Ordinal);
|
|
Assert.That(idxConfigure, Is.GreaterThan(0), "Configure call must be emitted");
|
|
Assert.That(idxSeal, Is.GreaterThan(idxConfigure), "Seal must run after Configure");
|
|
Assert.That(idxNotify, Is.GreaterThan(idxSeal), "NotifyNodeAdded replay must run after Seal");
|
|
}
|
|
|
|
[Test]
|
|
public void EmittedFactory_IsExtensible()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
|
|
|
|
string factory = files.Single(kv => kv.Key.EndsWith(".NodeManagerFactory.g.cs", StringComparison.Ordinal)).Value;
|
|
|
|
// Must NOT be sealed: users with Boiler-style customization
|
|
// need to subclass the factory to register additional namespaces
|
|
// or to swap in a hand-written manager subclass.
|
|
Assert.That(factory, Does.Not.Match(@"sealed\s+partial\s+class\s+\w+NodeManagerFactory"),
|
|
"Generated factory must not be sealed so users can subclass it");
|
|
Assert.That(factory, Does.Match(@"public\s+partial\s+class\s+\w+NodeManagerFactory"));
|
|
|
|
// Members must be virtual so subclasses can override
|
|
// (extending NamespacesUris or returning a custom manager).
|
|
Assert.That(factory, Does.Match(@"public\s+virtual\s+global::Opc\.Ua\.ArrayOf<string>\s+NamespacesUris"));
|
|
Assert.That(factory, Does.Match(
|
|
@"public\s+virtual\s+global::System\.Threading\.Tasks\.ValueTask<global::Opc\.Ua\.Server\.IAsyncNodeManager>\s+CreateAsync"));
|
|
|
|
Assert.That(factory, Does.Contain(": global::Opc.Ua.Server.IAsyncNodeManagerFactory"));
|
|
}
|
|
|
|
[Test]
|
|
public void EmittedFiles_AreAutoGenerated_AndUseGlobalQualifiedTypes()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: true);
|
|
|
|
foreach (KeyValuePair<string, string> kv in files
|
|
.Where(kv => kv.Key.EndsWith(".NodeManager.g.cs", StringComparison.Ordinal) ||
|
|
kv.Key.EndsWith(".NodeManagerFactory.g.cs", StringComparison.Ordinal)))
|
|
{
|
|
Assert.That(kv.Value, Does.StartWith("// <auto-generated />"),
|
|
$"{kv.Key} must start with the auto-generated marker");
|
|
Assert.That(kv.Value, Does.Contain("[global::System.CodeDom.Compiler.GeneratedCodeAttribute("),
|
|
$"{kv.Key} must carry the GeneratedCode attribute");
|
|
// No bare 'Opc.Ua.' prefixes — everything goes via global::
|
|
// to survive use-site namespace conflicts (matches the rest
|
|
// of the source-generation output).
|
|
int bare = CountUnqualifiedOpcUaUses(kv.Value);
|
|
Assert.That(bare, Is.Zero,
|
|
$"{kv.Key} must use global:: qualification only ({bare} bare uses found)");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// CreateInstanceOf<X> factories must emit AccessRestrictions and
|
|
/// RolePermissions inherited from the type's DefaultAccessRestrictions /
|
|
/// DefaultRolePermissions for ObjectType, VariableType and MethodType.
|
|
/// Regression test for the source-generated factory missing these
|
|
/// attributes when the type declares Default* permissions.
|
|
/// </summary>
|
|
[Test]
|
|
public void CreateInstanceOf_EmitsAccessRestrictionsAndRolePermissionsFromType()
|
|
{
|
|
Dictionary<string, string> files = GenerateForTestModel(generateNodeManager: false);
|
|
|
|
string ex = files
|
|
.Single(kv => kv.Key.EndsWith(".NodeStates.ex.g.cs", StringComparison.Ordinal))
|
|
.Value;
|
|
|
|
string variableFactory = ExtractFactoryBody(ex, "CreateInstanceOfRestrictedVariableType");
|
|
Assert.That(variableFactory, Does.Contain(
|
|
"state.AccessRestrictions = global::Opc.Ua.AccessRestrictionType.EncryptionRequired"));
|
|
Assert.That(variableFactory, Does.Contain(
|
|
"state.RolePermissions = new global::Opc.Ua.RolePermissionType[]"));
|
|
|
|
string objectFactory = ExtractFactoryBody(ex, "CreateInstanceOfRestrictedObjectType");
|
|
Assert.That(objectFactory, Does.Contain(
|
|
"state.AccessRestrictions = global::Opc.Ua.AccessRestrictionType.EncryptionRequired"));
|
|
Assert.That(objectFactory, Does.Contain(
|
|
"state.RolePermissions = new global::Opc.Ua.RolePermissionType[]"));
|
|
|
|
string methodFactory = ExtractFactoryBody(ex, "CreateInstanceOfRestrictedMethodType");
|
|
Assert.That(methodFactory, Does.Contain(
|
|
"state.AccessRestrictions = global::Opc.Ua.AccessRestrictionType.SigningRequired"));
|
|
Assert.That(methodFactory, Does.Contain(
|
|
"state.RolePermissions = new global::Opc.Ua.RolePermissionType[]"));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Extracts the body of a generated factory method (from the line that
|
|
/// declares it through the matching closing brace) so individual
|
|
/// factories can be asserted on without false matches from other
|
|
/// factories sharing token names.
|
|
/// </summary>
|
|
private static string ExtractFactoryBody(string source, string methodName)
|
|
{
|
|
string[] lines = source.Split('\n');
|
|
for (int i = 0; i < lines.Length; i++)
|
|
{
|
|
if (!lines[i].Contains("public static ", StringComparison.Ordinal) ||
|
|
!lines[i].Contains(methodName + "(", StringComparison.Ordinal))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
int braces = 0;
|
|
bool started = false;
|
|
var sb = new StringBuilder();
|
|
for (int j = i; j < lines.Length; j++)
|
|
{
|
|
sb.AppendLine(lines[j]);
|
|
foreach (char c in lines[j])
|
|
{
|
|
if (c == '{')
|
|
{
|
|
braces++;
|
|
started = true;
|
|
}
|
|
else if (c == '}')
|
|
{
|
|
braces--;
|
|
}
|
|
}
|
|
if (started && braces == 0)
|
|
{
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|
|
Assert.Fail("Method definition not found: " + methodName);
|
|
return string.Empty;
|
|
}
|
|
|
|
private static Dictionary<string, string> GenerateForTestModel(bool generateNodeManager)
|
|
{
|
|
const string designFile = "TestModel.xml";
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create(logLevel: LogLevel.Error);
|
|
using var fileSystem = new VirtualFileSystem();
|
|
string resources = Path.Combine(Directory.GetCurrentDirectory(), "Resources");
|
|
|
|
Generators.GenerateCode(new DesignFileCollection
|
|
{
|
|
Targets = [Path.Combine(resources, designFile)],
|
|
IdentifierFilePath = Path.Combine(
|
|
resources,
|
|
Path.GetFileNameWithoutExtension(designFile) + ".csv"),
|
|
Options = new DesignFileOptions
|
|
{
|
|
GenerateNodeManager = generateNodeManager
|
|
}
|
|
}, fileSystem, string.Empty, telemetry);
|
|
|
|
return fileSystem.CreatedFiles
|
|
.Where(c => Path.GetExtension(c) == ".cs")
|
|
.ToDictionary(c => c, c => Encoding.UTF8.GetString(fileSystem.Get(c)));
|
|
}
|
|
|
|
private static int CountUnqualifiedOpcUaUses(string source)
|
|
{
|
|
int count = 0;
|
|
const string needle = "Opc.Ua.";
|
|
foreach (string line in source.Split('\n'))
|
|
{
|
|
string trimmed = line.TrimStart();
|
|
// Skip XML doc comments and block-comment continuations —
|
|
// they reference type names cosmetically, not as code.
|
|
if (trimmed.StartsWith("///", StringComparison.Ordinal) ||
|
|
trimmed.StartsWith('*') ||
|
|
trimmed.StartsWith("//", StringComparison.Ordinal))
|
|
{
|
|
continue;
|
|
}
|
|
int idx = 0;
|
|
while ((idx = line.IndexOf(needle, idx, StringComparison.Ordinal)) >= 0)
|
|
{
|
|
if (idx >= 8 && line.Substring(idx - 8, 8) == "global::")
|
|
{
|
|
idx += needle.Length;
|
|
continue;
|
|
}
|
|
// Allow the 'Opc.Ua.SourceGeneration.Core' GeneratedCode tool name.
|
|
if (idx >= 1 && line[idx - 1] == '"')
|
|
{
|
|
idx += needle.Length;
|
|
continue;
|
|
}
|
|
count++;
|
|
idx += needle.Length;
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
}
|
|
}
|