Files
UA-.NETStandard/tests/Opc.Ua.Core.Tests/Redundancy/InMemorySharedKeyValueStoreTests.cs
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

458 lines
18 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.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Redundancy;
namespace Opc.Ua.Core.Tests.Redundancy
{
/// <summary>
/// Unit tests for <see cref="InMemorySharedKeyValueStore"/>.
/// </summary>
[TestFixture]
[Category("Redundancy")]
[Parallelizable(ParallelScope.All)]
public sealed class InMemorySharedKeyValueStoreTests
{
private static readonly ByteString s_valueA = new(new byte[] { 1, 2, 3 });
private static readonly ByteString s_valueB = new(new byte[] { 4, 5, 6, 7 });
/// <summary>
/// Verifies that a missing key returns false and a null byte string.
/// </summary>
[Test]
public async Task TryGetReturnsFalseWhenKeyMissingAsync()
{
using var store = new InMemorySharedKeyValueStore();
(bool found, ByteString value) = await store.TryGetAsync("missing").ConfigureAwait(false);
Assert.That(found, Is.False);
Assert.That(value.IsNull, Is.True);
}
/// <summary>
/// Verifies that a value can be retrieved after it is stored.
/// </summary>
[Test]
public async Task SetThenTryGetReturnsStoredValueAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
(bool found, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.True);
Assert.That(value.ToArray(), Is.EqualTo(s_valueA.ToArray()));
}
/// <summary>
/// Verifies that setting an existing key replaces its stored value.
/// </summary>
[Test]
public async Task SetOverwritesExistingValueAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
await store.SetAsync("key", s_valueB).ConfigureAwait(false);
(bool found, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.True);
Assert.That(value.ToArray(), Is.EqualTo(s_valueB.ToArray()));
}
/// <summary>
/// Verifies that reading a null key throws ArgumentNullException.
/// </summary>
[Test]
public void TryGetWithNullKeyThrows()
{
using var store = new InMemorySharedKeyValueStore();
Assert.That(async () => await store.TryGetAsync(null!).ConfigureAwait(false), Throws.ArgumentNullException);
}
/// <summary>
/// Verifies that setting a null key throws ArgumentNullException.
/// </summary>
[Test]
public void SetWithNullKeyThrows()
{
using var store = new InMemorySharedKeyValueStore();
Assert.That(async () => await store.SetAsync(null!, s_valueA).ConfigureAwait(false), Throws.ArgumentNullException);
}
/// <summary>
/// Verifies that compare-and-swap inserts an absent key when the expected value is null.
/// </summary>
[Test]
public async Task CompareAndSwapInsertsWhenAbsentAndExpectedNullAsync()
{
using var store = new InMemorySharedKeyValueStore();
bool swapped = await store.CompareAndSwapAsync("key", default, s_valueA).ConfigureAwait(false);
Assert.That(swapped, Is.True);
(bool found, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.True);
Assert.That(value.ToArray(), Is.EqualTo(s_valueA.ToArray()));
}
/// <summary>
/// Verifies that compare-and-swap fails for an absent key when a non-null value is expected.
/// </summary>
[Test]
public async Task CompareAndSwapFailsWhenAbsentButExpectedNonNullAsync()
{
using var store = new InMemorySharedKeyValueStore();
bool swapped = await store.CompareAndSwapAsync("key", s_valueA, s_valueB).ConfigureAwait(false);
Assert.That(swapped, Is.False);
(bool found, ByteString _) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.False);
}
/// <summary>
/// Verifies that compare-and-swap fails for an existing key when absence is expected.
/// </summary>
[Test]
public async Task CompareAndSwapFailsWhenPresentButExpectedNullAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
bool swapped = await store.CompareAndSwapAsync("key", default, s_valueB).ConfigureAwait(false);
Assert.That(swapped, Is.False);
(bool _, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(value.ToArray(), Is.EqualTo(s_valueA.ToArray()));
}
/// <summary>
/// Verifies that compare-and-swap replaces a value only when the expected value matches.
/// </summary>
[Test]
public async Task CompareAndSwapReplacesWhenExpectedMatchesAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
bool swapped = await store.CompareAndSwapAsync("key", s_valueA, s_valueB).ConfigureAwait(false);
Assert.That(swapped, Is.True);
(bool _, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(value.ToArray(), Is.EqualTo(s_valueB.ToArray()));
}
/// <summary>
/// Verifies that compare-and-swap deletes a matching entry when the replacement is null.
/// </summary>
[Test]
public async Task CompareAndSwapDeletesWhenReplacementIsNullAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
bool swapped = await store.CompareAndSwapAsync(
"key",
s_valueA,
default).ConfigureAwait(false);
Assert.That(swapped, Is.True);
(bool found, _) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.False);
}
/// <summary>
/// Verifies that compare-and-swap preserves an entry when the expected value differs.
/// </summary>
[Test]
public async Task CompareAndSwapFailsWhenExpectedDiffersAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
bool swapped = await store.CompareAndSwapAsync("key", s_valueB, s_valueA).ConfigureAwait(false);
Assert.That(swapped, Is.False);
(bool _, ByteString value) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(value.ToArray(), Is.EqualTo(s_valueA.ToArray()));
}
/// <summary>
/// Verifies that compare-and-swap rejects a null key.
/// </summary>
[Test]
public void CompareAndSwapWithNullKeyThrows()
{
using var store = new InMemorySharedKeyValueStore();
Assert.That(
async () => await store.CompareAndSwapAsync(null!, default, s_valueA).ConfigureAwait(false),
Throws.ArgumentNullException);
}
/// <summary>
/// Verifies that deletion removes an existing key.
/// </summary>
[Test]
public async Task DeleteRemovesExistingKeyAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
bool removed = await store.DeleteAsync("key").ConfigureAwait(false);
Assert.That(removed, Is.True);
(bool found, ByteString _) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.False);
}
/// <summary>
/// Verifies that deleting a missing key returns false.
/// </summary>
[Test]
public async Task DeleteReturnsFalseWhenKeyMissingAsync()
{
using var store = new InMemorySharedKeyValueStore();
bool removed = await store.DeleteAsync("missing").ConfigureAwait(false);
Assert.That(removed, Is.False);
}
/// <summary>
/// Verifies that deletion rejects a null key.
/// </summary>
[Test]
public void DeleteWithNullKeyThrows()
{
using var store = new InMemorySharedKeyValueStore();
Assert.That(async () => await store.DeleteAsync(null!).ConfigureAwait(false), Throws.ArgumentNullException);
}
/// <summary>
/// Verifies that scanning returns only entries whose keys match the requested prefix.
/// </summary>
[Test]
public async Task ScanReturnsOnlyEntriesMatchingPrefixAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("a/1", s_valueA).ConfigureAwait(false);
await store.SetAsync("a/2", s_valueB).ConfigureAwait(false);
await store.SetAsync("b/1", s_valueA).ConfigureAwait(false);
var keys = new List<string>();
await foreach (KeyValuePair<string, ByteString> entry in store.ScanAsync("a/"))
{
keys.Add(entry.Key);
}
Assert.That(keys, Has.Count.EqualTo(2));
Assert.That(keys, Does.Contain("a/1"));
Assert.That(keys, Does.Contain("a/2"));
Assert.That(keys, Does.Not.Contain("b/1"));
}
/// <summary>
/// Verifies that scanning with a null prefix returns all stored entries.
/// </summary>
[Test]
public async Task ScanWithNullPrefixReturnsAllEntriesAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("a", s_valueA).ConfigureAwait(false);
await store.SetAsync("b", s_valueB).ConfigureAwait(false);
var keys = new List<string>();
await foreach (KeyValuePair<string, ByteString> entry in store.ScanAsync(null!))
{
keys.Add(entry.Key);
}
Assert.That(keys, Has.Count.EqualTo(2));
}
/// <summary>
/// Verifies that scanning observes cancellation.
/// </summary>
[Test]
public async Task ScanHonorsCancellationAsync()
{
using var store = new InMemorySharedKeyValueStore();
await store.SetAsync("a", s_valueA).ConfigureAwait(false);
using var cts = new CancellationTokenSource();
cts.Cancel();
Assert.That(
async () =>
{
await foreach (KeyValuePair<string, ByteString> _ in store.ScanAsync("a", cts.Token))
{
}
},
Throws.InstanceOf<OperationCanceledException>());
}
/// <summary>
/// Verifies that a watcher receives both set and delete notifications.
/// </summary>
[Test]
public async Task WatchObservesSetAndDeleteChangesAsync()
{
using var store = new InMemorySharedKeyValueStore();
using var cts = new CancellationTokenSource();
IAsyncEnumerator<KeyValueChange> changes = store
.WatchAsync("k", cts.Token)
.GetAsyncEnumerator(cts.Token);
try
{
ValueTask<bool> firstMove = changes.MoveNextAsync();
await store.SetAsync("k1", s_valueA).ConfigureAwait(false);
Assert.That(await firstMove.ConfigureAwait(false), Is.True);
Assert.That(changes.Current.Kind, Is.EqualTo(KeyValueChangeKind.Set));
Assert.That(changes.Current.Key, Is.EqualTo("k1"));
Assert.That(changes.Current.Value.ToArray(), Is.EqualTo(s_valueA.ToArray()));
ValueTask<bool> secondMove = changes.MoveNextAsync();
await store.DeleteAsync("k1").ConfigureAwait(false);
Assert.That(await secondMove.ConfigureAwait(false), Is.True);
Assert.That(changes.Current.Kind, Is.EqualTo(KeyValueChangeKind.Delete));
Assert.That(changes.Current.Key, Is.EqualTo("k1"));
Assert.That(changes.Current.Value.IsNull, Is.True);
}
finally
{
cts.Cancel();
await changes.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Verifies that a watcher ignores changes outside its requested prefix.
/// </summary>
[Test]
public async Task WatchIgnoresChangesOutsidePrefixAsync()
{
using var store = new InMemorySharedKeyValueStore();
using var cts = new CancellationTokenSource();
IAsyncEnumerator<KeyValueChange> changes = store
.WatchAsync("watched/", cts.Token)
.GetAsyncEnumerator(cts.Token);
try
{
ValueTask<bool> move = changes.MoveNextAsync();
await store.SetAsync("other/1", s_valueA).ConfigureAwait(false);
await store.SetAsync("watched/1", s_valueB).ConfigureAwait(false);
Assert.That(await move.ConfigureAwait(false), Is.True);
Assert.That(changes.Current.Key, Is.EqualTo("watched/1"));
Assert.That(changes.Current.Value.ToArray(), Is.EqualTo(s_valueB.ToArray()));
}
finally
{
cts.Cancel();
await changes.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Verifies that canceling a watch token stops its enumeration.
/// </summary>
[Test]
public async Task WatchStopsWhenTokenIsCanceledAsync()
{
using var store = new InMemorySharedKeyValueStore();
using var cts = new CancellationTokenSource();
IAsyncEnumerator<KeyValueChange> changes = store
.WatchAsync("k", cts.Token)
.GetAsyncEnumerator(cts.Token);
try
{
ValueTask<bool> move = changes.MoveNextAsync();
cts.Cancel();
Assert.That(async () => await move.ConfigureAwait(false), Throws.InstanceOf<OperationCanceledException>());
}
finally
{
await changes.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Verifies that disposing the store completes outstanding watchers.
/// </summary>
[Test]
public async Task DisposeCompletesOutstandingWatchersAsync()
{
var store = new InMemorySharedKeyValueStore();
IAsyncEnumerator<KeyValueChange> changes = store
.WatchAsync(string.Empty, CancellationToken.None)
.GetAsyncEnumerator(CancellationToken.None);
try
{
ValueTask<bool> move = changes.MoveNextAsync();
store.Dispose();
Assert.That(await move.ConfigureAwait(false), Is.False);
}
finally
{
await changes.DisposeAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Verifies that disposing the store clears its stored data.
/// </summary>
[Test]
public async Task DisposeClearsStoredDataAsync()
{
var store = new InMemorySharedKeyValueStore();
await store.SetAsync("key", s_valueA).ConfigureAwait(false);
store.Dispose();
(bool found, ByteString _) = await store.TryGetAsync("key").ConfigureAwait(false);
Assert.That(found, Is.False);
}
}
}