Files
UA-.NETStandard/tests/Opc.Ua.Server.Tests/NodeManager/StartupExternalReferenceTests.cs
Marc Schier be61d598a9 Fix startup NodeManager lifecycle and imported method arguments (#4427)
# Description

Make startup-composed application NodeManagers participate in the live
lifecycle and bind imported NodeSet2 Method argument properties to their
typed `MethodState` children.

This change:

- adopts application NodeManagers created before startup into
`INodeManagerLifecycle.Registrations` after server startup succeeds,
while keeping diagnostics, configuration, and core managers protected;
- retains per-manager startup external-reference ownership and exact
routing positions so reload, removal, rollback, overlapping namespaces,
synchronous adapters, and server restart preserve existing behavior;
counted immutable reference snapshots avoid quadratic startup matching;
- rejects duplicate factory output across active, unpublished, and
retired lifecycle generations without deleting or disposing the live
manager; callers can catch the public
`NodeManagerAlreadyRegisteredException`;
- binds valid namespace-zero `Argument[]` `PropertyType`
`InputArguments` and `OutputArguments` Variables to
`MethodState.InputArguments` and `MethodState.OutputArguments` from
either `HasProperty` direction, without requiring `ParentNodeId`,
including local namespace-URI reference targets;
- preserves authored metadata during NodeSet typed-child promotion
without changing the initialization behavior of unrelated generated
nodes;
- retains generic-import guards for custom and malformed signatures,
duplicate standard-signature validation, and upstream factory-driven
generated-slot replacement and reconciliation callbacks;
- updates lifecycle and Runtime NodeSet documentation and clarifies
`OnServerStartedAsync` timing for both `StartAsync` overloads, including
the unopened default host returned to the caller.

This is a focused follow-up to #4418. That PR preserves registrations
from multiple fluent builders, but does not change lifecycle ownership
or NodeSet child typing. The branch includes upstream `master` through
`da7412c42`, including #4396, #4432, #4437, #4438, and #4440.

The completed review fixes in `686d0561f` are included. The latest base
merge (`a29fc6ca8`) combines them with #4432's shared batch/fluent
importer and generated state factories. One iterative linker supports
available parent nodes, deferred parent side tables, application-owned
handles, and placeholder reconciliation while retaining reference-driven
Method argument binding and URI handling. Upstream cancellation, GDS
assembly renames, certificate leak scoping, and xRegistry changes are
preserved.

## Related Issues

- Fixes #4421
- Fixes #4422

## CI regression fix

`e1a4436f0` fixes the GDS failure reported on Ubuntu and macOS. Copying
permission metadata in general `NodeState` initialization applied
`SecurityAdmin`-only defaults to generated GDS custom certificate groups
and denied their existing GDS-admin Browse requests. Metadata
preservation is now confined to NodeSet typed-child promotion; imported
Method argument permissions remain intact, while unrelated generated
nodes retain their existing initialization behavior.

Local Release validation also exposed a 260-character certificate path
in the startup-failure test added by this PR. Its isolated PKI now uses
a short temporary path. No assertions, authorization checks, or CI gates
were weakened, and no pre-existing tests were changed.

## macOS ARM64 NativeAOT suspension

Per maintainer request, `a15971f32` suspends only the failing
`macos-latest` / `osx-arm64` NativeAOT matrix entry. Re-enabling it once
the compiler contains the runtime fix is tracked in #4443. Intel macOS,
Linux, and Windows NativeAOT coverage, managed macOS tests, and all
other CI gates remain enabled. This is an explicit coverage suspension,
not a claim that the underlying compiler/linker defect is fixed.

The macOS ARM64 NativeAOT job on `a29fc6ca8` fails during native linking
with
`ld: Assertion failed: (_addend == uniqueIndex && "too many large
addends")`.
Both attempts of [run
34191755950](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/34191755950)
hit the same assertion before the native test executable can run; the
build/test summary failure is downstream.

This matches the NativeAOT Mach-O relocation issue in
dotnet/runtime#119380, fixed by relocation-anchor emission in
dotnet/runtime#124721 and its .NET 10 backport dotnet/runtime#132171.
The failing `Microsoft.DotNet.ILCompiler` 10.0.11 package's nuspec
points to `dotnet/dotnet` commit
`e2f47b0110ed922f21a1522da67279133ce28f32` (July 23); its object writer
does not contain the anchor fix merged on August 12. Version 10.0.11 is
currently the latest stable package.

The base commit passed on the same runner image and SDK, so this is not
being dismissed as a generally broken runner or a test flake. The
precise PR-specific object-layout trigger has not been isolated. A
compiler containing the relocation fix is needed before restoring the
lane. No test code, assertions, coverage thresholds, or shared tooling
settings were changed.

## Validation

Latest base-merge validation on both `net10.0` and `net48`, Release:

- Import helpers and argument-binding regressions: 51 passed per
framework.
- Batch/fluent import, generated-state overlays, runtime/startup
lifecycle, cross-source references, routing, reference snapshots, and
node-authoring selection: 344 passed per framework.
- Merge-specific cases cover available Method parents with
forward/inverse and URI/index references while retaining an
application-owned `NodeId` handle.
- The unchanged upstream `NodeSetImportIntegrationTests.cs:210` CA1861
warning remains; no diagnostic suppression or unrelated cleanup was
added.

Release CI-fix validation on both `net10.0` and `net48`:

- `CustomCertificateGroupIntegrationTest`: 4 passed, including the
unchanged CI failure.
- `UANodeSetHelpersTests`: 8 passed, including imported security
metadata.
- `StartupRuntimeNodeSetLifecycleTests`: 5 passed.

Earlier Debug merge and review validation on both frameworks:

- Lifecycle, RuntimeNodeSet, fluent, and OperationContext selection
after merging `978e6d1af`: 638 passed per framework.
- Startup/transport-binding and RuntimeNodeSet integration selection
after merging `017856f4a`: 28 passed per framework.
- Public exception contract and duplicate-registration selection in
`fbf08428b`: 6 passed per framework.

Targeted test invocations rebuilt the affected projects successfully.
The full `UA.slnx` suite was not rerun locally.

## Checklist

- [ ] 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.
- [x] I have addressed **all** PR feedback received.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 2bb8a834-7695-4ae6-84cb-2471c76d1b12
2026-09-08 11:11:53 +00:00

237 lines
11 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.Server.Tests.NodeManager
{
/// <summary>
/// Exercises reference snapshots through real startup and lifecycle adoption.
/// </summary>
[TestFixture]
[Parallelizable]
public sealed class StartupExternalReferenceTests
{
[TestCase("Unchanged")]
[TestCase("Reordered")]
[TestCase("Cloned")]
[TestCase("Removed")]
public async Task StartupDoesNotClaimExistingReferencesAsync(string mutation)
{
IReference first = Reference(1);
IReference second = Reference(2);
IAsyncNodeManager original = Manager(references =>
{
references[ObjectIds.ObjectsFolder] = [first, Reference(1), second];
references[ObjectIds.ViewsFolder] = [Reference(3)];
});
IAsyncNodeManager observer = Manager(references =>
{
switch (mutation)
{
case "Reordered":
references[ObjectIds.ObjectsFolder] =
references[ObjectIds.ObjectsFolder].Reverse().ToList();
break;
case "Cloned":
references[ObjectIds.ObjectsFolder] = [Reference(1), Reference(1), Reference(2)];
break;
case "Removed":
references[ObjectIds.ObjectsFolder] = [Reference(1)];
references.Remove(ObjectIds.ViewsFolder);
break;
case "Unchanged":
break;
default:
throw new ArgumentOutOfRangeException(nameof(mutation));
}
});
using MasterNodeManager master = CreateMaster([original, observer]);
await master.StartupAsync().ConfigureAwait(false);
ArrayOf<PreparedNodeManager> prepared = await ((IDynamicNodeManagerHost)master)
.TakeStartupNodeManagersAsync().ConfigureAwait(false);
Assert.That(prepared, Has.Count.EqualTo(2));
Assert.That(prepared[0].ExternalReferences[ObjectIds.ObjectsFolder], Has.Count.EqualTo(3));
Assert.That(prepared[0].ExternalReferences[ObjectIds.ObjectsFolder][0], Is.SameAs(first));
Assert.That(prepared[1].ExternalReferences, Is.Empty);
}
[Test]
public async Task StartupPreservesAddedMultiplicityOrderAndIdentityAsync()
{
IReference extraDuplicate = Reference(1);
IReference otherType = new NodeStateReference(ReferenceTypeIds.HasComponent, false, new NodeId(1u, 2));
IReference otherDirection = new NodeStateReference(ReferenceTypeIds.Organizes, true, new NodeId(1u, 2));
IReference stringTarget = new NodeStateReference(ReferenceTypeIds.Organizes, false, new NodeId("1", 2));
IReference newSource = Reference(3);
IAsyncNodeManager first = Manager(references =>
references[ObjectIds.ObjectsFolder] = [Reference(1), Reference(1), Reference(2)]);
IAsyncNodeManager second = Manager(references =>
{
references[ObjectIds.ObjectsFolder] =
[
Reference(2), Reference(1), Reference(1), extraDuplicate, otherType, otherDirection, stringTarget
];
references[ObjectIds.ViewsFolder] = [newSource];
});
IAsyncNodeManager third = Manager(_ => { });
using MasterNodeManager master = CreateMaster([first, second, third]);
await master.StartupAsync().ConfigureAwait(false);
ArrayOf<PreparedNodeManager> prepared = await ((IDynamicNodeManagerHost)master)
.TakeStartupNodeManagersAsync().ConfigureAwait(false);
IList<IReference> additions = prepared[1].ExternalReferences[ObjectIds.ObjectsFolder];
Assert.Multiple(() =>
{
Assert.That(additions, Has.Count.EqualTo(4));
Assert.That(additions[0], Is.SameAs(extraDuplicate));
Assert.That(additions[1], Is.SameAs(otherType));
Assert.That(additions[2], Is.SameAs(otherDirection));
Assert.That(additions[3], Is.SameAs(stringTarget));
Assert.That(prepared[1].ExternalReferences[ObjectIds.ViewsFolder][0], Is.SameAs(newSource));
Assert.That(prepared[2].ExternalReferences, Is.Empty);
});
}
[TestCase("Type")]
[TestCase("Direction")]
[TestCase("Target")]
public async Task StartupSnapshotsMutableReferenceValuesAsync(string changedField)
{
var mutable = new MutableReference(Reference(1));
IAsyncNodeManager first = Manager(references =>
references[ObjectIds.ObjectsFolder] = [mutable]);
IAsyncNodeManager second = Manager(references =>
{
switch (changedField)
{
case "Type":
mutable.ReferenceTypeId = ReferenceTypeIds.HasProperty;
break;
case "Direction":
mutable.IsInverse = true;
break;
case "Target":
mutable.TargetId = new ExpandedNodeId("remote", "urn:test:remote", 1);
break;
default:
throw new ArgumentOutOfRangeException(nameof(changedField));
}
references[ObjectIds.ObjectsFolder].Add(Reference(1));
});
using MasterNodeManager master = CreateMaster([first, second]);
await master.StartupAsync().ConfigureAwait(false);
ArrayOf<PreparedNodeManager> prepared = await ((IDynamicNodeManagerHost)master)
.TakeStartupNodeManagersAsync().ConfigureAwait(false);
Assert.That(prepared[1].ExternalReferences[ObjectIds.ObjectsFolder], Has.Count.EqualTo(1));
Assert.That(prepared[1].ExternalReferences[ObjectIds.ObjectsFolder][0], Is.SameAs(mutable));
}
[Test]
public async Task StartupCapturesEmptyReferenceTablesAsync()
{
using MasterNodeManager master = CreateMaster([Manager(_ => { }), Manager(_ => { })]);
await master.StartupAsync().ConfigureAwait(false);
ArrayOf<PreparedNodeManager> prepared = await ((IDynamicNodeManagerHost)master)
.TakeStartupNodeManagersAsync().ConfigureAwait(false);
Assert.That(prepared, Has.Count.EqualTo(2));
Assert.That(prepared[0].ExternalReferences, Is.Empty);
Assert.That(prepared[1].ExternalReferences, Is.Empty);
}
private static NodeStateReference Reference(uint target)
{
return new NodeStateReference(ReferenceTypeIds.Organizes, false, new NodeId(target, 2));
}
private static IAsyncNodeManager Manager(Action<IDictionary<NodeId, IList<IReference>>> create)
{
var manager = new Mock<IAsyncNodeManager>();
manager.SetupGet(value => value.NamespaceUris).Returns(["urn:test:startup-reference"]);
manager.Setup(value => value.CreateAddressSpaceAsync(
It.IsAny<IDictionary<NodeId, IList<IReference>>>(), It.IsAny<CancellationToken>()))
.Callback<IDictionary<NodeId, IList<IReference>>, CancellationToken>((references, _) =>
create(references))
.Returns(default(ValueTask));
return manager.Object;
}
private static MasterNodeManager CreateMaster(ArrayOf<IAsyncNodeManager> managers)
{
var factory = new Mock<IMainNodeManagerFactory>();
factory.Setup(value => value.CreateConfigurationNodeManager())
.Returns(Mock.Of<IConfigurationNodeManager>());
factory.Setup(value => value.CreateCoreNodeManager(It.IsAny<ushort>()))
.Returns(Mock.Of<ICoreNodeManager>());
var server = new Mock<IServerInternal>();
var namespaces = new NamespaceTable();
namespaces.Append("urn:test:server");
server.SetupGet(value => value.NamespaceUris).Returns(namespaces);
server.SetupGet(value => value.Telemetry).Returns(NUnitTelemetryContext.Create());
server.SetupGet(value => value.MainNodeManagerFactory).Returns(factory.Object);
return new MasterNodeManager(
server.Object,
new ApplicationConfiguration { ServerConfiguration = new ServerConfiguration() },
null,
managers.ToArray(),
null);
}
private sealed class MutableReference : IReference
{
public MutableReference(IReference reference)
{
ReferenceTypeId = reference.ReferenceTypeId;
IsInverse = reference.IsInverse;
TargetId = reference.TargetId;
}
public NodeId ReferenceTypeId { get; set; }
public bool IsInverse { get; set; }
public ExpandedNodeId TargetId { get; set; }
}
}
}