mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-23 10:23:13 +08:00
9b034f8291
# Description Nullable reference types are now enabled once, in `common.props`, and every project in the repository builds warning-clean with them. **Configuration** - `<Nullable>enable</Nullable>` lives in `common.props`. All per-project `<Nullable>` settings are removed: 178 project files (enable, annotations, and the `disable` in the three Aot test projects). - 419 per-file `#nullable enable`/`restore` directives and the 4 `#nullable disable` directives are removed. - Kept on purpose: - The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`, `PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the project setting in generated code, so the directive is required there. - `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against the 1.5.378 packages and does not import the repository props. - `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now describe the central setting. **Migration** (the 43 unset and 13 annotations-only projects, roughly 10k diagnostics) - **Production code: annotated at the declarations.** Covers `tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the LDS sample. - Members, parameters and returns are nullable where null actually flows. - Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`, `IsMethodTypeDesign`). - `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take `params object?[]`. `Template.AddReplacement` takes `string?` (rendering already skips null replacements). - `IRegisteredServerStore.RegisterAsync` returns `Task<RegistrationEntry?>`: it returns null when a registration is removed. - Dereferences backed by an invariant (for example, the validated model) use `!`, so runtime behaviour is unchanged. - **Behavioural changes in production code** (small, deliberate): - `NodeSetToModelDesign` throws `InvalidOperationException` when the file is not a NodeSet. Before, it threw a NullReferenceException on the next line. - `ModelDesignValidator` starts its lookup tables empty instead of null. A redundant `if (m_nodes == null) return;` guard is gone. - **Test code: minimal annotations.** - `?` on values that can be null, `!` where the test asserts non-null. - `= null!` for fixture members assigned in SetUp. - `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the `IEncodeable` constraint. - A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`) folded into the adjacent `IsNull`/`Count` checks. **Notes for reviewers** - The diff is large (~1,500 files) but almost entirely mechanical: `?`, `!` and directive removal. The non-annotation changes are listed above. - Known follow-up, not done here: `IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay non-nullable even though the validator returns null before it loads a dictionary. Making them nullable would ripple through every generator call site. ## Related Issues - Fixes #4439 ## 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. - [ ] 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. The "no new warnings" box covers net10.0 and net48: full non-incremental builds of `UA.slnx`, `tools/SourceGeneration.slnx`, `tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0 warnings and 0 errors under the repository's warnings-as-errors settings. net9.0 and net8.0 also had no nullable diagnostics, but they were not rebuilt after the final fixes. Tests have not been run locally yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
313 lines
15 KiB
C#
313 lines
15 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/
|
|
* ======================================================================*/
|
|
|
|
// CA2007: tests run without a SynchronizationContext; ConfigureAwait(false)
|
|
// adds noise without a behavioural benefit. Disabled file-level for the suite.
|
|
#pragma warning disable CA2007
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Redundancy.Server;
|
|
using Opc.Ua.Tests;
|
|
|
|
namespace Opc.Ua.Server.Tests.Redundancy
|
|
{
|
|
/// <summary>
|
|
/// Unit tests for <see cref="ServerRedundancyStartupTask"/> and
|
|
/// <see cref="ServerRedundancyController"/> subtype materialization of
|
|
/// <c>Server.ServerRedundancy</c>.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("Distributed")]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public class ServerRedundancyStartupTaskTests
|
|
{
|
|
[Test]
|
|
public void ConstructorThrowsOnNullController()
|
|
{
|
|
Assert.That(() => new ServerRedundancyStartupTask(null!), Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public void ControllerConstructorThrowsOnNullOptions()
|
|
{
|
|
Assert.That(() => new ServerRedundancyController(null!), Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public void OptionsUseSingleServerDefaults()
|
|
{
|
|
var options = new ServerRedundancyOptions();
|
|
|
|
Assert.That(options.Mode, Is.EqualTo(RedundancySupport.None));
|
|
Assert.That(options.PeerServerUris, Is.Empty);
|
|
Assert.That(options.CurrentServerId, Is.Not.Empty);
|
|
Assert.That(options.PeerServiceLevel, Is.EqualTo(ServiceLevels.Maximum));
|
|
}
|
|
|
|
[Test]
|
|
public void GetTypeDefinitionIdMapsModes()
|
|
{
|
|
Assert.That(ServerRedundancyController.GetTypeDefinitionId(RedundancySupport.None),
|
|
Is.EqualTo(ObjectTypeIds.ServerRedundancyType));
|
|
Assert.That(ServerRedundancyController.GetTypeDefinitionId(RedundancySupport.Transparent),
|
|
Is.EqualTo(ObjectTypeIds.TransparentRedundancyType));
|
|
Assert.That(ServerRedundancyController.GetTypeDefinitionId(RedundancySupport.Hot),
|
|
Is.EqualTo(ObjectTypeIds.NonTransparentRedundancyType));
|
|
Assert.That(ServerRedundancyController.GetTypeDefinitionId(RedundancySupport.Cold),
|
|
Is.EqualTo(ObjectTypeIds.NonTransparentRedundancyType));
|
|
}
|
|
|
|
[Test]
|
|
public void OnServerStartedThrowsOnNullServer()
|
|
{
|
|
var task = new ServerRedundancyStartupTask(
|
|
new ServerRedundancyController(new ServerRedundancyOptions()));
|
|
|
|
Assert.That(
|
|
async () => await task.OnServerStartedAsync(null!).ConfigureAwait(false),
|
|
Throws.ArgumentNullException);
|
|
}
|
|
|
|
[Test]
|
|
public async Task OnServerStartedNoOpsWhenServerObjectMissingAsync()
|
|
{
|
|
var task = new ServerRedundancyStartupTask(
|
|
new ServerRedundancyController(new ServerRedundancyOptions()));
|
|
var server = new Mock<IServerInternal>();
|
|
server.Setup(s => s.ServerObject).Returns((ServerObjectState)null!);
|
|
|
|
await task.OnServerStartedAsync(server.Object).ConfigureAwait(false);
|
|
|
|
server.VerifyGet(s => s.ServerObject, Times.Once);
|
|
}
|
|
|
|
[Test]
|
|
public async Task NoneModeKeepsBaseTypeWithoutSubtypeChildrenAsync()
|
|
{
|
|
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
|
|
var task = new ServerRedundancyStartupTask(
|
|
new ServerRedundancyController(new ServerRedundancyOptions()));
|
|
|
|
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
|
|
|
|
ServerRedundancyState redundancy = loaded.Server.Object.ServerObject.ServerRedundancy!;
|
|
Assert.That(redundancy.TypeDefinitionId, Is.EqualTo(ObjectTypeIds.ServerRedundancyType));
|
|
Assert.That(redundancy, Is.Not.InstanceOf<TransparentRedundancyState>());
|
|
Assert.That(redundancy, Is.Not.InstanceOf<NonTransparentRedundancyState>());
|
|
Assert.That(redundancy.RedundancySupport!.Value, Is.EqualTo(RedundancySupport.None));
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.CurrentServerId), Is.False);
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.ServerUriArray), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task TransparentModePromotesToTransparentSubtypeAsync()
|
|
{
|
|
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
|
|
var options = new ServerRedundancyOptions
|
|
{
|
|
Mode = RedundancySupport.Transparent,
|
|
CurrentServerId = "replica-a"
|
|
};
|
|
options.PeerServerUris.Add("urn:peer-a");
|
|
var task = new ServerRedundancyStartupTask(new ServerRedundancyController(options));
|
|
|
|
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
|
|
|
|
ServerRedundancyState redundancy = loaded.Server.Object.ServerObject.ServerRedundancy!;
|
|
Assert.That(redundancy.TypeDefinitionId, Is.EqualTo(ObjectTypeIds.TransparentRedundancyType));
|
|
Assert.That(redundancy, Is.InstanceOf<TransparentRedundancyState>());
|
|
|
|
var transparent = (TransparentRedundancyState)redundancy;
|
|
Assert.That(transparent.CurrentServerId, Is.Not.Null);
|
|
Assert.That(transparent.CurrentServerId!.Value, Is.EqualTo("replica-a"));
|
|
Assert.That(transparent.CurrentServerId.NodeId,
|
|
Is.EqualTo(VariableIds.Server_ServerRedundancy_CurrentServerId));
|
|
Assert.That(transparent.RedundantServerArray!.Value[0].ServerId, Is.EqualTo("urn:peer-a"));
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.CurrentServerId), Is.True);
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.ServerUriArray), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task NonTransparentModePromotesToNonTransparentSubtypeAsync()
|
|
{
|
|
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
|
|
var options = new ServerRedundancyOptions
|
|
{
|
|
Mode = RedundancySupport.Hot
|
|
};
|
|
options.PeerServerUris.Add("urn:peer-a");
|
|
options.PeerServerUris.Add("urn:peer-b");
|
|
var task = new ServerRedundancyStartupTask(new ServerRedundancyController(options));
|
|
|
|
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
|
|
|
|
ServerRedundancyState redundancy = loaded.Server.Object.ServerObject.ServerRedundancy!;
|
|
Assert.That(redundancy.TypeDefinitionId, Is.EqualTo(ObjectTypeIds.NonTransparentRedundancyType));
|
|
Assert.That(redundancy, Is.InstanceOf<NonTransparentRedundancyState>());
|
|
|
|
var nonTransparent = (NonTransparentRedundancyState)redundancy;
|
|
Assert.That(nonTransparent.ServerUriArray, Is.Not.Null);
|
|
Assert.That(nonTransparent.ServerUriArray!.Value, Is.EqualTo(["urn:peer-a", "urn:peer-b"]));
|
|
Assert.That(nonTransparent.ServerUriArray.NodeId,
|
|
Is.EqualTo(VariableIds.Server_ServerRedundancy_ServerUriArray));
|
|
Assert.That(nonTransparent.RedundantServerArray!.Value[0].ServerId, Is.EqualTo("urn:peer-a"));
|
|
Assert.That(nonTransparent.RedundantServerArray.Value[1].ServerId, Is.EqualTo("urn:peer-b"));
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.ServerUriArray), Is.True);
|
|
Assert.That(HasChild(loaded, redundancy, BrowseNames.CurrentServerId), Is.False);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ChangeModeAtRuntimeSwapsSubtypeAsync()
|
|
{
|
|
using LoadedDiagnosticsServer loaded = await CreateLoadedServerAsync().ConfigureAwait(false);
|
|
var options = new ServerRedundancyOptions();
|
|
options.PeerServerUris.Add("urn:peer-a");
|
|
var controller = new ServerRedundancyController(options);
|
|
var task = new ServerRedundancyStartupTask(controller);
|
|
|
|
await task.OnServerStartedAsync(loaded.Server.Object).ConfigureAwait(false);
|
|
Assert.That(loaded.Server.Object.ServerObject.ServerRedundancy!.TypeDefinitionId,
|
|
Is.EqualTo(ObjectTypeIds.ServerRedundancyType));
|
|
|
|
// None -> Transparent
|
|
options.CurrentServerId = "replica-a";
|
|
await controller.ChangeModeAsync(RedundancySupport.Transparent).ConfigureAwait(false);
|
|
|
|
Assert.That(controller.Mode, Is.EqualTo(RedundancySupport.Transparent));
|
|
ServerRedundancyState afterTransparent = loaded.Server.Object.ServerObject.ServerRedundancy!;
|
|
Assert.That(afterTransparent, Is.InstanceOf<TransparentRedundancyState>());
|
|
Assert.That(((TransparentRedundancyState)afterTransparent).CurrentServerId!.Value,
|
|
Is.EqualTo("replica-a"));
|
|
Assert.That(HasChild(loaded, afterTransparent, BrowseNames.CurrentServerId), Is.True);
|
|
|
|
// Transparent -> Hot: subtype swaps, CurrentServerId child gone, ServerUriArray present
|
|
await controller.ChangeModeAsync(RedundancySupport.Hot).ConfigureAwait(false);
|
|
|
|
ServerRedundancyState afterHot = loaded.Server.Object.ServerObject.ServerRedundancy!;
|
|
Assert.That(afterHot, Is.InstanceOf<NonTransparentRedundancyState>());
|
|
Assert.That(((NonTransparentRedundancyState)afterHot).ServerUriArray!.Value,
|
|
Is.EqualTo(["urn:peer-a"]));
|
|
Assert.That(HasChild(loaded, afterHot, BrowseNames.ServerUriArray), Is.True);
|
|
Assert.That(HasChild(loaded, afterHot, BrowseNames.CurrentServerId), Is.False);
|
|
Assert.That(
|
|
loaded.Manager.FindPredefinedNode<PropertyState<string>>(
|
|
VariableIds.Server_ServerRedundancy_CurrentServerId),
|
|
Is.Null);
|
|
}
|
|
|
|
private static bool HasChild(
|
|
LoadedDiagnosticsServer loaded,
|
|
ServerRedundancyState redundancy,
|
|
string browseName)
|
|
{
|
|
var children = new List<BaseInstanceState>();
|
|
redundancy.GetChildren(loaded.Server.Object.DefaultSystemContext, children);
|
|
return children.Exists(child => child.BrowseName.Name == browseName);
|
|
}
|
|
|
|
private static async Task<LoadedDiagnosticsServer> CreateLoadedServerAsync()
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
var namespaceUris = new NamespaceTable();
|
|
namespaceUris.Append("http://opcfoundation.org/UA/");
|
|
var serverUris = new StringTable();
|
|
var typeTree = new TypeTable(namespaceUris);
|
|
var messageContext = new ServiceMessageContext(telemetry, EncodeableFactory.Create())
|
|
{
|
|
NamespaceUris = namespaceUris,
|
|
ServerUris = serverUris
|
|
};
|
|
|
|
var server = new Mock<IServerInternal>();
|
|
var coreNodeManager = new Mock<ICoreNodeManager>();
|
|
coreNodeManager.Setup(m => m.ImportNodesAsync(
|
|
It.IsAny<ISystemContext>(),
|
|
It.IsAny<IList<NodeState>>(),
|
|
It.IsAny<bool>(),
|
|
It.IsAny<CancellationToken>()))
|
|
.Returns(new ValueTask());
|
|
var masterNodeManager = new Mock<IMasterNodeManager>();
|
|
masterNodeManager.Setup(m => m.RemoveReferencesAsync(
|
|
It.IsAny<List<LocalReference>>(),
|
|
It.IsAny<CancellationToken>()))
|
|
.Returns(new ValueTask());
|
|
|
|
server.Setup(s => s.Telemetry).Returns(telemetry);
|
|
server.Setup(s => s.NamespaceUris).Returns(namespaceUris);
|
|
server.Setup(s => s.ServerUris).Returns(serverUris);
|
|
server.Setup(s => s.TypeTree).Returns(typeTree);
|
|
server.Setup(s => s.MessageContext).Returns(messageContext);
|
|
server.Setup(s => s.CoreNodeManager).Returns(coreNodeManager.Object);
|
|
server.Setup(s => s.NodeManager).Returns(masterNodeManager.Object);
|
|
server.Setup(s => s.Factory).Returns(EncodeableFactory.Create());
|
|
|
|
var context = new ServerSystemContext(server.Object);
|
|
server.Setup(s => s.DefaultSystemContext).Returns(context);
|
|
|
|
var configuration = new ApplicationConfiguration
|
|
{
|
|
ServerConfiguration = new ServerConfiguration()
|
|
};
|
|
var manager = new DiagnosticsNodeManager(server.Object, configuration, NullLogger.Instance);
|
|
await manager.CreateAddressSpaceAsync(new Dictionary<NodeId, IList<IReference>>()).ConfigureAwait(false);
|
|
ServerObjectState serverObject = manager.FindPredefinedNode<ServerObjectState>(ObjectIds.Server);
|
|
server.Setup(s => s.ServerObject).Returns(serverObject);
|
|
server.Setup(s => s.DiagnosticsNodeManager).Returns(manager);
|
|
server.Setup(s => s.FindNodeManagers<IPredefinedNodeSubtypeReplacer>()).Returns([manager]);
|
|
return new LoadedDiagnosticsServer(server, manager);
|
|
}
|
|
|
|
private sealed class LoadedDiagnosticsServer : IDisposable
|
|
{
|
|
public LoadedDiagnosticsServer(
|
|
Mock<IServerInternal> server,
|
|
DiagnosticsNodeManager manager)
|
|
{
|
|
Server = server;
|
|
Manager = manager;
|
|
}
|
|
|
|
public Mock<IServerInternal> Server { get; }
|
|
|
|
public DiagnosticsNodeManager Manager { get; }
|
|
|
|
public void Dispose()
|
|
{
|
|
Manager.Dispose();
|
|
}
|
|
}
|
|
}
|
|
}
|