218 lines
12 KiB
C#
218 lines
12 KiB
C#
using System.Linq.Expressions;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
|
public sealed class GrpcDataHotRouteContinuityTests
|
|
{
|
|
// Reflection keeps the red test buildable before the continuity snapshot API is introduced.
|
|
private sealed class SnapshotSource { public object? Current { get; set; } }
|
|
private static (DataConnectionDeploymentRuntime Runtime, SnapshotSource Source, Type SnapshotType) Create()
|
|
{
|
|
var snapshotType = typeof(DataConnectionDeploymentRuntime).Assembly.GetType(
|
|
"ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataConnectionConsumerRoleSnapshot");
|
|
var source = new SnapshotSource();
|
|
if (snapshotType is null)
|
|
return (new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4,
|
|
consumerMayAcquire: () => true), source, typeof(object));
|
|
source.Current = System.Activator.CreateInstance(snapshotType!, RedundancyMode.Hot, true, 1L);
|
|
var body = Expression.Convert(Expression.Property(Expression.Constant(source), nameof(SnapshotSource.Current)), snapshotType!);
|
|
var provider = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(RedundancyMode), snapshotType!), body,
|
|
Expression.Parameter(typeof(RedundancyMode), "artifactMode")).Compile();
|
|
var constructor = typeof(DataConnectionDeploymentRuntime).GetConstructors().Single(x =>
|
|
x.GetParameters().Any(p => p.Name == "consumerRoleSnapshot"));
|
|
var runtime = (DataConnectionDeploymentRuntime)constructor.Invoke(["node-a", "owner", new Security(), new Activator(), 4,
|
|
null, (Func<bool>)(() => true), true, provider]);
|
|
return (runtime, source, snapshotType!);
|
|
}
|
|
private static void Set(SnapshotSource source, Type type, RedundancyMode mode, bool eligible, long epoch) =>
|
|
source.Current = System.Activator.CreateInstance(type, mode, eligible, epoch);
|
|
private static DataConnection Definition() => new()
|
|
{
|
|
DataConnectionId = "link", ClusterId = "owner", Revision = 1, Enabled = true,
|
|
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "target",
|
|
ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = "secret",
|
|
SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Read, MaxMessageBytes = 65536,
|
|
MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2, MaxMonitoredItems = 16,
|
|
MaxPendingBytes = 65536, TimeoutMilliseconds = 5000
|
|
};
|
|
private static async Task<DataConnectionDeploymentLease> Acquire(DataConnectionDeploymentRuntime runtime)
|
|
{
|
|
for (var i = 0; i < 100; i++)
|
|
{
|
|
if (runtime.TryAcquire("link", out var lease)) return lease!;
|
|
await Task.Delay(20, TestContext.Current.CancellationToken);
|
|
}
|
|
throw new TimeoutException("Route did not become ready.");
|
|
}
|
|
[Fact]
|
|
public async Task Hot_eligible_role_transitions_preserve_the_existing_route_but_epoch_aba_invalidates_it()
|
|
{
|
|
var (runtime, source, type) = Create();
|
|
await using (runtime)
|
|
{
|
|
runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot));
|
|
using var lease = await Acquire(runtime);
|
|
runtime.NotifyConsumerRoleChanged();
|
|
lease.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
|
using (var retained = await Acquire(runtime)) retained.CancellationToken.ShouldBe(lease.CancellationToken);
|
|
// The current verdict is positive again, but the intervening Unknown/owner change
|
|
// changed the epoch even when its callback was missed.
|
|
Set(source, type, RedundancyMode.Hot, true, 2);
|
|
await Should.ThrowAsync<InvalidOperationException>(() => lease.GetCapabilitiesAsync(new(TimeSpan.FromSeconds(1), 1, 1024), TestContext.Current.CancellationToken));
|
|
runtime.NotifyConsumerRoleChanged();
|
|
lease.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
|
}
|
|
}
|
|
[Theory]
|
|
[InlineData(RedundancyMode.Warm)]
|
|
[InlineData(RedundancyMode.None)]
|
|
public async Task Host_effective_non_hot_mode_drains_even_when_artifact_is_hot(RedundancyMode mode)
|
|
{
|
|
var (runtime, source, type) = Create();
|
|
await using (runtime)
|
|
{
|
|
runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot));
|
|
using var lease = await Acquire(runtime);
|
|
Set(source, type, mode, true, 1);
|
|
runtime.NotifyConsumerRoleChanged();
|
|
lease.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
|
}
|
|
}
|
|
[Fact]
|
|
public async Task Retained_metadata_guard_survives_borrower_disposal_but_not_unobserved_epoch_loss()
|
|
{
|
|
var (runtime, source, type) = Create();
|
|
await using (runtime)
|
|
{
|
|
runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot));
|
|
var borrowed = await Acquire(runtime);
|
|
var clock = new ManualTimeProvider();
|
|
var cache = new ProjectedCatalogCache(4, 4, clock);
|
|
var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1);
|
|
var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)),
|
|
clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock);
|
|
var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping",
|
|
cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent);
|
|
borrowed.Dispose();
|
|
proof.IsValid.ShouldBeTrue();
|
|
Set(source, type, RedundancyMode.Hot, true, 2);
|
|
proof.IsValid.ShouldBeFalse();
|
|
proof.CaptureDiagnostics().RouteAlive.ShouldBeFalse();
|
|
}
|
|
}
|
|
[Theory]
|
|
[InlineData(RedundancyMode.Warm)]
|
|
[InlineData(RedundancyMode.None)]
|
|
public async Task Non_hot_retained_metadata_does_not_revive_after_missed_ineligible_transition(RedundancyMode mode)
|
|
{
|
|
var (runtime, source, type) = Create();
|
|
await using (runtime)
|
|
{
|
|
Set(source, type, mode, true, 1);
|
|
runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot));
|
|
var borrowed = await Acquire(runtime);
|
|
var clock = new ManualTimeProvider();
|
|
var cache = new ProjectedCatalogCache(4, 4, clock);
|
|
var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1);
|
|
var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)),
|
|
clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock);
|
|
var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping",
|
|
cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent);
|
|
borrowed.Dispose();
|
|
proof.IsValid.ShouldBeTrue();
|
|
Set(source, type, mode, false, 2);
|
|
proof.IsValid.ShouldBeFalse();
|
|
Set(source, type, mode, true, 3);
|
|
proof.IsValid.ShouldBeFalse();
|
|
}
|
|
}
|
|
[Fact]
|
|
public void Read_epoch_is_stable_between_known_roles_and_changes_on_unknown_and_owner_replacement()
|
|
{
|
|
var role = new RedundancyRoleView();
|
|
var owner = role.RegisterDataServingOwner();
|
|
role.PublishDataServingRole(owner, RedundancyRole.Primary, true);
|
|
var original = role.ReadEligibilityEpoch;
|
|
role.PublishDataServingRole(owner, RedundancyRole.Secondary, false);
|
|
role.ReadEligibilityEpoch.ShouldBe(original);
|
|
role.PublishDataServingRole(owner, null, false);
|
|
role.PublishDataServingRole(owner, RedundancyRole.Primary, true);
|
|
role.ReadEligibilityEpoch.ShouldBeGreaterThan(original);
|
|
var afterUnknown = role.ReadEligibilityEpoch;
|
|
role.RetireDataServingOwner(owner);
|
|
var replacement = role.RegisterDataServingOwner();
|
|
role.PublishDataServingRole(replacement, RedundancyRole.Primary, true);
|
|
role.ReadEligibilityEpoch.ShouldBeGreaterThan(afterUnknown);
|
|
}
|
|
[Fact]
|
|
public async Task Hot_retained_guard_reads_role_without_waiting_for_dispatch_fence()
|
|
{
|
|
var role = new RedundancyRoleView();
|
|
var owner = role.RegisterDataServingOwner();
|
|
role.PublishDataServingRole(owner, RedundancyRole.Primary, true);
|
|
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), new Activator(), 4,
|
|
consumerRoleSnapshot: mode =>
|
|
{
|
|
var observed = role.CaptureDataServingRole();
|
|
return new(mode, observed.Role is "Primary" or "Secondary", observed.ReadEligibilityEpoch);
|
|
});
|
|
runtime.Apply(new(1, "artifact-1", [Definition()], RedundancyMode.Hot));
|
|
using var borrowed = await Acquire(runtime);
|
|
var clock = new ManualTimeProvider();
|
|
var cache = new ProjectedCatalogCache(4, 4, clock);
|
|
var serving = new ServingIdentity("remote", "boot", "Primary", 1, 1, 1);
|
|
var remote = new MetadataAuthorityLease(serving, new MetadataLease(1, 1, TimeSpan.FromSeconds(15)),
|
|
clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, clock);
|
|
var proof = new BoundProjectionLease(remote, borrowed.CancellationToken, new Authority(), cache, "mapping",
|
|
cache.CaptureGeneration("mapping"), () => true, borrowed.RouteCurrent);
|
|
borrowed.Dispose();
|
|
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var held = Task.Run(() =>
|
|
{
|
|
using (role.DispatchFence.Enter())
|
|
{
|
|
entered.SetResult();
|
|
release.Task.GetAwaiter().GetResult();
|
|
}
|
|
}, TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
proof.IsValid.ShouldBeTrue();
|
|
}
|
|
finally { release.SetResult(); await held; }
|
|
}
|
|
private sealed class Authority : IDataMappedCatalogAuthority
|
|
{
|
|
public long CatalogEpoch => 1;
|
|
public long AuthorityEpoch => 1;
|
|
public bool IsActive => true;
|
|
}
|
|
private sealed class Security : IDataConnectionSecurityProvider
|
|
{
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new EmptyHandler()));
|
|
}
|
|
private sealed class EmptyHandler : HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => throw new InvalidOperationException("Unexpected network call.");
|
|
}
|
|
private sealed class Activator : IDataConnectionScopeActivator
|
|
{
|
|
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken) => Task.CompletedTask;
|
|
}
|
|
}
|