Files
romanettandClaude Opus 5.5 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# 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>
2026-10-08 08:48:13 +02:00

373 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/
* ======================================================================*/
// CA2007: NUnit tests do not run in a synchronization context, so the
// ConfigureAwait recommendations on `await using` do not change behaviour
// — and AliasNameResolver.DisposeAsync returns synchronously anyway.
#pragma warning disable CA2007
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client.AliasNames;
using Opc.Ua.Client.AliasNames.Refresh;
namespace Opc.Ua.Client.Tests.AliasNames
{
/// <summary>
/// Coverage tests for <see cref="AliasNameResolver"/>: ensures the
/// cache is populated lazily, that
/// <see cref="AliasNameResolver.Invalidate"/> forces a refresh on
/// the next call, and that reverse lookups round-trip.
/// </summary>
[TestFixture]
[Category("AliasNames")]
[Parallelizable]
public class AliasNameResolverTests
{
private static CallMethodResult AliasesResult(
params (string name, ExpandedNodeId target)[] aliases)
{
var entries = new AliasNameDataType[aliases.Length];
for (int i = 0; i < aliases.Length; i++)
{
entries[i] = new AliasNameDataType
{
AliasName = new QualifiedName(aliases[i].name),
ReferencedNodes = new[] { aliases[i].target }.ToArrayOf()
};
}
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[]
{
Variant.FromStructure(entries.ToArrayOf())
}.ToArrayOf()
};
}
[Test]
public async Task ResolveLoadsCacheOnDemandAsync()
{
var harness = AliasNameSessionHarness.Create();
int callCount = 0;
harness.CallHandler = _ =>
{
callCount++;
return AliasesResult(
("Alpha", new ExpandedNodeId("T1", 2)),
("Beta", new ExpandedNodeId("T2", 2)));
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
IReadOnlyList<ExpandedNodeId> alpha =
await resolver.ResolveAsync("Alpha").ConfigureAwait(false);
Assert.That(callCount, Is.EqualTo(1));
Assert.That(alpha, Has.Count.EqualTo(1));
Assert.That(alpha[0], Is.EqualTo(new ExpandedNodeId("T1", 2)));
// Second resolve hits the cache; the underlying server is
// NOT contacted again.
IReadOnlyList<ExpandedNodeId> beta =
await resolver.ResolveAsync("Beta").ConfigureAwait(false);
Assert.That(callCount, Is.EqualTo(1),
"Second resolve must reuse the cache.");
Assert.That(beta[0], Is.EqualTo(new ExpandedNodeId("T2", 2)));
}
[Test]
public async Task ResolveAliasNameAsyncReverseLookupAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => AliasesResult(
("Speed", new ExpandedNodeId("V1", 2)));
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
string name = (await resolver
.ResolveAliasNameAsync(new ExpandedNodeId("V1", 2))
.ConfigureAwait(false))!;
Assert.That(name, Is.EqualTo("Speed"));
}
[Test]
public async Task InvalidateForcesRefreshOnNextResolveAsync()
{
var harness = AliasNameSessionHarness.Create();
int callCount = 0;
harness.CallHandler = _ =>
{
callCount++;
return AliasesResult(
("Sigma", new ExpandedNodeId($"T-{callCount}", 2)));
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
await resolver.ResolveAsync("Sigma").ConfigureAwait(false);
resolver.Invalidate();
IReadOnlyList<ExpandedNodeId> refreshed =
await resolver.ResolveAsync("Sigma").ConfigureAwait(false);
Assert.That(callCount, Is.EqualTo(2));
Assert.That(refreshed[0],
Is.EqualTo(new ExpandedNodeId("T-2", 2)));
}
[Test]
public async Task DuplicateAliasNamesMergeTargetsAsync()
{
// FindAlias searches sub-categories too, so the same Name may be
// returned twice; the second entry must not overwrite the first.
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => AliasesResult(
("Temp", new ExpandedNodeId("T1", 2)),
("Temp", new ExpandedNodeId("T2", 3)));
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
IReadOnlyList<ExpandedNodeId> result = await resolver
.ResolveAsync("Temp").ConfigureAwait(false);
Assert.That(result, Is.EqualTo(new[]
{
new ExpandedNodeId("T1", 2),
new ExpandedNodeId("T2", 3)
}));
}
[Test]
public async Task StrategyStartFailureDoesNotBreakResolveAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => AliasesResult(
("A", new ExpandedNodeId("T1", 2)));
var client = AliasNameClient.OpenStandardAliases(harness.Session);
var strategy = new ThrowingStartStrategy();
await using var resolver = new AliasNameResolver(
client,
new AliasNameResolverOptions { RefreshStrategy = strategy });
IReadOnlyList<ExpandedNodeId> result = await resolver
.ResolveAsync("A").ConfigureAwait(false);
Assert.That(result, Has.Count.EqualTo(1));
Assert.That(strategy.StartCalls, Is.EqualTo(1));
// Loaded: a further resolve neither refetches nor restarts.
await resolver.ResolveAsync("A").ConfigureAwait(false);
Assert.That(strategy.StartCalls, Is.EqualTo(1));
// The start is retried on the next load.
resolver.Invalidate();
await resolver.ResolveAsync("A").ConfigureAwait(false);
Assert.That(strategy.StartCalls, Is.EqualTo(2));
}
private sealed class ThrowingStartStrategy
: IAliasNameRefreshStrategy
{
public int StartCalls { get; private set; }
public ValueTask StartAsync(
AliasNameClient client,
Action onInvalidate,
CancellationToken ct)
{
StartCalls++;
throw ServiceResultException.Create(
StatusCodes.BadTooManySubscriptions, "rejected");
}
public ValueTask DisposeAsync()
{
return default;
}
}
[Test]
public async Task UnknownNameReturnsEmptyListAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => AliasesResult(
("A", new ExpandedNodeId("T1", 2)));
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
IReadOnlyList<ExpandedNodeId> result = await resolver
.ResolveAsync("Unknown").ConfigureAwait(false);
Assert.That(result, Is.Empty);
}
// ----------------------------------------------------------------
// Verbose mode coverage
// ----------------------------------------------------------------
private static CallMethodResult VerboseAliasesResult(
params (string name, ExpandedNodeId target, string? serverUri)[] aliases)
{
var entries = new AliasNameVerboseDataType[aliases.Length];
for (int i = 0; i < aliases.Length; i++)
{
entries[i] = new AliasNameVerboseDataType
{
AliasName = new QualifiedName(aliases[i].name),
ReferencedNodes = new[] { aliases[i].target }.ToArrayOf(),
ServerUris = new[] { aliases[i].serverUri ?? string.Empty }.ToArrayOf(),
AliasNameCategoryId = ObjectIds.Aliases
};
}
return new CallMethodResult
{
StatusCode = StatusCodes.Good,
OutputArguments = new[]
{
Variant.FromStructure(entries.ToArrayOf())
}.ToArrayOf()
};
}
[Test]
public async Task VerboseResolverPopulatesServerUrisAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = req =>
{
if (req.MethodId == MethodIds.AliasNameCategoryType_FindAliasVerbose)
{
return VerboseAliasesResult(
("Tag1", new ExpandedNodeId("T1", 2), "urn:remote-server"));
}
// Non-verbose path should not be hit when UseVerbose succeeds.
return AliasesResult(("Tag1", new ExpandedNodeId("T1", 2)));
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(
client,
new AliasNameResolverOptions { UseVerbose = true });
IReadOnlyList<ExpandedNodeId> targets =
await resolver.ResolveAsync("Tag1").ConfigureAwait(false);
IReadOnlyList<string?> uris =
await resolver.ResolveServerUrisAsync("Tag1").ConfigureAwait(false);
Assert.That(targets, Has.Count.EqualTo(1));
Assert.That(targets[0], Is.EqualTo(new ExpandedNodeId("T1", 2)));
Assert.That(uris, Has.Count.EqualTo(1));
Assert.That(uris[0], Is.EqualTo("urn:remote-server"));
}
[Test]
public async Task NonVerboseResolverReturnsEmptyServerUrisAsync()
{
var harness = AliasNameSessionHarness.Create();
harness.CallHandler = _ => AliasesResult(
("Tag1", new ExpandedNodeId("T1", 2)));
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(client);
await resolver.ResolveAsync("Tag1").ConfigureAwait(false);
IReadOnlyList<string?> uris =
await resolver.ResolveServerUrisAsync("Tag1").ConfigureAwait(false);
Assert.That(uris, Is.Empty,
"Non-verbose mode must surface an empty list for ServerUris (no decoration).");
}
[Test]
public Task VerboseResolverFallsBackToNonVerboseOnNotSupportedAsync()
{
// Server returns BadNotImplemented for the verbose method —
// the resolver must transparently fall back to FindAlias and
// populate the cache from the non-verbose response.
return AssertVerboseFallbackAsync(StatusCodes.BadNotImplemented);
}
[Test]
public Task VerboseResolverFallsBackToNonVerboseOnMethodInvalidAsync()
{
// A category that does not expose the optional FindAliasVerbose
// returns BadMethodInvalid (Part 4 §5.12.2.4); that must also
// trigger the non-verbose fallback instead of failing every resolve.
return AssertVerboseFallbackAsync(StatusCodes.BadMethodInvalid);
}
private static async Task AssertVerboseFallbackAsync(StatusCode verboseStatus)
{
var harness = AliasNameSessionHarness.Create();
// The category has no FindAliasVerbose instance method either, so
// the proxy's instance-MethodId retry finds nothing.
harness.BrowsePathHandler = _ => new BrowsePathResult
{
StatusCode = StatusCodes.BadNoMatch,
Targets = Array.Empty<BrowsePathTarget>().ToArrayOf()
};
int verboseCalls = 0;
int nonVerboseCalls = 0;
harness.CallHandler = req =>
{
if (req.MethodId == MethodIds.AliasNameCategoryType_FindAliasVerbose)
{
verboseCalls++;
return new CallMethodResult
{
StatusCode = verboseStatus
};
}
nonVerboseCalls++;
return AliasesResult(("Tag1", new ExpandedNodeId("T1", 2)));
};
var client = AliasNameClient.OpenStandardAliases(harness.Session);
await using var resolver = new AliasNameResolver(
client,
new AliasNameResolverOptions { UseVerbose = true });
IReadOnlyList<ExpandedNodeId> targets =
await resolver.ResolveAsync("Tag1").ConfigureAwait(false);
Assert.That(targets, Has.Count.EqualTo(1));
Assert.That(targets[0], Is.EqualTo(new ExpandedNodeId("T1", 2)));
Assert.That(verboseCalls, Is.EqualTo(1),
"Verbose call must have been attempted once.");
Assert.That(nonVerboseCalls, Is.EqualTo(1),
"Non-verbose fallback must have been issued after the verbose failure.");
// A second resolve should NOT re-attempt the verbose call —
// the resolver flips UseVerbose=false once it falls back.
resolver.Invalidate();
await resolver.ResolveAsync("Tag1").ConfigureAwait(false);
Assert.That(verboseCalls, Is.EqualTo(1),
"Once fallen back, the resolver must not re-attempt the verbose method.");
Assert.That(nonVerboseCalls, Is.EqualTo(2));
}
}
}