mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-29 07:07:24 +08:00
# Description The CTT AliasName conformance units skip or fail against the ConsoleReferenceServer. `AliasName Base` skips with *"No instance of AliasNameType has been found in the address space"*; `Category Tags`, `Category Topics` and `Hierarchy` fail. Part 17 support landed in #3779, but aliases live only inside the `IAliasNameStore` — nothing is browsable, no `AliasNameCategoryType` is nested under another, and the Topics aliases point at the Server object rather than at a `PublishedDataSetType` instance. Part 17 §6.2 clients — the CTT among them — discover aliases by browsing, not only by calling `FindAlias`. This PR materializes the store contents as real nodes and fills the three gaps. ### SDK — `Opc.Ua.Server` * **`DiagnosticsNodeManager.MaterializeRegisteredAliasNameNodesAsync`** (new, opt-in) walks every registered `IAliasNameStore` and creates one `AliasNameType` instance per alias — BrowseName carrying the alias name, `AliasFor` references to its targets, and the inverse `HasAlias` reference on each local target (via `externalReferences`, since targets usually live in another node manager) — plus an `AliasNameCategoryType` instance for every store category the standard NodeSet does not already ship. Categories whose NodeId belongs to another node manager are skipped, so an `AliasNameNodeManager` that also registers its store with the server-wide registry does not get its NodeIds claimed twice. Opt-in: servers that only need the well-known `FindAlias` to answer from their store pay nothing. The nodes are a snapshot taken at address-space creation — later mutations change what `FindAlias` returns but do not add or remove nodes. * **Optional Part 17 methods on the well-known categories.** The same pass instantiates whatever a category declares through `AliasNameCapabilities`: `FindAliasVerbose` (§6.3.3), `AddAliasesToCategory` (§6.3.4), `DeleteAliasesFromCategory` (§6.3.5) and `LastChange` (§6.3.1). Mutations require a `SecurityAdmin` caller on a `SignAndEncrypt` channel; the gate previously private to `AliasNameNodeManager` moved to `AliasNameMethodDispatcher` so both paths share one implementation. * **`LastChange`** is now tracked per category rather than only for the standard `Aliases` node, and the duplicated seeding logic collapsed into one helper. ### Reference server * A nested **`Devices`** category under `TagVariables` holds `Pump1_Status` and `Heater_Power`. `FindAlias` on `TagVariables` still returns all six names through subtree recursion, while `FindAlias` on `Devices` returns exactly two — which is what the Hierarchy unit checks. * `ReferenceServerConfigurationNodeManager` creates three **`PublishedDataSet` instances** under `PublishedDataSets` (`i=17371`) and the Topics aliases now target them, satisfying the *"is a Dataset"* check. These are address-space instances only — no PubSub runtime is added, and the CTT only inspects the target's type definition. ## Note for reviewers — the reserved NodeIds The optional children are created at the NodeIds the OPC Foundation reserves for them (`Aliases.FindAliasVerbose` = `i=24054`, `TagVariables.LastChange` = `i=32854`, …). Those identifiers are allocated in `StandardTypes.csv` but are **not** declared in the ModelDesign and **not** present in the published NodeSet, because the standard address space does not instantiate optional children. The source generator therefore emits no parent-to-instance mapping and no `MethodIds` constants for them, so `DiagnosticsNodeManager.ReservedChildIds` supplies the nine method ids and the two missing `LastChange` ids explicitly, each traceable to its registry row. The 18 argument-property ids do have generated `VariableIds` constants and are referenced through those. I deliberately did **not** "fix" this by declaring the children in `tools/Opc.Ua.SourceGeneration.Core/Design/StandardTypes.xml`: that file is a verbatim copy of upstream `UA-ModelCompiler/Design.v105/StandardTypes.xml` (the only differences today are upstream being newer), so a local edit is lost on the next sync and the NodeIds would silently revert to factory-minted ones. `docs/AliasNames.md` records this. Worth raising upstream separately: `StandardTypes.csv` allocates `Aliases_FindAliasVerbose` and siblings while the ModelDesign never declares those children, so the ModelCompiler cannot emit ids it has itself reserved. If that is ever reconciled, `ReservedChildIds` becomes redundant and deletes cleanly. ## Related Issues - Fixes #4012 ## 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. — **not done: verified on net8.0 only** (Server 4710, InformationModel 1099, Core 4443, plus the client and features alias suites; AOT build clean). Needs a run against net framework and net10 before this leaves draft. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. ### Tests `tests/Opc.Ua.InformationModel.Tests/Aliasname*Tests.cs` mirror the four CTT conformance units and no longer `Assert.Ignore` where the CTT reported failures — the alias suite is 37 tests with no skips. New `AliasnameOptionalMethodsTests` covers the optional methods, their reserved NodeIds, the anonymous-caller denial, an add/find/delete round trip and `LastChange` advancing on mutation. One pre-existing test changed premise: `EnumerateSubCategoriesAsyncOnLeafReturnsEmptyAsync` asserted that `TagVariables` has no sub-categories, which this PR deliberately makes false. It now targets `Topics` (still a leaf) and a new test guards the nesting. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
401 lines
16 KiB
C#
401 lines
16 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.Collections.Generic;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Client;
|
|
|
|
namespace Opc.Ua.InformationModel.Tests
|
|
{
|
|
/// <summary>
|
|
/// Shared helpers for the AliasName conformance tests. Provides constants
|
|
/// for the standard NodeIds defined by OPC UA Part 17 and reusable helper
|
|
/// methods for browsing the Aliases hierarchy and invoking the FindAlias
|
|
/// method on alias categories.
|
|
/// </summary>
|
|
internal static class AliasNameTestHelpers
|
|
{
|
|
public const uint AliasNameTypeId = 23455;
|
|
public const uint AliasNameCategoryTypeId = 23456;
|
|
public const uint AliasNameDataTypeId = 23468;
|
|
public const uint AliasNameDataTypeBinaryEncodingId = 23499;
|
|
public const uint AliasForReferenceTypeId = 23469;
|
|
public const uint AliasesObjectId = 23470;
|
|
|
|
public static readonly NodeId AliasNameTypeNodeId = new(AliasNameTypeId);
|
|
public static readonly NodeId AliasNameCategoryTypeNodeId = new(AliasNameCategoryTypeId);
|
|
public static readonly NodeId AliasNameDataTypeNodeId = new(AliasNameDataTypeId);
|
|
public static readonly NodeId AliasForNodeId = new(AliasForReferenceTypeId);
|
|
public static readonly NodeId AliasesNodeId = new(AliasesObjectId);
|
|
|
|
/// <summary>
|
|
/// Read a single attribute from a node.
|
|
/// </summary>
|
|
public static async Task<DataValue> ReadAttributeAsync(
|
|
ISession session, NodeId nodeId, uint attributeId)
|
|
{
|
|
ReadResponse response = await session.ReadAsync(
|
|
null, 0, TimestampsToReturn.Both,
|
|
new ReadValueId[]
|
|
{
|
|
new() { NodeId = nodeId, AttributeId = attributeId }
|
|
}.ToArrayOf(),
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(response.Results.Count, Is.EqualTo(1));
|
|
return response.Results[0];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Forward-browse a node's hierarchical references and return the
|
|
/// child references.
|
|
/// </summary>
|
|
public static Task<IList<ReferenceDescription>> BrowseChildrenAsync(
|
|
ISession session, NodeId nodeId)
|
|
{
|
|
return BrowseChildrenAsync(
|
|
session, nodeId, ReferenceTypeIds.HierarchicalReferences);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Forward-browse the given reference type from a node and return
|
|
/// the child references.
|
|
/// </summary>
|
|
public static async Task<IList<ReferenceDescription>> BrowseChildrenAsync(
|
|
ISession session, NodeId nodeId, NodeId referenceTypeId)
|
|
{
|
|
BrowseResponse response = await session.BrowseAsync(
|
|
null, null, 0,
|
|
new BrowseDescription[]
|
|
{
|
|
new() {
|
|
NodeId = nodeId,
|
|
BrowseDirection = BrowseDirection.Forward,
|
|
ReferenceTypeId = referenceTypeId,
|
|
IncludeSubtypes = true,
|
|
NodeClassMask = 0,
|
|
ResultMask = (uint)BrowseResultMask.All
|
|
}
|
|
}.ToArrayOf(),
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(response.Results.Count, Is.EqualTo(1));
|
|
Assert.That(StatusCode.IsGood(response.Results[0].StatusCode), Is.True,
|
|
$"Browse of {nodeId} failed: {response.Results[0].StatusCode}");
|
|
|
|
return response.Results[0].References.ToArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Locates the AliasNameCategory child of <see cref="AliasesNodeId"/>
|
|
/// with the given browse-name and the FindAlias method declared on it.
|
|
/// Skips the calling test (Assert.Ignore) when the server does not
|
|
/// expose the category or method.
|
|
/// </summary>
|
|
public static async Task<(NodeId CategoryId, NodeId FindAliasMethodId)>
|
|
FindCategoryAsync(ISession session, string categoryBrowseName)
|
|
{
|
|
IList<ReferenceDescription> children =
|
|
await BrowseChildrenAsync(session, AliasesNodeId).ConfigureAwait(false);
|
|
|
|
// The standard NodeSet exposes empty placeholder TagVariables /
|
|
// Topics objects in namespace 0 with no working FindAlias
|
|
// implementation. Prefer a category whose NodeId is NOT in
|
|
// namespace 0 (i.e. provided by the server's address space).
|
|
NodeId categoryId = NodeId.Null;
|
|
NodeId fallbackId = NodeId.Null;
|
|
foreach (ReferenceDescription child in children)
|
|
{
|
|
if (child.BrowseName.Name != categoryBrowseName ||
|
|
child.NodeClass != NodeClass.Object)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var resolved = ExpandedNodeId.ToNodeId(
|
|
child.NodeId, session.NamespaceUris);
|
|
if (resolved.NamespaceIndex != 0)
|
|
{
|
|
categoryId = resolved;
|
|
break;
|
|
}
|
|
if (fallbackId.IsNull)
|
|
{
|
|
fallbackId = resolved;
|
|
}
|
|
}
|
|
|
|
if (categoryId.IsNull)
|
|
{
|
|
categoryId = fallbackId;
|
|
}
|
|
|
|
if (categoryId.IsNull)
|
|
{
|
|
Assert.Ignore(
|
|
$"Server does not expose an AliasNameCategory '{categoryBrowseName}' under Aliases (i=23470).");
|
|
}
|
|
|
|
NodeId methodId = await FindMethodAsync(
|
|
session, categoryId, "FindAlias").ConfigureAwait(false);
|
|
|
|
if (methodId.IsNull)
|
|
{
|
|
Assert.Ignore(
|
|
$"Server does not expose a FindAlias method on category '{categoryBrowseName}'.");
|
|
}
|
|
|
|
return (categoryId, methodId);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Locates a method node with the given browse-name as a child of
|
|
/// <paramref name="parent"/>. Returns <see cref="NodeId.Null"/>
|
|
/// when no such method exists.
|
|
/// </summary>
|
|
public static async Task<NodeId> FindMethodAsync(
|
|
ISession session, NodeId parent, string methodBrowseName)
|
|
{
|
|
IList<ReferenceDescription> children =
|
|
await BrowseChildrenAsync(session, parent).ConfigureAwait(false);
|
|
|
|
foreach (ReferenceDescription child in children)
|
|
{
|
|
if (child.NodeClass == NodeClass.Method &&
|
|
child.BrowseName.Name == methodBrowseName)
|
|
{
|
|
return ExpandedNodeId.ToNodeId(
|
|
child.NodeId, session.NamespaceUris);
|
|
}
|
|
}
|
|
return NodeId.Null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Calls <c>FindAlias(pattern, referenceTypeFilter)</c> on the given
|
|
/// category and returns the raw <see cref="CallMethodResult"/>.
|
|
/// </summary>
|
|
public static async Task<CallMethodResult> CallFindAliasAsync(
|
|
ISession session,
|
|
NodeId categoryId,
|
|
NodeId findAliasMethodId,
|
|
string pattern,
|
|
NodeId referenceTypeFilter)
|
|
{
|
|
CallResponse response = await session.CallAsync(
|
|
null,
|
|
new CallMethodRequest[]
|
|
{
|
|
new() {
|
|
ObjectId = categoryId,
|
|
MethodId = findAliasMethodId,
|
|
InputArguments = new Variant[]
|
|
{
|
|
new(pattern),
|
|
new(referenceTypeFilter)
|
|
}.ToArrayOf()
|
|
}
|
|
}.ToArrayOf(),
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(response.Results.Count, Is.EqualTo(1));
|
|
return response.Results[0];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Decodes the AliasNameDataType[] returned by FindAlias from the
|
|
/// CallMethodResult's first output argument. The server encodes each
|
|
/// record as { QualifiedName AliasName, NodeId[] ReferencedNodes }.
|
|
/// </summary>
|
|
public static IList<AliasRecord> DecodeAliasResults(
|
|
ISession session, CallMethodResult result)
|
|
{
|
|
var records = new List<AliasRecord>();
|
|
if (result == null || result.OutputArguments.Count == 0)
|
|
{
|
|
return records;
|
|
}
|
|
|
|
if (!result.OutputArguments[0].TryGetValue(out ArrayOf<ExtensionObject> aliasArray))
|
|
{
|
|
return records;
|
|
}
|
|
|
|
for (int i = 0; i < aliasArray.Count; i++)
|
|
{
|
|
ExtensionObject ext = aliasArray.Span[i];
|
|
if (ext.IsNull)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (ext.TryGetValue(out AliasNameDataType typed,
|
|
session.MessageContext) &&
|
|
typed != null)
|
|
{
|
|
NodeId[] refs;
|
|
if (typed.ReferencedNodes.Count > 0)
|
|
{
|
|
refs = new NodeId[typed.ReferencedNodes.Count];
|
|
for (int j = 0; j < typed.ReferencedNodes.Count; j++)
|
|
{
|
|
refs[j] = ExpandedNodeId.ToNodeId(
|
|
typed.ReferencedNodes[j], session.NamespaceUris);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
refs = [];
|
|
}
|
|
records.Add(new AliasRecord(typed.AliasName, refs));
|
|
continue;
|
|
}
|
|
|
|
if (ext.TryGetAsBinary(out ByteString body) && !body.IsNull)
|
|
{
|
|
using var decoder = new BinaryDecoder(
|
|
body.ToArray(), session.MessageContext);
|
|
QualifiedName aliasName = decoder.ReadQualifiedName("AliasName");
|
|
ArrayOf<NodeId> referenced =
|
|
decoder.ReadNodeIdArray("ReferencedNodes");
|
|
records.Add(new AliasRecord(
|
|
aliasName,
|
|
referenced.ToArray() ?? []));
|
|
}
|
|
}
|
|
return records;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Locates a method by BrowseName and fails the test when the server
|
|
/// does not expose it. The optional Part 17 methods do have reserved
|
|
/// NodeIds (StandardTypes.csv), but no generated <c>MethodIds</c>
|
|
/// constants exist for them — the ModelDesign does not declare the
|
|
/// children — so tests resolve them by browsing, as a client
|
|
/// without prior knowledge would.
|
|
/// </summary>
|
|
public static async Task<NodeId> RequireMethodAsync(
|
|
ISession session, NodeId parent, string methodBrowseName)
|
|
{
|
|
NodeId methodId = await FindMethodAsync(session, parent, methodBrowseName)
|
|
.ConfigureAwait(false);
|
|
Assert.That(methodId.IsNull, Is.False,
|
|
$"Expected a '{methodBrowseName}' method under {parent}.");
|
|
return methodId;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Calls a method with the given input arguments and returns the raw
|
|
/// <see cref="CallMethodResult"/> without asserting on its status —
|
|
/// callers that expect a failure inspect it themselves.
|
|
/// </summary>
|
|
public static async Task<CallMethodResult> CallMethodAsync(
|
|
ISession session,
|
|
NodeId objectId,
|
|
NodeId methodId,
|
|
params Variant[] inputArguments)
|
|
{
|
|
CallResponse response = await session.CallAsync(
|
|
null,
|
|
new CallMethodRequest[]
|
|
{
|
|
new() {
|
|
ObjectId = objectId,
|
|
MethodId = methodId,
|
|
InputArguments = inputArguments.ToArrayOf()
|
|
}
|
|
}.ToArrayOf(),
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(response.Results.Count, Is.EqualTo(1));
|
|
return response.Results[0];
|
|
}
|
|
|
|
/// <summary>
|
|
/// Decodes the AliasNameVerboseDataType[] returned by
|
|
/// FindAliasVerbose from the first output argument.
|
|
/// </summary>
|
|
public static IList<AliasNameVerboseDataType> DecodeVerboseAliasResults(
|
|
ISession session, CallMethodResult result)
|
|
{
|
|
var records = new List<AliasNameVerboseDataType>();
|
|
if (result == null || result.OutputArguments.Count == 0)
|
|
{
|
|
return records;
|
|
}
|
|
if (!result.OutputArguments[0].TryGetValue(out ArrayOf<ExtensionObject> aliasArray))
|
|
{
|
|
return records;
|
|
}
|
|
|
|
for (int i = 0; i < aliasArray.Count; i++)
|
|
{
|
|
ExtensionObject ext = aliasArray.Span[i];
|
|
if (!ext.IsNull &&
|
|
ext.TryGetValue(out AliasNameVerboseDataType typed, session.MessageContext) &&
|
|
typed != null)
|
|
{
|
|
records.Add(typed);
|
|
}
|
|
}
|
|
return records;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns true when the referenced node is an instance of
|
|
/// <c>PublishedDataSetType</c> (i=14509) or one of its subtypes —
|
|
/// the "is a Dataset" check the Topics conformance unit applies to
|
|
/// every alias target.
|
|
/// </summary>
|
|
public static async Task<bool> IsPublishedDataSetAsync(
|
|
ISession session, ReferenceDescription target)
|
|
{
|
|
if (target.TypeDefinition.IsNull)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// The session's node cache walks (and memoizes) the subtype
|
|
// chain, so repeated targets of the same type cost one lookup
|
|
// instead of one Browse round trip per hierarchy level.
|
|
return await session.NodeCache.IsTypeOfAsync(
|
|
target.TypeDefinition,
|
|
ObjectTypeIds.PublishedDataSetType,
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Plain record describing a single alias entry returned by FindAlias.
|
|
/// </summary>
|
|
internal sealed record AliasRecord(QualifiedName AliasName, NodeId[] ReferencedNodes);
|
|
}
|
|
}
|