Files
UA-.NETStandard/tests/Opc.Ua.Redundancy.Client.Tests/Raft/HybridSharedKeyValueStoreTests.cs
Marc SchierandCopilot da7412c429 Add native xRegistry events and distinct Resource versions (#4396)
## Summary

- support the xRegistry 0.6.0 distinct Resource/Version hierarchy:
  `Registry -> Group -> Resource -> Versions -> Version`
- instantiate stable logical Resource nodes separately from exact
Version nodes
  while preserving existing Version NodeIds
- delegate logical Resource FileType operations and Version-view
metadata to the
selected default Version with handle pinning and shared writer
reservations
- make Resource and Version delete behavior role-stable and use
`MetaEpoch` /
  `Epoch` respectively
- use stable Resource SourceNodes, exact Version SourceNodes and the
  `Server -> Registry -> Group -> Resource -> Version` notifier chain
- keep a model-metadata-gated client fallback for 0.5 flat Servers; 0.6
Servers
  expose no legacy aliases
- target `HasWoTProjection` at the real stable logical Resource node
- use `AsyncCustomNodeManager` for the registration, fast-path, and
federation managers,
  with awaited lifecycle, node mutations, event delivery, and cleanup
- handle startup rollback, reentrant deletion callbacks, undisclosed
file handles,
  and retryable cleanup without blocking unrelated file operations

## Authoritative dependencies

- companion specification: OPCF-Members/spec-drafts#32 at
  `d3399fca025025a73e5a6b599f850a81d985c060`
- OPC UA binding: xregistry/spec#568
- xRegistry event semantics: xregistry/spec#563, merged as
  `66ee31e47fbadff6ab982ae1516f7d9065e46b64`
- companion NodeSet SHA-256:
  `369f5f3f1814b333e4eeb52bfb4b6a730cdff372505a5f91a54c94f0016ac4cf`

## Review feedback

- keep the WoT Connectivity information-model designation at `1.1`;
draft revisions update the publication date without changing the model
version
- eliminate all 198 unique CA1861 diagnostics across 54 files and remove
seven obsolete project suppressions
- fix the analyzer-clean touched-path CA1307 and the hierarchy follow-up
CA1846/CA1851 diagnostics without dropping legacy-TFM compatibility

- recover the reconcile queue after callback faults/cancellation and
continue accepted pending changes
- remove migration guidance for the xRegistry managers, which are new in
2.0

## Compatibility

- public WoT Connectivity model designation remains `1.1`
- generated event-record ABI, constructors, options, NodeIds, and stored
documents remain compatible
- the generic xRegistry managers are new in 2.0 and implement
`IAsyncNodeManager`;
use `IAsyncNodeManagerFactory` and the async lifecycle hooks (see
`docs\XRegistry.md`)
- persistence schema and document blobs remain compatible unless noted
below

## Validation

- merge validation at `980422f76` with upstream `e8bec27d5`: 454
targeted WoT/materialization/model/registry cases and all 327 XRegistry
cases passed on both net10.0 and net48; all 29 net10 aggregation sample
cases passed
- feedback regressions at `308e8ba74`: 55 targeted queue and live
registry event/projection/lifecycle cases passed on each of net10.0 and
net48
- prior CI: all 266 checks passed at `6489a0908`; the unchanged Ubuntu
Core certificate-counter test and dependent jobs passed on the one-time
retry ([run 34117304035, attempt
2](https://github.com/OPCFoundation/UA-.NETStandard/actions/runs/34117304035/attempts/2))
- `Opc.Ua.XRegistry.Tests` — 327 passed on net10.0 and net48 for
migration commit `32c914aaf`
- `Opc.Ua.WotCon.Tests` net10.0 — 1348 passed
- `Opc.Ua.WotCon.Bindings.Tests` net10.0 — 683 passed
- `Opc.Ua.SourceGeneration.Core.Tests` net10.0 — 3807 passed, 8 skipped
- `Opc.Ua.SourceGeneration.Tests` net10.0 — 145 passed
- `Opc.Ua.SourceGeneration.Stack.Tests` net10.0 — 94 passed
- affected XRegistry and WoT client/server projects build successfully
- xRegistry NodeSet is byte-identical to the companion artifact
- repository-wide CA1861 inventory — 198 unique diagnostics across 54
files reduced to zero
- targeted changed-fixture validation — 1,098 passed, 3 skipped, 0
failed
- constrained full `UA.slnx` net10.0 Release build — CA1861 = 0
- `Opc.Ua.XRegistry.Client` net472 and netstandard2.1 builds — 0
warnings, 0 errors
- independent shared-array safety review — no significant issues
- `git diff --check`

The final review regressions cover concurrent reconcile/open, synthetic
logical
handle collisions across default switches, cross-session Close
isolation,
shared writer reservations, logical FileType property/change
propagation,
logical Labels delegation, role-fixed deletion, event sources,
model-version
gating, and stable `HasWoTProjection` targets.

The companion specification and protocol binding are reviewed in the
linked PRs above.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5c79a1ed-6dab-4522-a9fc-6548caa78ad5
Copilot-Session: b605797f-a97a-4cd0-8f12-016d33c2fd88
Copilot-Session: 7ef369a5-2307-4f71-8a11-15af0e72f240
Copilot-Session: e716d455-8397-4d22-9c5a-398847ab7317
2026-09-08 04:46:40 +00:00

317 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/
* ======================================================================*/
// IDE0230: byte-array literals below are opaque binary test vectors, not text; a
// UTF-8 "..."u8 literal would misrepresent their intent, so keep the explicit byte arrays.
#pragma warning disable IDE0230 // Use UTF-8 string literal
// CA2000: system-under-test disposables are created per test and released at teardown;
// there is no cross-test resource leak. Suppressed file-level for the suite.
#pragma warning disable CA2000 // Dispose objects before losing scope
// 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 NUnit.Framework;
using Opc.Ua.Redundancy;
namespace Opc.Ua.Client.Redundancy.Tests
{
/// <summary>
/// Coverage for <see cref="HybridSharedKeyValueStore"/>: prefix routing between a bulk (CRDT) backend and a strong
/// (Raft) backend. Two <see cref="InMemorySharedKeyValueStore"/> instances stand in for the backends so routing is
/// directly observable.
/// </summary>
[TestFixture]
[Category("ClientRedundancy")]
public sealed class HybridSharedKeyValueStoreTests
{
[Test]
public async Task BulkKeyRoutesToBulkStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
(bool inBulk, _) = await bulk.TryGetAsync("node/1").ConfigureAwait(false);
(bool inStrong, _) = await strong.TryGetAsync("node/1").ConfigureAwait(false);
Assert.That(inBulk, Is.True, "bulk keys live in the CRDT backend");
Assert.That(inStrong, Is.False);
}
[Test]
public async Task StrongKeyRoutesToStrongStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("nonce/abc", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
(bool inStrong, _) = await strong.TryGetAsync("nonce/abc").ConfigureAwait(false);
(bool inBulk, _) = await bulk.TryGetAsync("nonce/abc").ConfigureAwait(false);
Assert.That(inStrong, Is.True, "strong keys live in the Raft backend");
Assert.That(inBulk, Is.False);
}
[Test]
public async Task CompareAndSwapOnStrongKeyUsesStrongStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
var value = ByteString.From(new byte[] { 7 });
bool created = await hybrid.CompareAndSwapAsync("lease/leader", default, value).ConfigureAwait(false);
(bool inStrong, _) = await strong.TryGetAsync("lease/leader").ConfigureAwait(false);
Assert.That(created, Is.True);
Assert.That(inStrong, Is.True);
}
[Test]
public async Task DeleteRoutesToSelectedStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/a", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
bool deletedBulk = await hybrid.DeleteAsync("node/1").ConfigureAwait(false);
bool deletedStrong = await hybrid.DeleteAsync("nonce/a").ConfigureAwait(false);
Assert.That(deletedBulk, Is.True);
Assert.That(deletedStrong, Is.True);
(bool foundBulk, _) = await bulk.TryGetAsync("node/1").ConfigureAwait(false);
(bool foundStrong, _) = await strong.TryGetAsync("nonce/a").ConfigureAwait(false);
Assert.That(foundBulk, Is.False);
Assert.That(foundStrong, Is.False);
}
[Test]
public async Task WatchOnStrongPrefixObservesStrongStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await using IAsyncEnumerator<KeyValueChange> enumerator =
hybrid.WatchAsync("election/", cts.Token).GetAsyncEnumerator(cts.Token);
ValueTask<bool> first = enumerator.MoveNextAsync();
await hybrid.SetAsync("election/leader", ByteString.From(new byte[] { 1 }), cts.Token)
.ConfigureAwait(false);
Assert.That(await first.ConfigureAwait(false), Is.True);
Assert.That(enumerator.Current.Key, Is.EqualTo("election/leader"));
}
[Test]
public async Task WatchOnBulkPrefixObservesBulkStoreAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await using IAsyncEnumerator<KeyValueChange> enumerator =
hybrid.WatchAsync("node/", cts.Token).GetAsyncEnumerator(cts.Token);
ValueTask<bool> first = enumerator.MoveNextAsync();
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 }), cts.Token).ConfigureAwait(false);
Assert.That(await first.ConfigureAwait(false), Is.True);
Assert.That(enumerator.Current.Key, Is.EqualTo("node/1"));
}
[Test]
public async Task EmptyPrefixScanMergesBothStoresAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/a", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
var keys = new List<string>();
await foreach (KeyValuePair<string, ByteString> entry in hybrid.ScanAsync(string.Empty)
.ConfigureAwait(false))
{
keys.Add(entry.Key);
}
Assert.That(keys, Is.EquivalentTo(["node/1", "nonce/a"]));
}
[Test]
public async Task StrongPrefixScanReturnsStrongKeysOnlyAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/a", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/b", ByteString.From(new byte[] { 3 })).ConfigureAwait(false);
var keys = new List<string>();
await foreach (KeyValuePair<string, ByteString> entry in hybrid.ScanAsync("nonce/").ConfigureAwait(false))
{
keys.Add(entry.Key);
}
Assert.That(keys, Is.EquivalentTo(["nonce/a", "nonce/b"]));
}
[Test]
public async Task BulkPrefixScanReturnsBulkKeysOnlyAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("node/2", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/a", ByteString.From(new byte[] { 3 })).ConfigureAwait(false);
var keys = new List<string>();
await foreach (KeyValuePair<string, ByteString> entry in hybrid.ScanAsync("node/").ConfigureAwait(false))
{
keys.Add(entry.Key);
}
Assert.That(keys, Is.EquivalentTo(["node/1", "node/2"]),
"a bulk-only prefix must not enumerate the strong store");
}
[Test]
public async Task IsStrongKeyClassifiesByPrefixAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
Assert.That(hybrid.IsStrongKey("nonce/x"), Is.True);
Assert.That(hybrid.IsStrongKey("lease/x"), Is.True);
Assert.That(hybrid.IsStrongKey("election/x"), Is.True);
Assert.That(hybrid.IsStrongKey("node/x"), Is.False);
Assert.That(hybrid.IsStrongKey(null!), Is.False, "a null key is treated as a bulk key");
}
[Test]
public async Task SetWithNullKeyThrowsAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong);
Assert.That(
async () => await hybrid.SetAsync(null!, ByteString.Empty).ConfigureAwait(false),
Throws.TypeOf<ArgumentNullException>());
}
[Test]
public async Task CustomStrongPrefixReplacesDefaultsAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
var prefixes = new ArrayOf<string>(s_stringValues1.AsMemory());
await using var hybrid = new HybridSharedKeyValueStore(bulk, strong, prefixes);
await hybrid.SetAsync("cas/x", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/y", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
(bool casInStrong, _) = await strong.TryGetAsync("cas/x").ConfigureAwait(false);
(bool nonceInBulk, _) = await bulk.TryGetAsync("nonce/y").ConfigureAwait(false);
Assert.That(casInStrong, Is.True, "the custom prefix routes to the strong store");
Assert.That(nonceInBulk, Is.True, "custom prefixes replace the defaults, so nonce/ is now a bulk key");
}
[Test]
public async Task OwnsStoresDisposesAsyncAndSyncBackendsAsync()
{
// bulk is an IDisposable backend, strong is an IAsyncDisposable
// backend, so disposing the hybrid exercises both dispose paths.
var bulk = new InMemorySharedKeyValueStore();
var strong = new RaftSharedKeyValueStore();
var hybrid = new HybridSharedKeyValueStore(bulk, strong, default, ownsStores: true);
await hybrid.SetAsync("node/1", ByteString.From(new byte[] { 1 })).ConfigureAwait(false);
await hybrid.SetAsync("nonce/a", ByteString.From(new byte[] { 2 })).ConfigureAwait(false);
await hybrid.DisposeAsync().ConfigureAwait(false);
// InMemorySharedKeyValueStore.Dispose clears its data, so a miss here
// proves the synchronous IDisposable backend was disposed.
(bool foundInBulk, _) = await bulk.TryGetAsync("node/1").ConfigureAwait(false);
Assert.That(foundInBulk, Is.False, "the synchronous IDisposable backend was disposed");
// The Raft backend disposes its owned consensus, so a subsequent
// mutation faults - proving the IAsyncDisposable backend was disposed.
Assert.That(
async () => await strong.SetAsync("nonce/b", ByteString.From(new byte[] { 3 })).ConfigureAwait(false),
Throws.InstanceOf<ObjectDisposedException>(), "the asynchronous IAsyncDisposable backend was disposed");
}
[Test]
public async Task DisposeIsIdempotentAsync()
{
using var bulk = new InMemorySharedKeyValueStore();
using var strong = new InMemorySharedKeyValueStore();
var hybrid = new HybridSharedKeyValueStore(bulk, strong);
await hybrid.DisposeAsync().ConfigureAwait(false);
Assert.That(async () => await hybrid.DisposeAsync().ConfigureAwait(false), Throws.Nothing);
}
[Test]
public void DefaultStrongKeyPrefixesExposesTheDefaults()
{
ArrayOf<string> defaults = HybridSharedKeyValueStore.DefaultStrongKeyPrefixes;
Assert.That(defaults.Count, Is.EqualTo(3));
Assert.That(defaults[0], Is.EqualTo("nonce/"));
Assert.That(defaults[1], Is.EqualTo("lease/"));
Assert.That(defaults[2], Is.EqualTo("election/"));
}
private static readonly string[] s_stringValues1 = ["cas/"];
}
}